Search code examples
javaswingitemlistener

Java - ItemListener not listening to my components?


I took a segment of my program and put the code here. Basically the issue is that the item listener method isnt being called. Here if the user selects the right answer and presses "submit" an actionlistener method will tell him/her if they got the answer right.

static boolean answer = false; // returns this as true if user got question right

public void QuizPanel() {
    QuizPanel = new JPanel();
    QuizPanel.setLayout(null); // default layout

    JLabel label = new JLabel( "True/False- Java is Object Orientated?");
    label.setBounds(10, 50, 400, 20);
    QuizPanel.add(label);

    option1 = new JCheckBox("True"); 
    option1.setSelected(false);
    option1.setBounds(10, 70, 120, 40);                         
    QuizPanel.add(option1);
    option1.addItemListener(this); // Adds a item listener

    option2 = new JCheckBox("False");
    option2.setSelected(false);
    option2.setBounds(40, 70, 120, 40);
    QuizPanel.add(option2);
    option2.addItemListener(this);

    ///////////////////////////////////////

    JButton submit = new JButton("SUBMIT ANSWER:");
    submit.setBounds(10, 100, 150, 20);
    QuizPanel.add(submit);

    submit.addActionListener(new ActionListener() { // Action Listener      
        public void actionPerformed(ActionEvent evt2) {
            System.out.println ("Your answer is " + answer); // Got it right?
        }
    });
}

public void itemStateChanged1(ItemEvent e1) { 
    Object source = e.getItemSelectable();          
    if (source == option1) { 
        answer = true;
    } else {
        //nothing- stays false
    }       
}

Nothing happens and it doesn't tell the user if he/she got it right/wrong.


Solution

  • QuizPanel = new JPanel();
    

    Use standard Java naming conventions. Variable names should not start with an upper case character:

    QuizPanel.setLayout(null);
    ...
    label.setBounds(10, 50, 400, 20);
    

    Don't use a null layout and setBounds(). Swing was designed to be used with a Layout Manager.

    public void itemStateChanged1(ItemEvent e1) throws IOException
    

    I don't know how your code compiles. You are implementing the wrong method. Also, why would an ItemListener throw an IOException?

    Too many little mistakes to guess what you are doing wrong. Post a proper SSCCE.