Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用GridBagLayout_Java - Fatal编程技术网

Java 如何使用GridBagLayout

Java 如何使用GridBagLayout,java,Java,我有一个JLabel、一个JButton和一个JTextField;我需要将JLabel从JFrame原点放入单元格(0,0),然后放入JTextField(1,0),最后在第二行放入JButton(0,1)。但是,我的所有组件都放在同一行中,它们从左到右开始 我的代码: public static void initializeFrame(){ GridBagLayout layout = new GridBagLayout(); // set frame layout

我有一个
JLabel
、一个
JButton
和一个
JTextField
;我需要将
JLabel
JFrame
原点放入单元格(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)两次

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


阅读更多关于更清晰的信息,并找到示例代码

请阅读有关的其他属性的更多信息


下面是带有内联注释的简化代码

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);