Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java program doesn't show swing elements until resized?

Tags:

java

swing

Could anyone please explain why this may be happening? Image is here Image I couldn't upload because I'm a new user.

setTitle("jNote");
    pack();
    setVisible(true);
    setLayout(new BorderLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Image icon = Toolkit.getDefaultToolkit().getImage("jNote.png");
    setIconImage(icon);
like image 470
Jordan Osborn Avatar asked Mar 07 '26 21:03

Jordan Osborn


2 Answers

Usually GUI size can be suggested by the contents. If called after the components are added, pack() will cause the GUI to be the minimum size it needs to display them.

jNote

import java.awt.BorderLayout;
import javax.swing.*;

public class JNote {

    public JComponent getGui(int rows, int cols) {
        JPanel p = new JPanel(new BorderLayout(2,2));

        p.add(new JLabel("1"), BorderLayout.LINE_START);
        JTextArea ta = new JTextArea(rows, cols);
        JScrollPane sp = new JScrollPane(
                ta,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        p.add(sp);
        p.add(
            new JLabel("Rows: " + rows + "    " + "Columns: " + cols),
            BorderLayout.PAGE_END);

        return p;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable(){
            public void run() {
                int cols = 20;
                JNote jNote = new JNote();
                for (int rows=6; rows>0; rows-=2) { 
                    JFrame f = new JFrame("jNote " + rows + "x" + cols);
                    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    f.setLocationByPlatform(true);
                    f.add(jNote.getGui(rows, cols));

                    f.pack();
                    f.setVisible(true);
                }
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
like image 127
Andrew Thompson Avatar answered Mar 10 '26 11:03

Andrew Thompson


When setting dimensions via preferred sizes, you must call pack() in order to apply your preferred sizes. Resizing a frame packs it as well, hence your observations.

// component initializations
yourFrame.pack();
like image 31
FThompson Avatar answered Mar 10 '26 11:03

FThompson



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!