Search code examples
javaswinglistenerjcomponent

JCheckbox listener


I've just recently started learning code in Java. I encountered a problem with adding a listener.I have been struggling with this problem for an hour but I couldn't find the solution.Could someone make a look and see whats wrong please. Here's my code:

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import java.awt.HeadlessException;
import java.awt.event.ItemEvent;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MultiListenerFrame extends JFrame {

    JPanel panel;
    JLabel label;
    JCheckBox button1;
    JCheckBox button2;
    JCheckBox button3;

    public MultiListenerFrame() throws HeadlessException {
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        this.setSize(600,500);

        panel = new JPanel();
        panel.setLayout(new FlowLayout());
        add(BorderLayout.NORTH, panel);

        button1  = new JCheckBox("button1");
        button2  = new JCheckBox("button2");
        button3  = new JCheckBox("button3");
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);

        button1.addActionListener(this); // here is my problem 


    }
    public void itemStateChanged(ItemEvent e) {
        Object source = e.getItemSelectable();
        if(source == button1) {
            label.setText("Hello");
        } else if (source == button2) {
            label.setText("world");
        } else if(source == button23) {
            label.setText("!!!");
        }

    }

    public static void main(String[] args) {
        MultiListenerFrame frame = new MultiListenerFrame();
        frame.setVisible(true);
    }

}

Solution

  • You're not adding an ActionListener. this refers to your MultiListenerFrame class.

    Define a listener somewhere and add that:

    this.button1.addActionListener(new ActionListener() {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO something
        }
    });