如何使 JTextField 与 window 一样宽

How to make JTextField as wide as the window

我想让文本自动与 window 一样宽。我尝试使用 text.setSize(window.getWidth(),20)text.setBounds(window.getWidth(),20),(其中文本是 JTextfield),但似乎唯一可行的方法是:static JTextField text = new JTextField(int numberOfColumns); 我正在使用 GridBag 布局。

编辑: 我已经根据 GridBagLayout 编辑了示例。

使用布局管理器。它会根据window自动扩展组件。 例如;

Jpanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
panel.add(textfield,c);