Swing中的FlowLayout

KAK*_*KAK 5 java layout swing

这是我的布局.

在此输入图像描述

两个单选按钮应位于欢迎标签下方.

像这样:

__________________________
|                        | 
|        WELCOME         |
|         *  *           |
|                        |
|                        |
|                        |
|________________________|
Run Code Online (Sandbox Code Playgroud)

两个星号是单选按钮.

我的代码:

northpanel.setLayout(new FlowLayout(FlowLayout.CENTER));
northpanel1.setLayout(new FlowLayout(FlowLayout.CENTER));


northpanel.add(welcome);  //this welcome text label

northpanel1.add(r1);   //this radio 1
northpanel1.add(r2);   //this radio 2


add(northpanel,BorderLayout.NORTH);
add(northpanel1,BorderLayout.NORTH);
Run Code Online (Sandbox Code Playgroud)

Rad*_*zea 5

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

public class StackOverflow14837740
{
    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            @Override
            public void run ()
            {
                createAndShowGUI ();
            }
        });
    }

    private static void createAndShowGUI ()
    {
        JFrame frame = new JFrame ();
        frame.setLayout (new BorderLayout ());
        frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

        JPanel northPanel = new JPanel (new GridLayout (2, 1));

        JPanel welcomePanel = new JPanel (new FlowLayout (FlowLayout.CENTER));      
        welcomePanel.add (new JLabel ("Welcome"));

        northPanel.add (welcomePanel);

        JPanel radioPanel = new JPanel (new FlowLayout (FlowLayout.CENTER));

        JRadioButton button1 = new JRadioButton ("Button 1", true);
        JRadioButton button2 = new JRadioButton ("Button 2", false);

        ButtonGroup group = new ButtonGroup ();
        group.add (button1);
        group.add (button2);

        radioPanel.add (button1);
        radioPanel.add (button2);

        northPanel.add (radioPanel);

        JPanel middlePanel = new JPanel (new GridLayout (3, 3));

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                middlePanel.add (new JButton ("Button " + i + j));
            }
        }

        JPanel southPanel = new JPanel (new FlowLayout (FlowLayout.CENTER));

        southPanel.add (new JLabel ("Whose turn:"));
        southPanel.add (new JButton ("Reset"));

        frame.add (northPanel, BorderLayout.NORTH);
        frame.add (middlePanel, BorderLayout.CENTER);
        frame.add (southPanel, BorderLayout.SOUTH);

        frame.pack ();
        frame.setVisible (true);
    }
}
Run Code Online (Sandbox Code Playgroud)

它看起来像这样(虽然你必须稍微调整一下):

PRINTSCREEN


tra*_*god 3

northpanel和添加northpanelpanel具有GridLayout(0, 1)然后

add(panel, BorderLayout.NORTH);
Run Code Online (Sandbox Code Playgroud)