[英]Why does the image not show up on the JPanel?
I want to draw an image on a JPanel
which is displayed on a JFrame
.我想在JFrame
上显示的JPanel
上绘制图像。 I tested the paint method without the frame and it seemed to work, but as soon as I added the image on the frame it won't get shown.我在没有框架的情况下测试了绘制方法,它似乎可以工作,但是一旦我在框架上添加了图像,它就不会显示出来。 Instead I only see a very small square which displays a small area of the image.相反,我只看到一个非常小的正方形,它显示图像的一小块区域。
Here's my code so far:到目前为止,这是我的代码:
TestFrame
class: TestFrame
类:public class TestFrame extends JFrame {
private JFrame frame = new JFrame();
private JPanel jp = new JPanel();
public MyFrame() {
frame.setTitle("test");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
jp.setBackground(Color.YELLOW);
frame.add(jp, BorderLayout.CENTER);
jp.add(new DrawPanel());
jp.repaint();
frame.setVisible(true);
}
}
DrawPanel
class: DrawPanel
类:public class DrawPanel extends JPanel {
private BufferedImage img;
public DrawPanel() {
try {
img = ImageIO.read(getClass().getResourceAsStream("/resources/heart.jpg"));
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
}
在方法paintComponent()
中尝试这个:
g.drawimage(img.getImage(), 0, 0, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.