How do I draw an image to a JPanel or JFrame?

后端 未结 2 1289
无人及你
无人及你 2020-11-30 11:04

How do I draw an Image to a JPanel or JFrame, I have already read oracle\'s tutorial on this but I can\'t seem to get it right. I need the image \"BeachRoad.png

相关标签:
2条回答
  • 2020-11-30 11:49

    There are a lot of methods, but I always override the paint(Graphics g) of a JComponent and use g.drawImage(...)

    edit: I was making a sample, but tieTYT did it perfectly, look at his answer :)

    0 讨论(0)
  • 2020-11-30 11:53

    Try this:

    package com.sandbox;
    
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.WindowConstants;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    public class SwingSandbox {
    
        public static void main(String[] args) throws IOException {
            JFrame frame = buildFrame();
    
            final BufferedImage image = ImageIO.read(new File("C:\\Projects\\MavenSandbox\\src\\main\\resources\\img.jpg"));
    
            JPanel pane = new JPanel() {
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.drawImage(image, 0, 0, null);
                }
            };
    
    
            frame.add(pane);
        }
    
    
        private static JFrame buildFrame() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(200, 200);
            frame.setVisible(true);
            return frame;
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题