我的目标是让我的组件根据我的GridBagConstraints调整大小,但是由于某些原因,当我的小程序运行时,这些组件会出现,但不会像我期望的那样填满整个小程序。下面是我的代码:
ServerPanel:
public class ServerPanel extends JPanel{
public ServerPanel(){
setLayout(new GridBagLayout()); //use gridbag layout
GridBagConstraints gbc = new GridBagConstraints();
JButton reverse = new JButton("Reverse text");
JButton send = new JButton("Send text");
JButton clear = new JButton("Clear text");
JTextField text = new JTextField("Test");
JScrollPane scrollPane = new JScrollPane(text, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//Reverse button
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.HORIZONTAL;
add(reverse, gbc);
//send button
gbc.gridy = 1;
add(send, gbc);
//clear button
gbc.gridy = 2;
add(clear,gbc);
//text field
gbc.gridy = 3;
gbc.ipadx = 20;
gbc.ipady = 20;
gbc.fill = gbc.BOTH;
add(scrollPane, gbc);
}
}来自扩展JApplet的ServerApplet的相关代码:
public void init(){
//dim = getSize();
//create the GUI in the EDT
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
//System.out.println(dim);
setLayout(new BorderLayout());
add(new ServerPanel(), BorderLayout.CENTER);
}
});
}发生的情况是创建了正确的组件,并且面板在applet中居中,但它不会展开以填充整个applet。任何帮助都是非常感谢的。谢谢!
发布于 2012-12-02 07:09:06
当我看到这个的时候:
但由于某种原因,当我的小程序运行时,组件会出现,但不会像我预期的那样填充整个小程序...
与GridBagLayout一起使用时,我会查看是否在GridBagConstraints上设置了weightx和weightx字段,因为它们保留为默认值0的症状是所有组件都集中在中间。
解决方案:在需要的地方设置这些字段。如果一个组件应该在x方向上扩展,那么给它一个+ weighty x,可能是1.0,对于weighty也是如此。
https://stackoverflow.com/questions/13664598
复制相似问题