【发布时间】:2021-08-29 23:43:44
【问题描述】:
我正在尝试使用 Java 中的 AI 制作井字游戏,但我对 Swing 和 Java 图形不熟悉。首先,即使我设置了不透明true(参见下面的ttt 类),我也无法更改我的JPanel 的背景颜色。然而,我能够更改 JFrame 的背景(参见课程tttFrame)。其次,当我尝试将 JPanel(这些面板是 X 和 O 所在的位置)添加到我当前 JPanel 的顶部时 - 带有线条的那个(或者可能是这样,但 JPanel 的背景颜色不会改变) 他们不会显示。 testpanel 和tttGrid 中的面板都没有出现。我假设我对如何实现 JFrames 和 JPanels 有错误的想法。
我的代码还在this.add(tttGrid[r][c]); 处引发了一个空指针异常。 tttGrid 基本上是 JPanel 的二维数组,旨在在用户/计算机单击时显示 X 或 O。我不确定我的代码如何导致 nullpointerexception。正如你在this.add(tttGrid[r][c]); 之前的行中所注意到的,我做了一些测试,我在控制台窗口中得到了这个输出:
actual label, row 0 col 0
actual label, row 0 col 1
actual label, row 0 col 2
null label, row 1 col 0
null label, row 1 col 1
null label, row 1 col 2
null label, row 2 col 0
null label, row 2 col 1
null label, row 2 col 2
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ttt extends JPanel{
private char playerChoice;
private JPanel[][] tttGrid;
public ttt(){
//this.setOpaque(true); Why isn't setBackground working in JPanel and
//this.setBackground(Color.BLUE); only working in JFrame class?
this.setPreferredSize(new Dimension(500,500));
this.setFocusable(true);
tttGrid = new JPanel[3][3];
for(int y = 50; y <= 290; y+=120){
int r = 0;
int c = 0;
for(int x = 70; x <= 310; x+=120){
tttGrid[r][c] = new JPanel();
tttGrid[r][c].setBounds(x,y,120,120);
tttGrid[r][c].setBackground(Color.GREEN);
tttGrid[r][c].setOpaque(true);
c++;
}
r++;
}
for(int r = 0; r < 3; r++){
for(int c = 0; c < 3; c++){
if(tttGrid[r][c] == null){
System.out.println("null panel, row " + r + " col " + c);
}
else{
System.out.println("real panel, row " + r + " col " + c);
}
this.add(tttGrid[r][c]); //nullpointerexception
}
}
//testing if JPanel is visible
JPanel testpanel = new JPanel();
testpanel.setBounds(70,50,120,120);
testpanel.setBackground(Color.MAGENTA);
testpanel.setOpaque(true);
this.add(testpanel);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(153, 250, 255));
g2d.setStroke(new BasicStroke(5));
g2d.drawLine(70, 170, 430, 170);
g2d.drawLine(70, 290, 430, 290);
g2d.drawLine(190, 50, 190, 410);
g2d.drawLine(310, 50, 310, 410);
}
public void gameStart(){
}
public void drawXO(){
}
}
import javax.swing.*;
import java.awt.*;
public class tttFrame extends JFrame{
public tttFrame(){
this.getContentPane().add(new ttt());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Tic-Tac-Toe");
ImageIcon icon = new ImageIcon("ttt.png");
this.setIconImage(icon.getImage());
this.setBackground(new Color(0,225,237)); //Background color only works on JFrame
this.setResizable(false);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new tttFrame();
}
}
下面的照片是我注释掉代码this.add(tttGrid[r][c]);得到的结果
【问题讨论】:
-
你的NPE是第一个
for-loop重置r造成的 -
你的下一个问题是,你正在与布局管理和绘画系统作斗争
标签: java swing nullpointerexception jpanel graphics2d