java GUI 问题 我该怎么设置页面布局使得组件在窗体放大时也在中间显示?

public class MainFrame extends JFrame implements ActionListener
{

/**
*
*/
private static final long serialVersionUID = 1L;
private JLabel welcome = new JLabel("通讯录");
private JPanel welcomejpanel=new JPanel();
private JButton sureJButton=new JButton("welcome");

Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth=screenSize.width;
int srceenHeight=screenSize.height;

public MainFrame()
{

//设置窗体相关属性
//设置窗口标题
this.setTitle("--个人通讯录--");
//设置窗口可拖动大小
this.setResizable(true);
//设置窗口大小
this.setSize(screenWidth/2,srceenHeight/2);
//设置窗口居于屏幕中央
setLocation((screenWidth-getWidth())/2,(srceenHeight-getHeight())/2);
//设置面板容器的布局策略为空
welcomejpanel.setLayout(null);
//设置面板容器背景色
welcomejpanel.setBackground(Color.BLUE);
sureJButton.setBounds(220, 250, 210, 110);
welcome.setBounds(250, 50, 200, 100);
//设置按钮的文本颜色
sureJButton.setForeground(Color.RED);
welcome.setForeground(Color.BLACK);
//设置标签和两个按钮的字体
sureJButton.setFont(new Font("宋体",Font.PLAIN,50));
welcome.setFont(new Font("楷体",Font.PLAIN,50));
//为按钮添加动作事件监听器
sureJButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
MainTest.main(new String[0]);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
new MainTest().validate();
MainFrame.this.dispose();
}
});

//将面板容器添加到内容窗格
this.add(welcomejpanel);
welcomejpanel.add(welcome);
welcomejpanel.add(sureJButton);
//为窗口添加关闭响应事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

//显示窗体
this.setVisible(true);

}

//主方法
public static void main(String []args)
{
new MainFrame();//创建登陆窗体
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub

}

}

要想随意布局就不能使用布局管理器,直接setLayout( null );
添加组件后,对组件设置setBounds(...)
但是这种情况最好窗口大小不能变

另外一个是使用GridBagLayout,这个布局管理器相当复杂且强悍,要想用的很熟得下功夫

使用图片来布局是不可能的(虽然可以识别出区域来,但是没办法确定哪个组件放在哪个位置)
使用文本还差不多,最好使用XML定义(如果使用null布局有希望以后可以变动的话)
温馨提示:内容为网友见解,仅供参考
第1个回答  2015-05-19
使用GridBagLayout,构造一个一行一列的表格,GridBagConstraints基本用默认值就可以实现了
相似回答