Java GUI布局不能完全正确

时间:2014-05-28 03:16:51

标签: java user-interface layout

我尝试了许多不同的布局,但没有一个给我预期的效果。

我想要这样的事情:

+-----------------------------+
         Centered Text
+-------+
|Button |
+-------+
+-----------------------------+

在HTML中,它可能如下所示:

<p align="center">Some text</p>
<input type="button" value="Press"/>

我遇到的麻烦是某些布局(BorderLayout)它喜欢调整按钮大小以适应。其他布局(Boxlayout和GroupLayout)将执行以下操作:

+-----------------------------+
         Centered Text
               +-------+
               |Button |
               +-------+
+-----------------------------+

即使我将JLabel与CENTER对齐并且Button与LEFT对齐。

非常感谢我的助手。

3 个答案:

答案 0 :(得分:2)

有许多布局可以实现这一点,事实上,您甚至可以一起使用BorderLayoutFlowLayout来执行此操作,但此示例仅使用{{1 }}

enter image description here

GridBagLayout

查看Laying Out Components Within a Container了解更多示例和详细信息

答案 1 :(得分:1)

FlowLayout(int align)允许您定义理由。默认为CENTER。如果您只是左对齐包含按钮的面板的FlowLayout,则无需手动使用GridBagLayout即可。 NetBeans提供了一个出色的GridBagLayout自定义程序,但您不想触及它自动生成的代码。

enter image description here

import javax.swing.*;
import java.awt.*;

public class MyLooks extends JFrame {

    public MyLooks() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        p = new JPanel(new GridLayout(2, 1));
        p1 = new JPanel();
        p2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        myLabel = new JLabel("this is a label");
        myButton = new JButton("press");
        p1.add(myLabel);
        p2.add(myButton);
        p.add(p1);
        p.add(p2);
        setContentPane(p);
        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MyLooks().setVisible(true);
            }
        });
    }

    private JLabel myLabel;
    private JButton myButton;
    private JPanel p, p1, p2;
}

答案 2 :(得分:1)

虽然MadProgrammer和Costis Aivalis已经回答了你的问题,但这里也是MigLayout的回答:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import net.miginfocom.swing.MigLayout;

public class MigLayoutDemo {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    JLabel label = new JLabel("Centered text");
    JButton button = new JButton("Button");

    public MigLayoutDemo() {
        panel.setLayout(new MigLayout());
        label.setHorizontalAlignment(JLabel.CENTER);
        panel.add(label, "wrap, pushx, growx");
        panel.add(button);

        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MigLayoutDemo::new);
    }

}

同样的效果,但与GridBagLayout的情况不同,这种方法不那么冗长,我个人认为MigLayout更容易使用。

enter image description here