0

I want to make the text automatically as wide as the window. I tried using text.setSize(window.getWidth(),20) and text.setBounds(window.getWidth(),20), (where text is JTextfield), but the only way that seems to work is: static JTextField text = new JTextField(int numberOfColumns); I'm using GridBag layout.

Marian
  • 25
  • 7

1 Answers1

0

EDIT: I have edited example according to GridBagLayout.

Use layout manager. It will automatically expands component according to window. For example;

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);
mstfyldz
  • 482
  • 1
  • 6
  • 12
  • I think i forgot to mention, that I'm using GridBag layout. I don't know whether that makes a difference – Marian Mar 08 '19 at 12:52
  • Yes, it makes a _huge_ difference! In the `GridBagConstraints` for your field, set the `gridx` to 0, the `gridwidth` to `GridBagConstraints.REMAINDER and `fill` to `GridBagConstraints.HORIZONTAL` or `GridBagConstraints.BOTH` – Kevin Anderson Mar 08 '19 at 13:01