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(); 
        } 
    });

    /* . . . */

}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Nicola
  • 395
  • 2
  • 13

1 Answers1

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Works, but this is not what I want. This solution resizes also the corners, and this should **not** happen with 9-patch files! – Nicola Aug 10 '13 at 13:04
  • Based on your comment, I'm guessing you want something like [this](http://developer.android.com/tools/help/draw9patch.html); I'm not aware of an existing component, but `drawImage()` automatically scales to the destination rectangle. – trashgod Aug 10 '13 at 16:53
  • `drawImage()` scales the all rectangle. I don't want this. What I want is to use [9-patch](http://developer.android.com/tools/help/draw9patch.html) 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. – Nicola Aug 10 '13 at 17:11
  • Swing doesn't have such a component; you'll have to clarify your use case, for [example](http://stackoverflow.com/a/14599176/230513). – trashgod Aug 10 '13 at 17:36
  • So ok, I have to create my own implementation like in the piece of code that I posted. Thanks for your time. – Nicola Aug 10 '13 at 18:40