I want to add item listener inside of an action listener, so that whenever the user presses the checkbox and clicks the buttons the frame displays a label whether the answer is true or not. Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KBC implements ItemListener {
JFrame f;
JLabel l;
JButton b;
JCheckBox k0;
JCheckBox k1;
JCheckBox k2;
JCheckBox k3;
JCheckBox k4;
JLabel z;
public static void main(String[] args) {
KBC u = new KBC();
u.go();
}
public void go() {
z = new JLabel("Nothing");
f = new JFrame("Hello");
l = new JLabel("q1- Ans is 3");
b = new JButton("Click");
k0 = new JCheckBox("hello1");
k1 = new JCheckBox("hello2");
k2 = new JCheckBox("hello3");
k3 = new JCheckBox("hello4");
k4 = new JCheckBox("hello5");
l.setFont(new Font("serif", Font.BOLD, 50));
b.addActionListener(new ButtonAction());
f.setLayout(null);
f.setSize(1024, 768);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l.setBounds(150, 100, 500, 100);
k0.setBounds(200, 300, 50, 100);
k1.setBounds(200, 320, 100, 100);
k2.setBounds(200, 340, 100, 100);
k3.setBounds(200, 360, 100, 100);
k4.setBounds(200, 380, 100, 100);
b.setBounds(600, 550, 100, 100);
f.add(l);
f.add(k0);
f.add(k1);
f.add(k2);
f.add(k3);
f.add(k4);
f.add(b);
f.add(z);
k0.setVisible(true);
k1.setVisible(true);
k3.setVisible(true);
k4.setVisible(true);
b.setVisible(true);
z.setVisible(true);
k2.setVisible(true);
l.setVisible(true);
}
@Override
public void itemStateChanged(ItemEvent eve) {
if (eve.getSource() == k3) {
z.setText("YOu are r8");
} else {
z.setText("YOu are rong");
}
}
}
class ButtonAction extends KBC implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
k0.addItemListener(new KBC());
k1.addItemListener(new KBC());
k2.addItemListener(new KBC());
k3.addItemListener(new KBC());
k4.addItemListener(new KBC());
}
}