2013-04-04 52 views
1

我一直在为一个项目的GUI工作,到目前为止,我似乎无法让JFrame显示出来。这是我的代码。JFrame显示一个巨大的白色框

package code; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class GUI extends JFrame { 
    private JPanel ui, board, u1, u2, game, main; 
    private JTextField console; 
    private int x, y; 

    public GUI (Controller c) { 
     setSize(new Dimension(900,710)); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //console.setText("Hello, and welcome to the game of Lotus!"); 
     main = new JPanel(new BorderLayout()); 
     game = new JPanel(new BorderLayout()); 
     board = new BoardPanel(c); 
     ui = new JPanel (new GridLayout(1,2));; 
     u1 = new JPanel (new FlowLayout()); 
     u2 = new StackPanel(c); 
     board = new JPanel(); 

     createAndShowGUI(); 
     add(main); 
     setVisible(true); 
    } 

    public GUI() { 
     setSize(new Dimension(900,710)); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //console.setText("Hello, and welcome to the game of Lotus!"); 
     main = new JPanel(new BorderLayout()); 
     game = new JPanel(new BorderLayout()); 
     board = new BoardPanel(); 
     ui = new JPanel (new GridLayout(1,2));; 
     u1 = new JPanel (new FlowLayout()); 
     u2 = new StackPanel(); 
     board = new JPanel(); 


     createAndShowGUI(); 
     add(main); 
     setVisible(true); 
     printToConsole("Yes, it's working!"); 
    } 

    public void createAndShowGUI() { 
     //add components to ui 
     u1.setSize(200,300); 
     u2.setSize(200,400); 
     ui.add(u1); 
     ui.add(u2); 

     //add components to game 
     board.setSize(700,700); 
     ui.setSize(200,700); 
     game.add(board, BorderLayout.CENTER); 
     game.add(ui, BorderLayout.EAST); 


     //add main frame components to gui 
     main.add(game, BorderLayout.CENTER); 
     main.add(console, BorderLayout.SOUTH); 
    } 

    public void update() { 
     repaint(); 
    } 

    public void printToConsole (String s) { 
     console.setText(s); 
    } 

} 

每当我跑这一点,我在

main.add(控制台,BorderLayout.SOUTH)得到一个NullPointerException异常;

如果我注释掉该行,它将毫无错误地运行,但所有显示的内容都是一个巨大的空白白框。

任何人都可以帮忙吗?

回答

1

您还没有初始化console其抛出NullPointerException异常

console = new JTextField("Some Name"); 
+0

我觉得自己像个白痴。谢谢您的帮助! – yuritsuki 2013-04-04 19:41:42

+0

不要难过。它发生在我们所有人初始化实例。下次注意异常,Exception给你提供很多关于错误的信息。 – Smit 2013-04-04 19:43:22

0

console不被任何实例化。除此之外,你所有的都是JPanel s,所以没有什么可以显示为JPanel本身并不提供很多视觉反馈。