0

I have an image within a Jlabel which I want to rotate 90 degrees right when the user hits the button. I've attempted it myself, but with various errors. I was told the best way to do it was to use Graphics2D?

Main Class:

private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {        
BufferedImage image;
        try {
            image = ImageIO.read(file);
            Image scaled = image.getScaledInstance(Jlabel1.getWidth(), Jlabel1.getHeight(), 5);
            Jlabel1.setIcon(new ImageIcon(scaled));

Button:

 private void rotateButtonActionPerformed(java.awt.event.ActionEvent evt) {
        Graphics2D userImage = (Graphics2D)JLabel1.getGraphics();
    userImage.rotate(Math.toRadians(90));
    userImage.drawImage(JLabel1, JLabel1.getHeight(), JLabel1.getWidth());
    }
Adam Hinx
  • 215
  • 3
  • 21
  • 2
    *"aren't even worth posting"* Leads to the feeling 'not even worth answering'. – Andrew Thompson Jun 08 '12 at 15:48
  • 1
    "arent even worth posting" meaning they were well off what was needed........ – Adam Hinx Jun 08 '12 at 15:49
  • 1
    So you basically decided to post nothing of relevant code, and ask us how to do this. So I am missing some crucial information: where do I need to send my invoice to ? – Robin Jun 08 '12 at 16:02
  • I'm not asking you to code it for me. I'm just simply asking if Graphics2D is the best method of getting such result. – Adam Hinx Jun 08 '12 at 16:06

1 Answers1

2

You should never ever use Component.getGraphics() for drawing on a component. Instead, you should always overwrite paintComponent and work with the Graphics object that gets passed to it.

Component.getGraphics() simply can't work. Java uses a callback mechanism for drawing graphics. You are not supposed to "push" graphics information into a component using getGraphics(). Instead you are supposed to wait until Java calls your paint()/paintComponent() method. At that moment you are supposed to provide the Component with the drawings you would like to do.

This mechanism is necessary so Java can support graphics systems which don't remember window contents when it is obscured (e.g. overlayed by another window). When the window becomes visible again, such graphics systems have to ask the application to reconstruct the window content. Therefore, paint()/paintComponent() is supposed to be the memory of a component. getGraphics(), however, doesn't have any recollection of previous drawing operations. So once a drawing done via getGraphics() is lost, it can't be reconstructed. There is nothing in there that stores the old drawing data, and there is nothing in AWT/Swing which informs getGraphics() to do some re-drawing.

In addition, there are situations where Component.getGraphics() simply returns null. This is a defined behavior of the method. And finally, most users of getGraphics() forget to dispose the Graphics object after usage.

http://www.pscode.org/guifaq.html

lbalazscs
  • 17,474
  • 7
  • 42
  • 50