我想缩短我的文本字段,这样它就不会伸展到我的jframe的末尾,所以它现在看起来是这样的:

如何控制文本字段的宽度,使其不像我尝试的setPreferedSize()和setSize(),但它们不起作用??
@Override
public void run() {
JFrame frame = new JFrame("Test Calculator");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(500, 500);
JPanel panel = new JPanel(new GridBagLayout());
frame.getContentPane().add(panel, BorderLayout.NORTH);
GridBagConstraints c = new GridBagConstraints();
JLabel testLabel = new JLabel("Enter Score For Test 1: ");
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(40, 15, 15, 0);
panel.add(testLabel , c);
JTextField txtField1 = new JTextField("TextField");
c.gridx = 1;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .5;
panel.add(txtField1 , c);
}发布于 2013-07-11 05:02:33
您告诉布局文本字段必须水平填充,这就是它所做的。替换
c.fill = GridBagConstraints.HORIZONTAL;通过
c.fill = GridBagConstraints.NONE;发布于 2013-07-11 04:58:53
首先也是最重要的,去掉这个:
frame.setSize(500, 500);取而代之的是,在填充JFrame之后,在将其设置为可见之前,让您的组件和布局管理器通过对它调用pack()来调整自己的大小。
接下来,考虑在主容器周围添加一个空边框,或者使用容器向GridBagLayout添加一个空JLabel。
您还可以为您的JTextField提供适当的插入,以便在它周围提供缓冲。
c.insets = new Insets(40, 15, 15, 40);
panel.add(txtField1, c);发布于 2013-07-11 05:01:45
您可以通过更改GridBagConstraints网格宽度字段来更改特定组件占用的列数。
//this would make the next component take up 2 columns
c.gridwidth = 2;https://stackoverflow.com/questions/17580736
复制相似问题