topper1309 topper1309 - 11 months ago 46
Java Question

My JRadioButton does not shows when I run but when I click on that area it shows

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
public static void main(String arg[]){
MainClass main = new MainClass();

private void prepareGUI(){ //GUI
mainFrame = new JFrame("Select any one");

//Frame position set
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;

//radio for employee
radStudent = new JRadioButton("Student");

//radio for Teachers
radTeacher = new JRadioButton("Teacher");



Thank you in advance!!

Answer Source

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.