【问题标题】:set all components to be center of the JFrame将所有组件设置为 JFrame 的中心
【发布时间】:2015-05-05 22:32:54
【问题描述】:

我使用了 FormLayout,我想将我的所有组件(JLabel 和 JtextField)设置在 JFrame 的中心。

我尝试使用 panel.setAlignmentX 和 panel.setAlignmentY 但它不起作用。

 panel.setAlignmentX(Component.CENTER_ALIGNMENT);
 panel.setAlignmentY(Component.CENTER_ALIGNMENT);

下面是我的一段代码,请帮忙谢谢。

import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

@SuppressWarnings("serial")
public class UI extends JFrame {

    private JPanel panel = new JPanel();

    public UI() {

    FormLayout layout = new FormLayout(
            "pref, pref, pref, pref", 
            "pref, pref, pref, pref");

        panel.setLayout(layout);
        CellConstraints cc = new CellConstraints();

        panel = new JPanel (layout);

        panel.add(new JLabel("L1 "), cc.xy(2, 2));
        panel.add(new JTextField(15), cc.xy(3, 2));

        panel.add(new JLabel("L2 "), cc.xy(2, 3));
        panel.add(new JTextField(15), cc.xy(3, 3));    
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.setAlignmentY(Component.CENTER_ALIGNMENT);
        add(panel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(510,400);
        setLocationRelativeTo(null);
        setResizable(false);
    }

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

            }
        });
    }
}

【问题讨论】:

    标签: java swing form-layout


    【解决方案1】:

    使用GridBagLayout。默认情况下,添加到布局中的任何组件(面板)都将居中:

    //add(panel);
    setLayout( new GridBagLayout() );
    add(panel, new GridBagConstraints());
    

    这将允许您在包含您的组件的面板上使用您的FormLayout。现在内容窗格使用GridBagLayout,因此您的表单将居中。

    【讨论】:

      猜你喜欢
      • 2015-08-29
      • 2023-03-13
      • 2017-04-08
      • 2015-09-20
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多