chope_chope
chope_chope

Reputation: 470

Set JTextField width to match width of JPanel

I'm looking for a way to set the display of a JTextField to take up the entire width of the JPanel that contains it.

The only method I've been able to find to do this is the setColumns() method combined with a getWidth() method called on the JPanel after the pack() and setVisible() methods are called. But when I do this the JTextField ends up much larger than the JPanel that encloses it. My assumption on why this happens is that the getWidth() returns that size of the JPanel in pixels, and the columns in the JTextField are all larger than a pixel.

I'm not even looking for the field to dynamically resize, just to be as wide as the JPanel at the start of the program

Any help greatly appreciated

Upvotes: 0

Views: 2655

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Make use of an appropriate layout manager...

Remember, it's not the responsibility of the component to decide how big it should, that's the responsibility of the layout manager, the component can only provide hints about how big it would like to be...

For example, you could do this with a GridBagLayout...

enter image description here

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {

            JTextField field = new JTextField(10);
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(field, gbc);

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

Take a look at Laying Out Components Within a Container for more details

Upvotes: 4

Related Questions