Adding an image to a JPanel background

后端 未结 2 463
有刺的猬
有刺的猬 2021-01-22 12:00

How can I add an image to a JPanel background. The image will not be scaled or resized. Thanks.

相关标签:
2条回答
  • 2021-01-22 12:53
    /**
     * @author
     *
     */
    public class ImagePanel extends JPanel {
    
        private Image image = null;
    
        public ImagePanel(String filename) {
            this.image = new ImageIcon(filename).getImage();
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            ImagePanel panel = new ImagePanel("resources/image.jpg");
    
            JFrame frame = new JFrame("Frame");
            frame.setSize(800, 600);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.getContentPane().add(panel, BorderLayout.CENTER);
            frame.setVisible(true);
        }
    }
    
    0 讨论(0)
  • 2021-01-22 13:03

    You can override one of these methods:

    JComponent.paint(Graphics g)
    JComponent.paintComponent(Graphics g)
    
    0 讨论(0)
提交回复
热议问题