Colby Stahl
Colby Stahl

Reputation: 67

JFrame/JPanel's Dimensions are Incorrect

So, right now whenever the Game class runs (which contains a MainPanel object), I get only a small box just big enough to fit the "minimize", "restore", and "close" buttons, rather than a 1280x720 screen. All of my other JFrame/JPanel combinations work except for this one, and I can't seem to figure out why. It is most likely just a small mistake, but I've been puzzled for far too long on this issue. Thanks!

 public class Game extends JFrame{ 
    public static MainPanel mp = new MainPanel();
    public static void main( String[] args){
        Game g1 = new Game();
        g1.play();
    }

    public Game(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle( "Game" );
        setResizable( false );
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setPreferredSize(new Dimension(1280, 720));
        setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        setUndecorated(false);

        mp.setBackground( Color.BLACK );
        mp.setPreferredSize( new Dimension(1280, 720) );
        mp.setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
        mp.setLayout( null );
        mp.repaint();

        getContentPane().add( mp );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setVisible(true);
                }
            });
    }

}

and

public class MainPanel extends JPanel{
    private JPanel jp = new JPanel();
    public MainPanel(){
        jp.setBackground( Color.BLACK );
        jp.setPreferredSize( new Dimension(1280,720) );
        jp.setLayout( null );
    }

    private void play(){
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                setVisible(true);
            }
        });
    }
}

Upvotes: 0

Views: 63

Answers (1)

user7485924
user7485924

Reputation:

Instead of using:

setPreferredSize(Dimension dimension);

use:

setSize(int width, int height);

setPreferredSize(Dimension dimension); don't work in JFrame and only work for components like JPanel.

I hope that helps!!

Upvotes: 1

Related Questions