我想将 png 图像分配给 JLabel
。
我尝试了此代码,但没有出现图像[更新]:
class firstPokemonChoose extends JFrame{
private static final int WIDTH = 800; //ukuran panjang window
private static final int HEIGHT = 800; //ukuran lebar window
JLabel intro, tryImage;
public firstPokemonChoose(){
setTitle("Choose Your Pokemon"); //set judul window
setSize(WIDTH, HEIGHT); //set ukuran
intro = new JLabel("Please choose your first Pokemon", SwingConstants.LEFT);
java.net.URL url = getClass().getResource("torchic.png");
ImageIcon img = new ImageIcon(url);
tryImage.setIcon(img);
Container pane = getContentPane();
pane.setLayout(new GridLayout(3, 3));
pane.add(intro);
pane.add(tryImage);
setVisible(true); //set windows visible
setDefaultCloseOperation(EXIT_ON_CLOSE);
validate();
}
}
最佳答案
您必须向 JLabel 提供 Icon 实现(即 ImageIcon)。您可以通过 setIcon 方法(如您的问题中所示)或通过 JLabel 构造函数来完成此操作:试试这个
tryImage.setIcon(new ImageIcon(path));
关于java - 如何在 Java 中将图像分配给 JLabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36679181/