为什么图像不在jpanel上显示?

发布于 2025-01-25 08:28:15 字数 1291 浏览 3 评论 0原文

我想在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昵称有卵用 2025-02-01 08:28:15

在方法paintcomponent()中尝试使用此方法:

g.drawimage(img.getImage(), 0, 0, null); 

Try with this in the method paintComponent():

g.drawimage(img.getImage(), 0, 0, null); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文