JPanel无法获得给定的大小

时间:2017-02-28 12:06:55

标签: java swing jframe jpanel

我制作了一个JPanel并为其分配了大小。但分配的大小不起作用。我无法弄清楚代码有什么问题?我只获得了JFrame。为什么会这样?请帮忙!

    // Frame.java
    package game;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import game.graphics.Screen;
    public class Frame extends JFrame{  
        public Frame() 
        {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setTitle("SNAKE");
            setResizable(false);
            setVisible(true);
        }   
        public void Init()
        {
            setLayout(new GridLayout(1,1,0,0));     
            Screen s = new Screen();
            add(s);
            pack();     
            setLocationRelativeTo(null);        
        }   
        public static void main(String[] args)
        {
            new Frame();
        }
    }
    //Screen.java
    package game.graphics;
    import java.awt.Dimension;
    import javax.swing.JPanel;
    public class Screen extends JPanel {

        public static final int WIDTH = 800, HEIGHT = 800;
        public Screen()
        {
            setPreferredSize(new Dimension(WIDTH, HEIGHT));
        }
    }

1 个答案:

答案 0 :(得分:0)

import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.JFrame;
public class Frame extends JFrame{  
    public Frame() 
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("SNAKE");
        setResizable(false);
        setVisible(true);
    }   
    public void Init()
    {
        setLayout(new GridLayout(1,1,0,0));     
        Screen s = new Screen();
        add(s);
        pack();     
        setLocationRelativeTo(null);        
    }   
    public static void main(String[] args)
    {
        Frame f = new Frame();
        f.Init();
    }




public class Screen extends JPanel {

    public static final int WIDTH = 1000, HEIGHT = 800;
    public Screen()
    {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
    }
}
  }

//这是解决方案