Search code examples
javaswinguser-interfacejtextfield

How to make JTextField as wide as the window


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.


Solution

  • 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);