【发布时间】:2020-07-17 08:32:02
【问题描述】:
我已经尝试了好几个小时了。我有一个扩展 JComponent 的类,并且在它的paintComponent 中我试图绘制一个图像,但我做不到。这是我的代码:
public class Main extends JComponent{
public static void main(String[] args) {
Main main = new Main();
JFrame frame = new JFrame(Info.getGameTitle());
frame.add(main);
frame.setSize(Info.getWidth(), Info.getHeight());
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("Window closed");
System.exit(0);
}
});
frame.setAlwaysOnTop(true);
frame.setFocusable(true);
frame.setAutoRequestFocus(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Graphics g = main.getGraphics();
main.paint(g);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = null;
try {
image = ImageIO.read(new FileInputStream("images/01.jpg"));
}catch(FileNotFoundException e) {
System.out.println("Could not find file!");
e.printStackTrace();
}catch(IOException e) {
System.out.println("Could not read file!");
e.printStackTrace();
}
g.drawImage(image, 0, 0, this);
}
}
它没有抛出任何异常,因此图像似乎已加载。但是,屏幕上什么也没有出现。如果我尝试绘制形状或文本,那效果很好。 我做错了什么?
编辑:现在我提供了一个工作示例。
【问题讨论】:
-
考虑提供一个runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将减少混乱并获得更好的响应
-
请注意
paintComponent会经常被称为非常。因此,在那里做一些耗时的事情(比如读取图像文件)并不是一个好主意 -
JLabel有什么问题? -
我测试了你的代码变体,它对我来说很好
标签: java swing bufferedimage jcomponent