How to show pictures in jFrame, using java2d?

前端 未结 3 2017
温柔的废话
温柔的废话 2020-12-12 08:13

I\'m new on working with Java and Netbeans. In many others languages, it\'s a simple stuff to do. But after broke my brain thinking, I couldn\'t. My doubt is simple to expla

3条回答
  •  半阙折子戏
    2020-12-12 08:46

    You need, as was told below to extend JPanel class and override paintComponent method in it.

    public class DrawImageClass extends JPanel {
        private static final long serialVersionUID = 1L;
        private Image image;
        public DrawImageClass(Image image) throws HeadlessException {
            super();
            this.image = image;
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D)g;
            g2d.drawImage(image, null, null);
        }
    }
    

    And then create JFrame and add this class to it.

    public class App {
        private static final int WIDTH=480, HEIGHT = 640;
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(new Dimension(HEIGHT, WIDTH));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            try {
                DrawImageClass panel = new DrawImageClass(ImageIO.read(new File(App.class.getResource("/1.png").getPath())));
                panel.setPreferredSize(new Dimension(HEIGHT, WIDTH));
                frame.add(panel);
                frame.setVisible(true);
            } catch (Exception e) {
                System.out.println("wrong path or smth other");
            }  
        }
    }
    

    Example for picture which is in resource folder in project

提交回复
热议问题