1

我一直在为一个项目开发 GUI,到目前为止,我似乎根本无法让 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);
    }

}

每当我运行它时,我都会收到 NullPointerException

main.add(控制台,BorderLayout.SOUTH);

如果我注释掉那行,它运行时没有错误,但显示的只是一个巨大的空白白框。

有人可以帮忙吗?

4

2 回答 2

1

您尚未初始化console正在抛出 NullPointerException

 console = new JTextField("Some Name");
于 2013-04-04T19:40:56.380 回答
0

console没有在任何地方实例化。除了你所拥有的一切都是JPanels,所以没有什么可以显示的,因为JPanel它本身并不能提供太多的视觉反馈。

于 2013-04-04T19:42:22.180 回答