Background image for a jPanel not working

后端 未结 1 1426
死守一世寂寞
死守一世寂寞 2020-11-28 16:24

I am new to making GUIs so I decided to try the the windows builder for eclipse, and while great I do have some doubts. I have been searching but I cannot seen to find a goo

相关标签:
1条回答
  • 2020-11-28 17:10

    A simple method, if you're not interested in resizing the background image or applying any effects is to use a JLabel...

    BufferedImage bg = ImageIO.read(Menu.class.getResource("/imgs/rotom.jpg"));
    JLabel label = new JLabel(new ImageIcon(bg));
    setContentPane(label);
    setLayout(...);
    

    There are limitations to this approach (beyond scaling), in that the preferred size of the label will always be that of the image and never take into account it's content. This is both good and bad.

    The other approach, which you seem to be using, is to use a specialised component

    public class BackgroundPane extends JPanel {
    
        private BufferedImage img;
    
        public BackgroundPane(BufferedImage img) {
            this.img = img;
        }
    
        @Override
        public Dimension getPreferredSize() {
            return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, this);
        }
    }
    

    You should avoid trying to perform any task in the paintComponent method which may take time to complete as paintComponent may be called often and usually in quick succession....

    Getting the image to scale when the component is resized is an entire question into of it self, for some ideas, you could take a look at...

    • Java: maintaining aspect ratio of JPanel background image
    • Java: JPanel background not scaling
    • Quality of Image after resize very low -- Java
    • Reading/Loading images

    Oh, and, you should avoid extending directly from top level containers, like JFrame, they reduce the reusability for your components and lock you into a single container

    0 讨论(0)
提交回复
热议问题