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

1 回答 1

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

于 2012-06-08T17:02:11.920 回答