gpt4 book ai didi

java - 如何使用 GridBagLayout

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:53 25 4
gpt4 key购买 nike

我有一个 JLabel、一个 JButton 和一个 JTextField;我需要将 JLabelJFrame 原点放入单元格 (0,0),然后放入 JTextField (1,0),最后在第二行放入 JButton (0,1)。但是,我的所有组件都放在同一行中,并且从左到右开始。

我的代码:

public static  void initializeFrame(){
GridBagLayout layout = new GridBagLayout();
// set frame layout
JFrame frame = new JFrame("JFrame Source Demo");
frame.setSize(new Dimension(400,200));
frame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JPanel topPanel = new JPanel();
JLabel jlbempty = new JLabel("MacAddress");
c.gridx = 0;
c.gridy = 0;
c.ipadx = 30;
c.ipady = 10;
topPanel.add(jlbempty,c);
JTextField field1 = new JTextField();
c.gridx = 1;
c.gridy = 0;
c.ipadx = 30;
c.ipady = 10;
topPanel.add(field1,c);
field1.setPreferredSize(new Dimension(150, 20));
JButton jb = new JButton("Generation Mac");
c.gridx = 0;
c.gridy = 1;
c.ipadx = 30;
c.ipady = 10;
layout.setConstraints( jb, c ); // set constraints
topPanel.add(field1,c);
topPanel.add(jb,c);
frame.add(topPanel);
frame.pack();
frame.setVisible(true);
}

最佳答案

我在您的代码中观察到的一些事情。

  • topPanel 的布局设置为 GridBagLayout

  • 您正在调用 topPanel.add(field1, c); 两次。

  • 不要使用首选尺寸,而应使用相对尺寸。只需将其交给布局管理器来调整组件的大小即可。

<小时/>

了解更多关于How to Use GridBagLayout的信息为了更加清晰,还可以找到示例代码。

请详细了解 GridBagLayout 的其他属性.

<小时/>

这是带有内联注释的简化代码。

GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
// c.insets=new Insets(5,5,5,5); // margin outside the panel

JPanel topPanel = new JPanel(new GridBagLayout());

JLabel jlbempty = new JLabel("MacAddress");
c.gridx = 0;
c.gridy = 0;
// c.weightx=0.25; // width 25% for 1st column
topPanel.add(jlbempty, c);

JTextField field1 = new JTextField();
c.gridx = 1;
c.gridy = 0;
// c.weightx=0.75; // width 75% for 2nd column
topPanel.add(field1, c);

JButton jb = new JButton("Generation Mac");
c.gridx = 0;
c.gridy = 1;
//c.gridwidth = 2; //SPAN to 2 columns if needed
// c.weightx=1.0; // back to width 100%
topPanel.add(jb, c);

关于java - 如何使用 GridBagLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23727126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com