我的小程序应该从名为 map1.txt 的 .txt 文件中读取,并将其中的字符存储在 Char[][] 数组中。根据我的 map1.txt 中的字符,如果 char 为“x”,则我的 Tile 类绘制红色,否则绘制绿色。(相反,程序显示面板后面的内容,而不是红色和绿色的框。编辑)。
public class MainClass extends JPanel {
static Tile[][] tile = new Tile[SomeInts.amount][SomeInts.amount];
static Map map = new Map();
public MainClass () {
this.setBackground(Color.white);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for (int x = 0; x < SomeInts.amount; x++){
for (int y = 0; y < SomeInts.amount; y++){
tile[x][y].colorBody(g, x, y);
}
}
}
//Most important
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(500, 500);
f.setLocation(100,100);
f.setTitle("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainClass p = new MainClass ();
f.add(p);
f.setVisible(true);
//load map
map.loadMap();
for (int x = 0; x < SomeInts.amount; x++){
for (int y = 0; y < SomeInts.amount; y++){
tile[x][y] = new Tile();
}
}
for (int x = 0; x < SomeInts.amount; x++){
for (int y = 0; y < SomeInts.amount; y++){
tile[x][y].setType(map.charmap[x][y]);
}
}
}
}
public class Tile {
char type = 'a';
public void setType(char c){
type = c;
}
public void colorBody(Graphics g, int x, int y){
if (type == 'x'){
g.setColor(new Color(255, 0, 0));
g.fillRect(x * 10, y * 10, 10, 10);
}
else{
g.setColor(new Color(0, 255, 0));
g.fillRect(x * 10, y * 10, 10, 10);
}
}
}
public class Map {
public char[][] charmap = new char[SomeInts.amount][SomeInts.amount];
public void loadMap(){
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("map1.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (line != null){
int y = 0;
for (int x = 0; x < line.length(); x++){
charmap[x][y] = line.charAt(x);
}
y++;
}
}
//Not used but does work
public void createMap() {
for (int x = 0; x < SomeInts.amount; x++){
for (int y = 0; y < SomeInts.amount; y++){
charmap[x][y] = 'x';
}
}
}
}