Múltiples JComboBox

Ok, hay dos jcombobox mostrados, uno es una lista de ciudades desde donde sale un vuelo y otro es una lista de ciudades a las que va un vuelo cuando un usuario selecciona una opción de ambos cuadros combinados Quiero que muestre que estás volando de París a Belfast Tengo el siguiente código, pero no sé cómo agregar otra selección, ya que en este momento solo dice que estás volando de París a.

        if(e.getSource() == ownerList )
        {
            JComboBox cb = (JComboBox)e.getSource();
            String ownerName = (String)cb.getSelectedItem();
             if(ownerName.equals("Paris"))
        {
            text9.setText(ownerName);
            int flag = 10;
            drawApp(flag);
        }   
        }

        if(e.getSource() == cityList )
        {
            JComboBox cb = (JComboBox)e.getSource();
            String cityName = (String)cb.getSelectedItem();
             if(cityName.equals("Belfast"))
        {
            text10.setText(cityName);
            int flag = 10;
            drawApp(flag);
        }   
        }

preguntado el 27 de agosto de 11 a las 19:08

si implementa ActionListener para JComboBox (), su pregunta es un candidato real para el lector de mentes más profundo y con batería nueva en su globo mágico -

Lo siento, sí, esto en público void actionPerformed (ActionEvent e) {} -

3 Respuestas

He reescrito todo el guión (lo siento) ...

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class FlightBooker extends JFrame implements ActionListener {
    FlightBooker() {
        super("Book a Flight!");
        JLabel fromLabel = new JLabel("Current Location:");
        JComboBox fromLocations = new JComboBox();
        fromLocations.addItem("Paris");
        //fromLocations.addItem(someLocation);
        //...
        JLabel toLabel = new JLabel("Destination:");
        JComboBox destinations = new JComboBox();
        destinations.addItem("Belfast");
        //destinations.addItem(someLocation);
        //...
        JButton okButton = new JButton("OK");
        JLabel status = new JLabel("");
        add(fromLabel);
        add(fromLocations);
        add(toLabel);
        add(destinations);
        okButton.addActionListener(this);
        add(okButton);
        add(status);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }

    public void actionPerformed(ActionEvent event) {
        Object from = fromLocations.getSelectedItem();
        String FROM = from.toString();
        Object to = destinations.getSelectedItem();
        String TO = to.toString();
        status.setText("You're flying from " + FROM + "to " + TO + ".");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() { new FlightBooker().setVisible(true); }
        });
    }
}

Esto debería hacer lo que quieras. :)

Respondido 28 ago 11, 00:08

aquí está tu SSCCE, pero cambié tu ActionListener a ItemListener para JComboBoxy envuelve su método principal en invokeLater ()cambiado setBounds(int, int, int, int) como trabajo exactamente para LayoutManager, que JComponents devuelve Tamaño para Contenedor de nivel superior etcétera ...,

luego

enter image description here

del código

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComboBoxListeners {

    private JFrame f;
    private JComboBox flyFromCombo;
    private JComboBox flyToCombo;
    private JLabel tripLabel = new JLabel();
    private Object[] itemsFrom;
    private Object[] itemsTo;

    public ComboBoxListeners() {
        itemsFrom = new Object[]{"-", "First - From", "Second - From", "Third - From"};
        itemsTo = new Object[]{"-", "First - To", "Second - To", "Third - To"};
        //flyFromCombo.setPrototypeDisplayValue("################################################");
        flyFromCombo = new JComboBox(itemsFrom);
        flyFromCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if ((e.getStateChange() == ItemEvent.SELECTED)) {
                    String str = flyFromCombo.getSelectedItem().toString();
                    String str1 = flyToCombo.getSelectedItem().toString();
                    setLabelText(str, str1);
                }
            }
        });
        flyToCombo = new JComboBox(itemsTo);
        flyToCombo.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if ((e.getStateChange() == ItemEvent.SELECTED)) {
                    String str = flyFromCombo.getSelectedItem().toString();
                    String str1 = flyToCombo.getSelectedItem().toString();
                    setLabelText(str, str1);
                }
            }
        });
        tripLabel.setPreferredSize(new Dimension(400, 30));
        f = new JFrame("ComboBox ItemListeners");
        f.setLayout(new GridLayout(0, 1, 15, 15));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(flyFromCombo);
        f.add(flyToCombo);
        f.add(tripLabel);
        f.setLocation(150, 150);
        f.pack();
        f.setVisible(true);
    }

    private void setLabelText(String str1, String str2) {
        String textForLabel = "";
        String helpStringFirst = str1.trim();
        if (helpStringFirst != null && helpStringFirst.length() > 0) {
            if (!helpStringFirst.equals("-")) {
                textForLabel = "Flight No57. from :   " + helpStringFirst;
            } else {
                textForLabel = "Flight from Un-Know :   ";
            }
        }
        String helpStringSecond = str2.trim();
        if (helpStringSecond != null && helpStringSecond.length() > 0) {
            if (!helpStringSecond.equals("-")) {
                textForLabel = textForLabel + "   --> to :   " + helpStringSecond;
            } else {
                textForLabel += "   to :   Un-Know    ";
            }
        }
        final String pushTextForLabel = textForLabel;
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                tripLabel.setText(pushTextForLabel);
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboBoxListeners comboBoxListeners = new ComboBoxListeners();
            }
        });
    }
}

