I am new to java swing. I have pasted my code below for your reference,
I am trying to create 2 JRadioButtons in JFrame and if i click that JRadioButton it
should display 5 JCheckboxes for each JRadioButton in the same JFrame.
JRadiobutton is displaying now but if i click that JRadioButton "JCheckboxes" is not
displaying. please see my code below, if any changes need in my code, please do
accordingly.i am struggling for this.
MultipleFramesExample.java calling createMainView() in Mainview.java class
public class MultipleFramesExample extends JFrame {
public void fun()
{
MainView MV = new MainView();
MV.createMainView();
}
public static void main(String[] args) {
MultipleFramesExample ob=new MultipleFramesExample();
ob.fun();
}
}
Mainview.java creates Jframe and Buttons etc..
public class MainView extends JFrame implements ActionListener {
JFrame frame1;
MainView mV=null;
JCheckBox chinButton;
JRadioButton birdButton;
MultipleFramesExample ob=new MultipleFramesExample();
JPanel panel = new JPanel(new BorderLayout());
public void createMainView() {
mV = new MainView();
frame1 = new JFrame();
frame1.setTitle("Main View");
frame1.setSize(50,50);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
birdButton = new JRadioButton("click");
frame1.getContentPane().add(birdButton);
birdButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
Container contentPane = frame1.getContentPane();
contentPane.setLayout(new FlowLayout());
JCheckBox jb=new JCheckBox();
if (event.getActionCommand().equals(birdButton)) {
frame1.add(new JCheckBox("JIL1"));
frame1.add(new JCheckBox("JIL2"));
frame1.add(new JCheckBox("JIL3"));
frame1.add(new JCheckBox("JIL4"));
frame1.add(new JCheckBox("JIL5"));
frame1.setVisible(true);
//panel.add(jb, BorderLayout.PAGE_START);
// panel.getComponentCount();
}
}
public void fun1(){
}
}
Is it possible to create them like this?
Update: Here’s a working example:
Original post
You have some problems with your code:
JCheckBoxes whenever the button is clicked. If the user clicks it twice, more checkboxes would be created.frame1.add(new JCheckBox("JIL"));frame1.getContentPane().add(jb);Try the following steps:
Create and add all objects that you need for testing (
JRadioButton,JCheckBox) and make sure that they are both displayed (check Using Layout Managers and A Visual Guide to Layout Managers if you add both but do not see both).In your
ActionListener, use something likecheckBox.setVisible(radioButton.isSelected())to switch visibility of your checkBox according to the state of your radioButton.