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

时间:2016-06-26 14:51:55

标签: java mysql swing nullpointerexception actionlistener

在GUI中,我有两个JComboBox,其中所有的comboBox项都是从两个tables中检索到的,这些项是标题时间。在我当前的代码中,当选择标题时,我会调用displayDate(selected);,因为我在选择addActionListener中实施了comboBox

但这不是我想要的。运行此文件时,我希望它立即根据选择JcomboBox中的第一项显示日期。选择组合框项目更改时,仅更改日期。什么是正确的写作方式?

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


    }
        });
    }

enter image description here

被修改

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$2.mouseClicked(HomePage.java:151)
    at java.awt.Component.processMouseEvent(Unknown Source)

1 个答案:

答案 0 :(得分:1)

将你的selectDate(...)作为BuyTicket类的一个方法,将其从ActionListener的范围中取出。在您完成第一次数据库搜索并填充第一个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。变量名都应以较低的字母开头,而类名以大写字母开头。了解并遵循这一点将使我们能够更好地理解您的代码,并使您能够更好地理解其他代码。

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

有关详情,请查看教程 - 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$2.mouseClicked(HomePage.java:151)
    at java.awt.Component.processMouseEvent(Unknown Source)

你现在遇到了一个全新而鲜明的问题。请为我们指出哪一行是BuyTicket.java:131,因为该行上的变量为空,并且您尝试使用它就像引用一个对象一样。调试这个的关键是仔细查看该行,查看哪个变量为null或使用调试器或println来帮助确定哪一个为null,然后修复代码以使其成为“' s不再为空。请参阅:What is a NullPointerException, and how do I fix it?

  

BuyTicket.java:131Date.removeAllItems();。错误似乎来自displayDate(getMovie);,刚刚添加的新代码

所以Date JComboBox为null,如果你查看代码,它显而易见的原因,以及显而易见的修复方法 - 在构造函数中创建它,而不是在ActionListener中创建它。