Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 537
Code-Apprentice Avatar asked May 03 '26 15:05

Code-Apprentice


1 Answers

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..."

like image 158
Bela Vizer Avatar answered May 06 '26 05:05

Bela Vizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!