gpt4 book ai didi

java - 在 Eclipse 中将图像添加到 JPanel

转载 作者:行者123 更新时间:2023-12-02 05:56:11 25 4
gpt4 key购买 nike

我的主课中有这个:

panel.setBackground(Color.green);
ImagePanel background = new ImagePanel("Images/background.png");
panel.add(background);

但是当我运行它时,我只看到绿色背景并得到异常:

"javax.imageio.IIOException: Can't read input file!"

这是 ImagePanel 类:

public class ImagePanel extends JPanel {
private BufferedImage img;

public ImagePanel(String path) {
// load the background image
try {
img = ImageIO.read(new File(path));
} catch(IOException e) {
e.printStackTrace();
}
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// paint the background image and scale it to fill the entire space
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}

我正在使用 Eclipse,这是我的图像所在的位置:src/Images/background.png

<小时/>

好的,现在我有:

ImagePanel background = new ImagePanel("src/Images/background.png");

它不再显示异常,但我仍然看不到图像,只有绿色背景......

完整方法如下:

 private void createAndShowGUI() {

frame = new JFrame("Java 2048 By Xandru");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);

panel = new JPanel();
panel.setLayout(null);
panel.setBounds(0, 0, HEIGHT, WIDTH);
panel.setBackground(Color.green);
frame.add(panel);

//Add the background
ImagePanel background = new ImagePanel("src/Images/background.png");
panel.add(background);

//Create the main Frame
frame.pack();

//Set dimensions
frame.setSize(WIDTH, HEIGHT);

//Center it
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((screen.getWidth() - frame.getWidth()) /2);
int y = (int) ((screen.getHeight() - frame.getHeight()) /2);
frame.setLocation(x, y);

//Set visible
frame.setVisible(true);
}

最佳答案

从资源文件夹中查看图像2.png

Image image= ImageIO.read(new File("resources/2.png"));

或者

如果图像位于该类所在的同一包(文件夹)中,请尝试此操作

Image image = ImageIO.read(getClass().getResourceAsStream("2.png"));

这是项目结构

enter image description here

<小时/>

--编辑-

按这个方法试试

EventQueue.invokeLater(new Runnable() {

@Override
public void run() {

try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Java 2048 By Xandru");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);

// Add the background
ImagePanel background = new ImagePanel("src/images/2.png");
frame.add(background);

// Create the main Frame
frame.pack();

// Set dimensions
frame.setSize(new Dimension(width, height));

// Center it
frame.setLocationRelativeTo(null);

// Set visible
frame.setVisible(true);

}
});

关于java - 在 Eclipse 中将图像添加到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23068938/

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