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.
Asked
Active
Viewed 39 times
0

Marian
- 25
- 7
-
Don't set the size but use an apropriate layout. https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html – kai Mar 08 '19 at 12:51
-
See : https://stackoverflow.com/a/55024689/3992939 – c0der Mar 08 '19 at 12:51
1 Answers
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