How use a 9-patch image as background on a JPanel?
Asked Answered
R

1

2

I'm searching a way for use a 9-patch file as background for javax.swing.JPanel. So that the background image automatically resizes itself when the dimensions of the JPanel change.

Is it possible? Or I have to create all the pieces of the image and manually resize some of them when the listener triggers (like in the piece of code that follows)?

public class JPanelWithNinePatchBackground extends JPanel { 
{ 
    /* Define all parts of the background like BufferedImage */

    addComponentListener(new ComponentAdapter() { 
        public void componentResized(ComponentEvent e) { 

            // Resize images . . . 

            JPanelWithBackground.this.repaint(); 
        } 
    });

    /* . . . */

}
Rah answered 10/8, 2013 at 12:14 Comment(0)
A
1

Yes, use either of the drawImage() implementations that let you specify the corners of the destination rectangle. The method will complete faster if the source and destination rectangles match in size. RCTile is an example.

Attention answered 10/8, 2013 at 12:28 Comment(5)
Works, but this is not what I want. This solution resizes also the corners, and this should not happen with 9-patch files!Rah
Based on your comment, I'm guessing you want something like this; I'm not aware of an existing component, but drawImage() automatically scales to the destination rectangle.Attention
drawImage() scales the all rectangle. I don't want this. What I want is to use 9-patch images like on Android. Solution that doesn't scale the all rectangle but just some defined parts for let the scaled image perfectly fit the area but keeping corners unchanged. If I wasn't clear enough the link will help you.Rah
Swing doesn't have such a component; you'll have to clarify your use case, for example.Attention
So ok, I have to create my own implementation like in the piece of code that I posted. Thanks for your time.Rah

© 2022 - 2024 — McMap. All rights reserved.