SetPreferredSize not working

the code:

import java.awt.Dimension;

import javax.swing.*;

public class Game extends JFrame {
    private static final long serialVersionUID = -7919358146481096788L;
    JPanel a = new JPanel();
    public static void main(String[] args) {
        new Game();
    }
    private Game() {
        setTitle("Insert name of game here");
        setLocationRelativeTo(null);
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        a.setPreferredSize(new Dimension(600, 600));
        add(a);
        pack();
        setVisible(true);
    }
}

So, I set the preferred size JPanelto 600 by 600 and pack the frame, but the frame size is still 0 to 0.

Why is this and how to fix it?

+5
source share
3 answers

As you said, it pack()will try to arrange the window so that each component is resized to its preferred size.

The problem is that the layout manager is apparently the one who is trying to organize the components and their respective preferred values. However, when you install the layout manager as null, no one is responsible for this.

setLayout(null), . , LayoutManager.

:

import java.awt.Dimension;

import javax.swing.*;

public class Game extends JFrame {
    private static final long serialVersionUID = -7919358146481096788L;
    JPanel a = new JPanel();
    public static void main(String[] args) {
        new Game();
    }
    private Game() {
        setTitle("Insert name of game here");
        setLocationRelativeTo(null);
        //setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        a.setPreferredSize(new Dimension(600, 600));
        add(a);
        pack();
        setVisible(true);
    }
}
+8

pack() , :

setPreferredSize(new Dimension(600, 600));

-

setLocationRelativeTo(null);

pack() :)

, , BorderLayout JFrame?

+2

setLayout(null), pack():

,

.

, :

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JFrame {

    JPanel panel = new JPanel();

    private void createAndShowGUI() {
        setTitle("FrameDemo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel.setPreferredSize(new Dimension(600, 600));
        add(panel);

        //setLayout(null); //wont work with this call as pack() resizes according to layout manager
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Game().createAndShowGUI();
            }
        });
    }
}
+2
source

All Articles