Code-Apprentice
Code-Apprentice

Reputation: 83527

Hand-coding Swing components

Okay, apparently I've gotten lazy lately by using the NetBeans GUI Builder. When I add a JLabel and a JTextField to my window, the JFrame doesn't resize itself. I've written a SSCCE to demonstrate:

package swingdemo;

import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class SwingDemo {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Swing Demo");
        Container contentPane = frame.getContentPane();
        JLabel label = new JLabel("Demo Label");
        JTextField textField = new JTextField();

        contentPane.setLayout(new FlowLayout());
        contentPane.add(label);
        contentPane.add(textField);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

What am I missing here? I know it's something rather simple. Do I need to call setPreferredSize() on both my JLabel and JTextField?

Upvotes: 3

Views: 158

Answers (1)

Bela Vizer
Bela Vizer

Reputation: 2537

call frame.pack() at the end of your code

javadoc says:

"Causes this Window to be sized to fit the preferred size and layouts of its subcomponents..."

Upvotes: 4

Related Questions