根据 JComboBox 中的第一项显示项目

Display the item based on the first item in JComboBox

在 GUI 中,我有两个 JComboBox,其中所有组合框项目都是从两个 tables 中检索的,它们是 title时间。在我当前的代码中,当我选择标题时,displayDate(selected);将被调用,因为我已经在Select comboBox中实现addActionListener

但这不是我想要的。当此文件为 运行 时,我希望它立即根据 Select JcomboBox 中的第一项显示日期。当 Select comboBox 项目发生变化时,只有日期发生了变化。什么是正确的写作方式?

  public class BuyTicket {  
    static JFrame frame;
    JLabel title,lblMainDate,selectMovie,dateOfShow;
    JComboBox Select,Date;

    public JPanel createContentPane() throws IOException
    {

        title = new JLabel("CYBER CINEMA");
        Select = new JComboBox();
        Select.setLocation(115,90);
        Select.setSize(175, 20);
        try {   
            DatabaseConnection db=new DatabaseConnection();
            Connection connect=db.getConnection();
            String sql="Select title FROM movie";
            PreparedStatement ps=connect.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
            String name = rs.getString("title");
            Select.addItem(name);         
        }

    } catch (Exception e) {
        System.out.println("null");
    }


        Select.addActionListener(new ActionListener()
        {
    public void actionPerformed(ActionEvent event)
        {
         JComboBox comboBox=(JComboBox) event.getSource();
         Object selected = Select.getSelectedItem();
         displayDate(selected);
        }

    private void displayDate(Object selected) {
        // TODO Auto-generated method stub
          try { 
                Date.removeAllItems();
                DatabaseConnection db=new DatabaseConnection();
                Connection connect=db.getConnection();
                String sql="Select date FROM movie WHERE title = ?";
                PreparedStatement ps=connect.prepareStatement(sql);
                ps.setObject(1, selected);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                String date1 = rs.getString("date");
                DefaultComboBoxModel model = (DefaultComboBoxModel)Date.getModel();
                if (model.getIndexOf(date1) == -1)
                {
                    Date.addItem(date1);
                }

            }

        } catch (Exception e) {
            System.out.println("null");
        }


    }
        });
    }

已编辑

public class BuyTicket {

    static JFrame frame;
    JLabel title,lblMainDate,selectMovie,dateOfShow;
    JComboBox Select,Date;

    public JPanel createContentPane() throws IOException
    {
        Select = new JComboBox();
        Select.setLocation(115,90);
        Select.setSize(175, 20);
        try {   
            DatabaseConnection db=new DatabaseConnection();
            Connection connect=db.getConnection();
            String sql="Select title FROM movie";
            PreparedStatement ps=connect.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
            String name = rs.getString("title");
            Select.addItem(name);         
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

        Select.addActionListener(new ActionListener()
        {
    public void actionPerformed(ActionEvent event)
        {
         JComboBox comboBox=(JComboBox) event.getSource();
         Object selected = Select.getSelectedItem();
         displayDate(selected);
        }
        });

        String getMovie = (String)Select.getSelectedItem(); // New code added, directly display the Date JComboBox items 
        System.out.println(getMovie);
        displayDate(getMovie);
        Date = new JComboBox();
        Date.setLocation(115,140);
        Date.setSize(175, 20);
    }

    private void displayDate(Object selected) {
        // TODO Auto-generated method stub
          try { 
                Date.removeAllItems();
                DatabaseConnection db=new DatabaseConnection();
                Connection connect=db.getConnection();
                String sql="Select date FROM movie WHERE title = ?";
                PreparedStatement ps=connect.prepareStatement(sql);
                ps.setObject(1, selected);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                String date1 = rs.getString("date");
                DefaultComboBoxModel model = (DefaultComboBoxModel)Date.getModel();
                if (model.getIndexOf(date1) == -1)
                {
                    Date.addItem(date1);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}

我添加了一些代码,但是日期还是不能直接显示,报nullpointer错误

最新输出

Angry Bird
java.lang.NullPointerException
    at gui.BuyTicket.displayDate(BuyTicket.java:131)
    at gui.BuyTicket.createContentPane(BuyTicket.java:87)
    at gui.BuyTicket.createAndShowGUI(BuyTicket.java:115)
    at gui.HomePage.mouseClicked(HomePage.java:151)
    at java.awt.Component.processMouseEvent(Unknown Source)

通过将您的 selectDate(...) 移出 ActionListener 的范围,使它成为 BuyTicket class 的方法。然后在完成第一次数据库搜索并填充第一个 JComboBox 后,直接调用此方法,传入第一个 JComboBox 中的第一项。

即,更改为:

public class BuyTicket {
    //...

    public JPanel createContentPane() throws IOException {
        // ...
        Select.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // ...
            }

            // within addActionListener scope
            private void displayDate(Object selected) {
                // ...
            }
        });
        // ...
    }
}

对此:

public class BuyTicket {
    //...

    public JPanel createContentPane() throws IOException {
        // ...
        Select.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // ...
            }

        });
        // ...
    }

    // within class scope
    private void displayDate(Object selected) {
        // ...
    }
} 

作为附带建议,您将想要学习和使用 Java naming conventions。变量名称应全部以小写字母开头,而 class 名称应以大写字母开头。了解这一点并遵循这一点将使我们能够更好地理解您的代码,并使您能够更好地理解其他人的代码。


侧面建议 2:您将希望从后台线程(例如 SwingWorker)中执行所有数据库搜索。您将希望使用回调机制(如 PropertyChangelistener)在 worker 完成时通知您,以便您可以提取并显示它收集的数据。例如:

  • Get and send messages with Java Threads
  • Dialog isn't responsive while SwingWorker works in the background
  • Repeat SwingWorker

有关此的更多信息,请查看教程 -- Lesson: Concurrency in Swing


侧面建议 3:您真的不想拥有这样的代码:

} catch (Exception e) {
    System.out.println("null");
}

至少打印出堆栈跟踪(例如,e.printStacktrace();),这样你就会知道发生了什么异常,如果有的话。此外,您应该捕获 特定的 异常,而不是过于宽泛的 Exception.


关于:

java.lang.NullPointerException
    at gui.BuyTicket.displayDate(BuyTicket.java:131)
    at gui.BuyTicket.createContentPane(BuyTicket.java:87)
    at gui.BuyTicket.createAndShowGUI(BuyTicket.java:115)
    at gui.HomePage.mouseClicked(HomePage.java:151)
    at java.awt.Component.processMouseEvent(Unknown Source)

您现在遇到了一个全新且独特的问题。请为我们指明哪一行是 BuyTicket.java:131,因为该行上有一个变量为 null,而您正试图将其用作引用对象。调试它的关键是仔细查看该行,查看哪个变量为空,或者使用调试器或 println 来帮助找出哪个为空,然后修复您的代码,使其不再为空。参见:What is a NullPointerException, and how do I fix it?


Line BuyTicket.java:131 is Date.removeAllItems();. The error seems coming from displayDate(getMovie);,the new code I just added

因此 Date JComboBox 为 null,如果您查看代码,就会很明显地知道原因以及如何修复它——在构造函数中创建它,而不是在 ActionListener 中创建它。