Java 编译器无法解析覆盖 JButton 的符号



我正在编写一个编辑器,它创建一个按钮矩阵。单击时,按钮的显示符号会发生变化。所以我创建了一个扩展 JButton 的新类并更改了一些东西。 编译时编译器告诉我,它无法解析符号AlienGameButton。但是为什么?如何解决问题?

package MapGenerator;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
public class MapGenerator {
public static void main(String[] args) {

//Initialisierung der Mapgröße über einen Input-Dialog
int hight, width;
hight = Integer.parseInt(JOptionPane.showInputDialog(null, "Höhe des Spielfeldes: "));
width = Integer.parseInt(JOptionPane.showInputDialog(null, "Breite des Spielfeldes: "));
System.out.println(width);
System.out.println(hight);

//Erstellen eines Fensters abhängig von der Anzahl der gewünschten Felder
JFrame GeneratorFenster = new JFrame("Map Generator");
GeneratorFenster.setSize(hight * 50 + 50, width * 50);
GeneratorFenster.setVisible(true);
AlienGameButton buttons[][] = new AlienGameButton[hight][width];
GeneratorFenster.setLayout(new GridLayout(hight, width));
for (int i = 0; i < hight; i++) {
for (int j = 0; j < width; j++) {
buttons[i][j] = new AlienGameButton();
GeneratorFenster.add(buttons[i][j]);
}
GeneratorFenster.setVisible(true);
}
}
}

以及我创建的按钮的类:

package MapGenerator;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AlienGameButton extends JButton implements ActionListener {
private int count = 0;
public AlienGameButton() {
this.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
count += 1;
count %= 3;
switch (count) {
case 0:
setText(" ");
break;
case 1:
setText("A");
break;
case 2:
setText("#");
break;
case 3:
setText("P");
break;
case 4:
setText("O");
break;
}
}
}

这是编译器错误:

MapGenerator.java:26: error: cannot find symbol
AlienGameButton buttons[][] = new AlienGameButton[hight][width];
^
symbol:   class AlienGameButton
location: class MapGenerator
MapGenerator.java:26: error: cannot find symbol
AlienGameButton buttons[][] = new AlienGameButton[hight][width];
^
symbol:   class AlienGameButton
location: class MapGenerator
MapGenerator.java:31: error: cannot find symbol
buttons[i][j] = new AlienGameButton();
^
symbol:   class AlienGameButton
location: class MapGenerator
3 errors

正如评论中提到的,如果你觉得尝试使用 javac 文件名.java编译,它将无法正常工作。请使用以下两个命令使其工作:

javac MapGenerator/AlienGameButton.java
javac MapGenerator/MapGenerator.java

而不是

javac AlienGameButton.java
javac MapGenerator.java

另外,正如您所说,当您将其移动到src目录时,它开始工作,这是因为该软件包已更改为默认软件包。

附注:

一些建议和编码标准:

包名和类名不应完全相同

包名称 应始终从小写字母开头,类名应始终 从大写字母开始

最新更新