我想缩短我的文本字段,这样它就不会延伸到我的 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 对齐文本字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17580736/