简体   繁体   中英

I want 2 JLabels to show on the same JFrame in Java

I can't get the JLabel pieces to both show up on the same JFrame. I've tried resizeing; but it didn't work. Do I need to place the JLabel's in a JPanel? I want both JLabels' to show on the same JFrame. Any help is appreciated. Thanks.

public class HelloWorldFrame extends JFrame
{
    private TitledBorder title;
    private TitledBorder title2;

    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");

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

        JLabel label2 = new JLabel();
        title2 = BorderFactory.createTitledBorder("Greeting");
        title2.setTitleJustification(TitledBorder.LEFT);
        label2.setBorder(title2);
        label2.setSize(100, 100);
        add(label2);

        helloWorld.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

//The main begins below

import javax.swing.JFrame;

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

}

您需要示例中的布局管理器。

The structure you should have is : JFrame > JPanel > JLabel .

JFrame frame = new JFrame();
JPanel panel = new JPanel();

JLabel label_1 = new JLabel("some text");
JLabel label_2 = new JLabel("other text");

panel.add(label_1);
panel.add(label_2);

frame.add(panel);
frame.pack();
frame.setVisible(true);

In your code you have some JButton : add them to the JPanel , not to the JLabel !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM