我要缩短我的文本字段,以便它不会延伸到我的JFrame的结束,所以这是现在的样子: GridBagLayout对齐textField?
如何控制文本框的宽度,但这并没有streatch就像我尝试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);
}
“接下来,考虑在主容器周围添加一个空白边框,或者使用容器向GridBagLayout添加空的JLabel”我不明白为什么我需要这样做?请解释一下 – babaysteps
@babaysteps:这一切都取决于你想要做什么。如果你想添加到面板上的所有组件都有一个空白边框,那么给它一个与插入类似的EmptyBorder。如果你想在右边有一个空列,那么在c.gridY = 2的位置上添加一个空白的JLabel。如果您只是想稍微移动JTextField的右端,请按上面所示更改插入。我建议你尝试一下你的代码,并尝试一下这些东西,你也会阅读这些教程。 –