Respondido 28 ago 11, 00:08

Consulte este fragmento de código y mira como funciona tambien.

package lca;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class combo extends JFrame {
Connection connection = null;
PreparedStatement prepared = null;
ResultSet rs = null;
 JComboBox<String> comboBox,comboBox_1,comboBox_2;

 String sel1 , sel2;

 public combo() {
    getContentPane().setLayout(null);

     comboBox = new JComboBox<String>();


    comboBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            sel1 = (String) comboBox.getSelectedItem();
            popcombo1();
            comboBox_1.setSelectedIndex(-1);
        }
    });
    comboBox.setBounds(41, 77, 146, 20);
    getContentPane().add(comboBox);

    comboBox_1 = new JComboBox<String>();
    comboBox_1.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            sel2 = (String) comboBox_1.getSelectedItem();
            popcombo2();
        }
    });
    comboBox_1.setBounds(41, 108, 146, 20);
    getContentPane().add(comboBox_1);

    comboBox_2 = new JComboBox<String>();
    comboBox_2.setBounds(41, 139, 146, 20);
    getContentPane().add(comboBox_2);

    JButton btnLoad = new JButton("Load");
    btnLoad.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            try {
                String sql1 = "SELECT DISTINCT Name FROM Project_info  " ;
                Class.forName("org.sqlite.JDBC");
                 Connection connection2 =        DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Nitesh\\Desktop\\SM\\Project.sqlite");


                prepared = connection2.prepareStatement(sql1);
                rs = prepared.executeQuery();
                while(rs.next())
                {
                    String name  = rs.getString("Name");
                     comboBox.addItem(name);
                }
                connection2.close();}
                catch(Exception e3)
                {
                    System.err.println( e3.getClass().getName() + ": " + e3.getMessage() );
                }

            finally {
                try{
                rs.close(); prepared.close();
                //connection2.close(); 
                }
                catch(Exception e1) { } }
            comboBox.setSelectedIndex(-1); 
            }



    });
    btnLoad.setBounds(41, 11, 89, 23);
    getContentPane().add(btnLoad);
}

public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Throwable e) {
        e.printStackTrace();
    }
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                combo frame = new combo();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

  }
    public void popcombo1() {
    comboBox_1.removeAllItems();
     try {
        String sql1 = "SELECT DISTINCT Pro_cat FROM Project_info where Name  = '" +sel1 +  "'" ;
        Class.forName("org.sqlite.JDBC");
         Connection connection2 = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Nitesh\\Desktop\\SM\\Project.sqlite");


        prepared = connection2.prepareStatement(sql1);
        rs = prepared.executeQuery();
        while(rs.next())
        {
            String name  = rs.getString("Pro_cat");
             comboBox_1.addItem(name);
        }
        connection2.close();}
        catch(Exception e3)
        {
            System.err.println( e3.getClass().getName() + ": " + e3.getMessage() );
        }

    finally {
        try{
        rs.close(); prepared.close();
        //connection2.close(); 
        }
        catch(Exception e1) { } }
    comboBox_1.setSelectedIndex(-1);
    }
  public void popcombo2() {
    comboBox_2.removeAllItems();
    try {
        String sql1 = "SELECT DISTINCT Sub_cat FROM Project_info where Pro_cat = '" +sel2 +  "' AND Name = '"+ sel1+ "'" ;
        Class.forName("org.sqlite.JDBC");
         Connection connection2 = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Nitesh\\Desktop\\SM\\Project.sqlite");


        prepared = connection2.prepareStatement(sql1);
        rs = prepared.executeQuery();
        while(rs.next())
        {
            String name  = rs.getString("Sub_cat");
             comboBox_2.addItem(name);
        }
        connection2.close();}
        catch(Exception e3)
        {
            System.err.println( e3.getClass().getName() + ": " + e3.getMessage() );
        }

    finally {
        try{
        rs.close(); prepared.close();
        //connection2.close(); 
        }
        catch(Exception e1) { } }

    }


}

Respondido el 15 de diciembre de 16 a las 18:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.