0

In GUI, I have two JComboBox where all the comboBox items are retrieved from two tables, which are title and time. In my current code, when the title is selected, displayDate(selected); will get called since I have implemented addActionListener in Select comboBox.

But this is not what I want. When this file is run, I want it straight away display the date based on the first item in Select JcomboBox. When the Select comboBox item changed, only the date changed. What would be the correct way to write?

  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

Edited

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


    }

}

I have added some code, but the Date still cannot directly display and I get a nullpointer error.

Latest Output

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)
John Joe
  • 12,412
  • 16
  • 70
  • 135

1 Answers1

1

Make your selectDate(...) a method of the BuyTicket class by taking it out of the ActionListener's scope. Then after you've done your first database search and have filled the first JComboBox, directly call this method, passing in the first item from the first JComboBox.

i.e., change this:

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) {
                // ...
            }
        });
        // ...
    }
}

to this:

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

As a side recommendation, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.


Side recommendation 2: you will want to do all database searches from within a background thread, such as a SwingWorker. You will want to use a call back mechanism, such as a PropertyChangelistener, to notify you when the worker is done, so you can extract and display the data that it has collected. For example:

For more on this, please check out the tutorial -- Lesson: Concurrency in Swing


Side recommendation 3: You really don't want to have code like this:

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

At least print out the stacktrace (e.g., e.printStacktrace();) so you'll know what exceptions have occurred, if any. Also, you should catch specific exceptions not the over-broad Exception.


Regarding:

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)

You've now got a totally new and distinct problem. Please indicate for us which line is BuyTicket.java:131 since there is a variable on that line that is null, and you're trying to use as if it references an object. The key to debugging this is to look critically at the line, to see which variable is null or to use a debugger or println's to help figure out which one is null, and then fix your code so that it's no longer null. See: 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

So the Date JComboBox is null, and if you look at the code it's obvious why, and obvious how to fix it -- create it in the constructor, not in the ActionListener.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Sir I follow your suggestions but the date still display nothing. It still requires me to select the item in JComboBox first then only display the date. – John Joe Jun 26 '16 at 15:33
  • Line `BuyTicket.java:131` is `Date.removeAllItems();`. The error seems coming from displayDate(getMovie);,the new code I just added. – John Joe Jun 27 '16 at 15:25
  • Do you mean create the function in constructor ? – John Joe Jun 27 '16 at 15:32
  • @JohnJoe: I'm not sure what you mean by "create the function" but bottom line is a variable has to refer to a valid object before you use it. Here is where you play around with your code and see if you can fix it based on what you know. Good luck. – Hovercraft Full Of Eels Jun 27 '16 at 15:51
  • Sir can you specify what did you meant by _create it in the constructor, not in the ActionListener_ ? – John Joe Jun 27 '16 at 15:56
  • Look at where you currently call `new JComboBox()` and assign it to the Date variable. But most important *think* where the variable gets assigned an object. You must do the assignment ***before*** using the variable. It's common sense. – Hovercraft Full Of Eels Jun 27 '16 at 15:58
  • Thanks Sir, I add the ` Date JComboBox` before function `displayDate(getMovie);` get called and the problem finally fixed. – John Joe Jun 27 '16 at 16:05