2017-02-28 84 views
0

我製作了一個JPanel併爲其分配了大小。但分配的大小不起作用。我無法弄清楚代碼有什麼問題?我只獲取JFrame。爲什麼這樣?請幫忙!JPanel無法獲得給定的大小

// 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)); 
     } 
    } 
+5

你需要的地方調用'的init()方法'你'Screen'添加到'Frame'。 – Izruo

+0

感謝它的工作。 – nischalinn

回答

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)); 
    } 
} 
    } 

//這裏是解決