4

如何将这些 JComponents 像内容窗格中心的表单一样对齐...使用 Swing

        panel1.add(l1);
        panel1.add(c1);
        panel1.add(l2);
        panel1.add(c2);
        panel1.add(b4);
        panel1.add(b5);
        frame1.getContentPane().add(panel1);

请帮我

4

4 回答 4

6

你先阅读在容器中布局组件教程怎么样?我滥用这句话但是,总是有不止一种方法可以给猫剥皮


这是一个在实例上使用BoxLayoutand的多余示例-setAlignmentX(...)JComponent

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

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        panel.add(new DisabledJButton());
        panel.add(new DisabledJButton());
        panel.add(new DisabledJButton());
        panel.add(new DisabledJButton());
        panel.add(new DisabledJButton());

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class DisabledJButton extends JButton{
        public DisabledJButton(){
            super("Disabled");
            setEnabled(false);
            setAlignmentX(Component.CENTER_ALIGNMENT);
        }
    }
}

在此处输入图像描述

于 2011-08-09T18:38:40.047 回答
2

检查SpringLayout是否符合您的需求。如果没有,可能GridBagLayout会做。

这是一个使用 SpringLayout 进行简单表单式布局的示例。

于 2011-08-09T18:46:26.293 回答
1

我建议使用 boxlayout 管理器。在没有 IDE 帮助的情况下使用布局管理器需要一些时间和练习。更多信息可以在这里找到:http: //download.oracle.com/javase/tutorial/uiswing/layout/box.html

于 2011-08-09T18:40:14.157 回答
0

如果一切都失败了,您可以随时尝试:http ://code.google.com/intl/nl-NL/javadevtools/wbpro/layoutmanagers/swing/index.html

窗口生成器给我留下了深刻的印象,它生成漂亮而干净的代码,并且很容易集成到 eclipse 中。

于 2011-08-09T19:29:47.523 回答