0

我试图在 JFrame 上放置 5 个按钮。四个按钮应该在第一行,第五个应该在第二行。但是这里所有的按钮都出现在一行中,第五个按钮的一半在面板之外。顺便说一句,如果我使用 frame.pack(); 我的框架变得比我预期的要小。我不想改变框架的大小。我想在第二行找到第五个。

import java.awt.GridBagLayout;
import java.awt.GridLayout;

import javax.swing.*;


public class test {

    public static void main(String[] args) {


        JFrame frame = new JFrame();
        frame.setBounds(100, 100, 529, 300);
        frame.getContentPane().setLayout(new GridLayout(1, 0, 0, 0));


        JPanel panel = new JPanel();
        frame.getContentPane().add(panel);
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));


        JButton btnNewButton_4 = new JButton("New button");
        panel.add(btnNewButton_4);

        JButton btnNewButton_3 = new JButton("New button");
        panel.add(btnNewButton_3);

        JButton btnNewButton = new JButton("New button");
        panel.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("New button");
        panel.add(btnNewButton_1);

        JButton btnNewButton_2 = new JButton("New button");
        panel.add(btnNewButton_2);


        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }

}
4

4 回答 4

3

四个按钮应该在第一行,第五个应该在第二行。

于 2013-04-18T13:57:57.693 回答
1

What I do is use null as the layout manager and place the components my self. A manager works well if you want your components to be relayed when the window is resized or you do not know the final size of applet etc

But most of the time that is not true or over kill

Instead just place the components on a grid by pixel using setBounds(x,y,width,height); Example:

    JFrame frame = new JFrame();
    frame.setBounds(100, 100, 529, 300);
    frame.getContentPane().setLayout(null);//over ride default
    Container c = frame.getContentPane();


    JButton btnNewButton_4 = new JButton("New button");
    c.add(btnNewButton_4);
    c.seBounds(4,10,40,25);

    JButton btnNewButton_3 = new JButton("New button 3");
    c.add(btnNewButton_3);
    c.seBounds(40,10,40,25);//...etc

Samples

于 2013-04-18T14:09:08.483 回答
1

您正在使用 BoxLayout,其中组件不会包装(查看 API 文档:http ://docs.oracle.com/javase/6/docs/api/javax/swing/BoxLayout.html )

关于尺寸,尝试使用 panel.setMinimumSize(Dimension d)

于 2013-04-18T13:58:09.123 回答
0

您还可以使用 setBounds(arg1 , arg2 , arg3 , arg4) 方法。使用它以获得更好的帮助。不使用布局管理器(绝对定位)

于 2015-04-14T18:08:01.243 回答