I have a requirement in java swing. I have two checkBox (C++ and Java).
When we click on C++ on the right-side I want to create one JLabel with two JCheckBox controls.
Then when I deselect the checkBox then the components to their right-side should be removed.
public class CheckBoxWithJLabel {
public static void main(String[] args) {
JFrame f= new JFrame("CheckBox Example");
JPanel leftPanel = new JPanel();
leftPanel.setBounds(40,80,200,200);
JPanel rightPanel = new JPanel();
rightPanel.setBounds(280, 80, 100, 30);
final ActionListener checkBoxActionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JCheckBox checkBoxType = (JCheckBox) actionEvent.getSource();
if (checkBoxType.isSelected()) {
System.out.println();
final JLabel label = new JLabel("Sonu");
label.setBounds(10, 50, 100, 30);
label.setText(checkBoxType.getText());
rightPanel.add(label);
f.add(rightPanel);
}else {
System.out.println("Unchecked");
}
}
};
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
leftPanel.add(checkbox1);
leftPanel.add(checkbox2);
checkbox1.addActionListener(checkBoxActionListener);
checkbox2.addActionListener(checkBoxActionListener);
f.add(leftPanel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Can anyone help me to solve this problem?
For Java Swing components, you use setVisible(true/false) to show and hide components. Below, I've made some changes to your sample to demonstrate this: