JPanel with image background

后端 未结 2 1825
既然无缘
既然无缘 2020-12-03 22:39

How to put image background on JPANEL?

JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)); 
pDraw.setPreferredSize(new Dimension(600,600)); //size of t         


        
相关标签:
2条回答
  • 2020-12-03 23:05

    It is probably easiest to load the Image into an ImageIcon and display it in a JLabel, however:
    To directly 'draw' the image to the JPanel, override the JPanel's paintComponent(Graphics) method to something like the following:

    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);
        page.drawImage(img, 0, 0, null);
    }
    

    where img is an Image (possibly loaded through the ImageIO.read() call).

    Graphics#drawImage is a heavily overloaded command which will allow you to be highly specific in how, how much, and where you paint the image to the component.

    You can also get 'fancy' and scale the image to your pleasing using the Image#getScaledInstance method. This will take a -1 for either the width or the height parameter in order to keep the aspect ratio of the image the same.

    Putting it in a more fancy way:

    public void paintComponent(Graphics page)
    {
        super.paintComponent(page);
    
        int h = img.getHeight(null);
        int w = img.getWidth(null);
    
        // Scale Horizontally:
        if ( w > this.getWidth() )
        {
            img = img.getScaledInstance( getWidth(), -1, Image.SCALE_DEFAULT );
            h = img.getHeight(null);
        }
    
        // Scale Vertically:
        if ( h > this.getHeight() )
        {
            img = img.getScaledInstance( -1, getHeight(), Image.SCALE_DEFAULT );
        }
    
        // Center Images
        int x = (getWidth() - img.getWidth(null)) / 2;
        int y = (getHeight() - img.getHeight(null)) / 2;
    
        // Draw it
        page.drawImage( img, x, y, null );
    }
    
    0 讨论(0)
  • 2020-12-03 23:16

    Here's an explanation.

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