ImageIcon未显示

Joh*_*son 0 java swing imageicon

我正在尝试显示类主教的对象的ImageIcon.使用getImage()检索ImageIcon.返回的ImageIcon存储在引用m中但它没有显示,并且正在显示另一个直接加载的ImageIcon h.我犯了什么错误?

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);
  }

}
Run Code Online (Sandbox Code Playgroud)

Kor*_*urk 5

你用错误的方式定义了构造函数 - 没有必要void.因此,您的Bishop类调用默认的空构造函数,因此您的变量 img永远不会正确设置.删除它,以便正确调用构造函数:

而不是这个:

public void bishop() {
        img = new ImageIcon("bishop.png");
    }
Run Code Online (Sandbox Code Playgroud)

定义它没有空格:

public bishop() {
            img = new ImageIcon("bishop.png");
        }
Run Code Online (Sandbox Code Playgroud)