我正在嘗試顯示班主教對象的ImageIcon。使用getImage()檢索ImageIcon。返回的ImageIcon存儲在引用m中,但未顯示,並且正在顯示另一個直接加載的ImageIcon h。我正在犯什麼錯誤?ImageIcon未顯示
import javax.swing.*;
//Game.java
public class Game {
public static void main(String[] args) {
board b = new board();
bishop bis1 = new bishop();
bis1.setLocation(0, 0);
ImageIcon m = bis1.getImage();
b.squares[0][1].add(new JLabel(m));
ImageIcon h = new ImageIcon("rook.png");
b.squares[0][0].add(new JLabel(h));
}
}
//bishop.java
import javax.swing.*;
import java.awt.*;
public class bishop {
private ImageIcon img;
private int row;
private int col;
public void bishop() {
img = new ImageIcon("bishop.png");
}
public void setLocation(int i, int j) {
row = i;
col = j;
}
public int getX() {
return row;
}
public int getY() {
return col;
}
public ImageIcon getImage() {
return img;
}
}
// board.java
import javax.swing.*;
import java.awt.*;
public class board {
public JFrame frame;
public JPanel squares[][] = new JPanel[3][3];
public board() {
frame = new JFrame("Simplified Chess");
frame.setSize(900, 400);
frame.setLayout(new GridLayout(2,3));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
squares[i][j] = new JPanel();
if ((i + j) % 2 == 0) {
squares[i][j].setBackground(Color.black);
} else {
squares[i][j].setBackground(Color.white);
}
frame.add(squares[i][j]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Java代碼約定規定類名稱應始終以大寫字母開頭。您應該將bishop.java重命名爲Bishop.java並將board.java重命名爲Board.java。這使得代碼更易於閱讀。 – 2012-03-08 14:30:40
@SteveMcLeod我很後悔命名不好的做法。請記住。 – 2012-03-08 14:39:48
@deporter這兩個圖像都在同一個文件夾 – 2012-03-08 14:40:13