为什么图像不在jpanel上显示?
我想在jpanel
上绘制图像,该图像显示在jframe
上。我在没有框架的情况下测试了油漆方法,并且似乎可以工作,但是一旦在框架上添加图像就不会显示出来。相反,我只看到一个很小的正方形,它显示图像的一小部分。
到目前为止,这是我的代码:
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:
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);
}
}
I want to draw an image on a JPanel
which is displayed on a JFrame
. 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:
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:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在方法
paintcomponent()
中尝试使用此方法:Try with this in the method
paintComponent()
: