Несколько JComboBox - PullRequest
       22

Несколько JComboBox

1 голос
/ 27 августа 2011

Хорошо, отображаются два jcombobox, один из которых представляет собой список городов, из которых отправляется рейс, а другой - список городов, в которые направляется рейс, когда пользователь выбирает параметр в обоих полях со списком. Из Парижа в Белфаст, у меня есть следующий код, но я не знаю, как добавить другой выбор, поскольку в данный момент он просто говорит, что вы летите из Парижа в.

        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);
        }   
        }

Ответы [ 3 ]

4 голосов
/ 28 августа 2011

здесь ваш SSCCE , но я изменил ваш ActionListener на ItemListener для JComboBox и упаковывает ваш основной метод в invokeLater () , изменено setBounds(int, int, int, int) как задание точно для LayoutManager, , JComponents возвращает размер для Контейнер верхнего уровня и т. д. .,

тогда

enter image description here

из кода

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();
            }
        });
    }
}
4 голосов
/ 28 августа 2011

Я переписал весь сценарий (извините) ...

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); }
        });
    }
}

Это должно делать то, что вы хотите. :)

1 голос
/ 15 декабря 2016

Проверьте этот фрагмент кода и посмотрите, как он работает тоже .

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) { } }

    }


}
...