因此,我正在处理一个小的“游戏”,并且其中的一部分图标以行显示(每个图标一个jpanel)。我添加的这些Icon组件在隔离时可以完美显示,但是当我将其添加到它们的每一行时,它们似乎根本没有显示。我是新手,所以我想知道是否是因为图像比放入图像的行小一些?
以下是独立运行图标的代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.nio.file.Path;
public class fermiPicoNanoImage extends JPanel {
private BufferedImage image = null;
private int[] imageDims = new int[] { 83, 47};
//for testing
public String currentImage;
public fermiPicoNanoImage() throws IOException {
}
public void set(String whichImage) throws IOException, IllegalArgumentException {
whichImage = whichImage.toLowerCase();
try {
if( whichImage == "fermi" || whichImage == "f" ) {
Path filePath = Paths.get("src\\resources\\icon-fermi.png").toAbsolutePath();
image = ImageIO.read( new File( filePath.toString() ) );
currentImage = "fermi";
}
else if( whichImage == "nano" || whichImage == "n" ){
Path filePath = Paths.get("src\\resources\\icon-nano.png").toAbsolutePath();
image = ImageIO.read( new File( filePath.toString() ) );
currentImage = "nano";
}
else if( whichImage == "pico" || whichImage == "p" ) {
Path filePath = Paths.get("src\\resources\\icon-pico.png").toAbsolutePath();
image = ImageIO.read( new File( filePath.toString() ) );
currentImage = "pico";
}else {
throw new IllegalArgumentException();
}
}catch(Exception err) {
System.err.println( err.getMessage() );
err.printStackTrace();
}
this.repaint();
}
public void unset(){
image = null;
currentImage = null;
this.repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(image != null) {
g.drawImage(image, 0, 0, null);
}else if(image == null) {
g.drawImage(image, 0, 0, Color.WHITE, null);
}
}
public static void main(String[] args) throws IOException{
fermiPicoNanoImage fnpImage = new fermiPicoNanoImage();
JFrame frame = new JFrame();
frame.add(fnpImage);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
fnpImage.set("pico");
}
}
呈现所有内容的JFrame在这里。正如其他Stack帖子中所建议的那样,我在框架设置为可见之前添加了组件。我不确定渲染是否存在问题。
现在,由于使用了本地图像,由于找不到本地图像,因此我找不到一种简单的方法来使主类适用于你们,所以我只将整个eclipse项目放入google驱动器文件夹中。
https://drive.google.com/drive/folders/12n-Ze2jivwVJ1XxgQILN5zKNRfZNJ6Z5?usp=sharing
任何有关我需要使组件呈现的建议都将大有帮助。谢谢!
答案 0 :(得分:2)
关于我需要使组件呈现什么的任何建议都会有很大帮助
您是否通过在if条件中添加System.out.println(…)语句来验证代码是否正在执行?
一个可能的问题如下:
else if( whichImage == "pico" || whichImage == "p" ) {
请勿使用“ ==”进行字符串比较。
“ ==”检查对象是否为同一实例,而不是对象的值是否相同。
代替使用equals(…)
方法:
else if( "pico".equals(whichImage) || "p".equals(whichImage) ) {
更改了比较顺序,因此即使“ whichImage”变量为null,它也仍然可以工作。