gpt4 book ai didi

java - 图像图标不显示

转载 作者:行者123 更新时间:2023-12-01 07:37:39 24 4
gpt4 key购买 nike

我正在尝试显示 bishop 类对象的 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);
}

}

最佳答案

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

而不是这个:

public void bishop() {
img = new ImageIcon("bishop.png");
}

定义它而不带空:

public bishop() {
img = new ImageIcon("bishop.png");
}

关于java - 图像图标不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9619110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com