当前位置: 代码迷 >> J2SE >> 一个关于GridBagLayout的有关问题(100分,决不吝啬)
  详细解决方案

一个关于GridBagLayout的有关问题(100分,决不吝啬)

热度:153   发布时间:2016-04-24 13:40:13.0
一个关于GridBagLayout的问题(100分,决不吝啬)
我想让一个文本框位于两个按钮下一行,并且占两列,但是结果是错的.
请帮我看一下,代码如下:
import   java.awt.*;
import   javax.swing.*;

public   class   Mytest
{
public   static   void   main(String[]   args)
{
MytestFrame   frame   =   new   MytestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class   MytestFrame   extends   JFrame
{
public   MytestFrame()
{
setSize(400,   300);

Container   contentPane   =   getContentPane();
GridBagLayout   layout   =   new   GridBagLayout();
GridBagConstraints   cons   =   new   GridBagConstraints();

contentPane.setLayout(layout);

cons.gridx   =   0;
cons.gridy   =   0;
cons.gridwidth   =   1;
contentPane.add(new   JButton( "Button1 "),   cons);

cons.gridx   =   1;
cons.gridy   =   0;
contentPane.add(new   JButton( "Button2 "),   cons);

cons.gridx=0;
cons.gridy=1;
cons.gridwidth=2;
contentPane.add(new   JTextField( "Text "));

}
}

------解决方案--------------------
import java.awt.*;
import javax.swing.*;

public class Mytest
{
public static void main(String[] args)
{
MytestFrame frame = new MytestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class MytestFrame extends JFrame
{
public MytestFrame()
{
setSize(400, 300);

Container contentPane = getContentPane();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();

contentPane.setLayout(layout);

cons.gridx = 0;
cons.gridy = 0;
cons.gridwidth = 1;
contentPane.add(new JButton( "Button1 "), cons);

cons.gridx = 1;
cons.gridy = 0;
contentPane.add(new JButton( "Button2 "), cons);

cons.gridx=0;
cons.gridy=1;
cons.gridwidth=2;
contentPane.add(new JTextField( "Text ",13),cons);

}
}

------解决方案--------------------
呵呵,lz少加个cons
------解决方案--------------------
import java.awt.*;
import javax.swing.*;

public class Mytest
{
public static void main(String[] args)
{
MytestFrame frame = new MytestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class MytestFrame extends JFrame
{
public MytestFrame()
{
setSize(400, 300);

Container contentPane = getContentPane();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();

contentPane.setLayout(layout);

cons.gridx = 0;
cons.gridy = 0;
cons.gridwidth = 1;
contentPane.add(new JButton( "Button1 "), cons);

cons.gridx = 1;
cons.gridy = 0;
contentPane.add(new JButton( "Button2 "), cons);

cons.gridx=0;
cons.gridy=1;
cons.gridwidth=GridBagConstraints.CENTER;
contentPane.add(new JTextField( "Text "),cons);

}
}
------解决方案--------------------
首先给你一个建议:将布局写成一个函数,便于理解,更便于重复调用!
  相关解决方案