Question

I am new to Java; but I'm having a blast. I feel like I'm missing something really simple; but I can't figure it out.

I want the RadioButtons to be displayed inside the JFrame."

public class HelloWorldFrame extends JFrame
{
    private TitledBorder title;

    public HelloWorldFrame()
    {
        super("Hello World!                  ");
        JFrame helloWorld = new JFrame();
        JLabel label = new JLabel();
        title = BorderFactory.createTitledBorder("Language");
        title.setTitleJustification(TitledBorder.LEFT);
        label.setBorder(title);
        add(label);

        setSize(300, 200);

        JRadioButton button1 = new JRadioButton("English");
        JRadioButton button2 = new JRadioButton("French");
        JRadioButton button3 = new JRadioButton("Spanish");
        ButtonGroup bG = new ButtonGroup();
        bG.add(button1);
        bG.add(button2);
        bG.add(button3);
        label.add(button1);
        label.add(button2);
        label.add(button3);
        helloWorld.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}


//The main class starts here

public class HelloWorldApp
{
    public static void main(String[] args)
    {
        JFrame helloWorld = new HelloWorldFrame();
        helloWorld.setVisible(true);
    }

}
Was it helpful?

Solution

The first question is why? Why do you want to add the radio buttons to a JLabel?

Having said that, you can set the labels layout manager to something other then it's default value of null...

label.setLayout(new FlowLayout());
label.add(button1);
label.add(button2);
label.add(button3);

Next...your class extends from JFrame, but in your constructor, you are creating another JFrame, this means that when you do...

JFrame helloWorld = new HelloWorldFrame();
helloWorld.setVisible(true);

Nothing will be displayed, because nothing has been added to the frame.

Instead, make your class extend from something like JFrame and then add that to your JFrame in main

Updated

I just did some testing and doing this (adding buttons to a label) won't work well, as the JLabel calculates it's preferred size based on the text and icon, not it's contents (like something like JPanel would)...just saying...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top