我想缩短我的文本字段,使其不会延伸到我的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);
}
最佳答案
您在告诉布局文本字段必须水平填充,这就是它的作用。更换
c.fill = GridBagConstraints.HORIZONTAL;
通过
c.fill = GridBagConstraints.NONE;
关于java - GridBagLayout对齐textField吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17580736/