简体   繁体   English

Java- JPanel设计问题

[英]Java- JPanel design problems

UPDATE: NVM IM AN IDIOT PASSING A NULL 更新: NVM IM偶数传递为空

ummm so I recently learned about panels and I'm trying to redesign the start menu of a tictactoe project, nothing major. 嗯,所以我最近了解了面板,并且我正在尝试重新设计tictactoe项目的开始菜单,没什么大不了的。

This is my dream: 这是我的梦想:

在此处输入图片说明

This is my current code: 这是我当前的代码:

public static void modeGUI () {

    //MAIN JFRAME GUI
    JFrame gui = new JFrame("TicTacToe");
    gui.setVisible(true);
    gui.setSize(600, 200);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //MAIN PANEL
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(3, 1));
    gui.add(mainPanel);

    //QUESTION PANEL
    JPanel questionPanel = new JPanel();
    questionPanel.setLayout(new FlowLayout());
    JLabel q1 = new JLabel("Please select your mode");
    q1.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    questionPanel.add(q1);
    mainPanel.add(questionPanel);

    //MODE PANEL
    JPanel  modePanel = new JPanel();
    modePanel.setLayout(new GridLayout());
    JButton[] modeButtons = new JButton[3];
    modeButtons[0].setText("First turn");
    modeButtons[1].setText("Second turn");
    modeButtons[2].setText("P vs. P");
    for (JButton modeButton : modeButtons) {
        modeButton.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        modeButton.addActionListener(new Response());
        modePanel.add(modeButton);
    }
    mainPanel.add(modePanel);

    //OPTION PANEL
    JPanel optionsPanel = new JPanel();
    optionsPanel.setLayout(new FlowLayout());
    mainPanel.add(optionsPanel);
}

However when I attempt to run it it gives an error at line 30, which correlates to this line: modeButtons[0].setText("First turn"); 但是,当我尝试运行它时,在第30行给出了错误,该错误与此行相关: modeButtons[0].setText("First turn"); . Can anyone help see what's wrong? 谁能帮忙看看有什么问题吗?

This is the error btw: 这是错误的顺便说一句:

Exception in thread "main" java.lang.NullPointerException at Ttt.modeGUI(Ttt.java:30) at Ttt.main(Ttt.java:7) Ttt.main(Ttt.java:7)的Ttt.modeGUI(Ttt.java:30)处的线程“ main”中的java.lang.NullPointerException异常

The array of buttons is empty. 按钮数组为空。

JButton[] modeButtons = new JButton[3];

This line creates an array of JButtons, but each element is by default set to null (as with the creation of all arrays). 该行创建一个JButtons数组,但是默认情况下每个元素都设置为null(与创建所有数组一样)。

So when you try this 所以当你尝试这个

modeButtons[0].setText("First turn");

A NullPointerException is thrown since modeButtons[0] is null . 由于modeButtons[0]null所以抛出NullPointerException You have to explicitly define each button before you can begin assigning their values. 您必须先明确定义每个按钮,然后才能开始分配它们的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM