[英]Java- JPanel design problems
更新: NVM IM偶数传递为空
嗯,所以我最近了解了面板,并且我正在尝试重新设计tictactoe项目的开始菜单,没什么大不了的。
这是我的梦想:
这是我当前的代码:
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);
}
但是,当我尝试运行它时,在第30行给出了错误,该错误与此行相关: modeButtons[0].setText("First turn");
。 谁能帮忙看看有什么问题吗?
这是错误的顺便说一句:
Ttt.main(Ttt.java:7)的Ttt.modeGUI(Ttt.java:30)处的线程“ main”中的java.lang.NullPointerException异常
按钮数组为空。
JButton[] modeButtons = new JButton[3];
该行创建一个JButtons数组,但是默认情况下每个元素都设置为null(与创建所有数组一样)。
所以当你尝试这个
modeButtons[0].setText("First turn");
由于modeButtons[0]
为null
所以抛出NullPointerException
。 您必须先明确定义每个按钮,然后才能开始分配它们的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.