Reputation: 151
Hello Im facing this problem in netbeans 8.1 when I run my simple swing application. My frame shows only one radio button and for second radio button when I select on that area it shows and when I deselect it disappears. Check the below images
When I run my swing application
When I click on the radio button area it shows
Source Code:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class MainClass {
private JFrame mainFrame;
private JRadioButton radStudent,radTeacher;
public MainClass(){ //Constructor of main class
prepareGUI();
}
public static void main(String arg[]){
MainClass main = new MainClass();
}
private void prepareGUI(){ //GUI
mainFrame = new JFrame("Select any one");
mainFrame.setSize(300,200);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
//Frame position set
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
mainFrame.setLocationRelativeTo(null);
//radio for employee
radStudent = new JRadioButton("Student");
radStudent.setBounds(10,10,100,20);
//radio for Teachers
radTeacher = new JRadioButton("Teacher");
radTeacher.setBounds(110,10,100,20);
mainFrame.add(radStudent);
mainFrame.add(radTeacher);
}
}
Thank you in advance!!
Upvotes: 1
Views: 67
Reputation: 140465
Thing is: you have to understand that the JFrame is using a LayoutManager to organize the items you add to it.
Changing your code to
mainFrame.add(radStudent, BorderLayout.PAGE_START);
mainFrame.add(radTeacher, BorderLayout.PAGE_END);
will give you a frame that shows the one button on top; and the other on the bottom of the window (because, by default, JFrame uses a BorderLayout to organize its children).
In other words: as soon as you want to use more than one component, you have to sit down first and think up how to organize those components. And then you select that LayoutManager, for example BorderLayout that provides the easiest way to get to that "structure" you decided to use.
Upvotes: 2