gpt4 book ai didi

java - 将 JLabel 旋转 90 度 Java

转载 作者:行者123 更新时间:2023-12-02 07:45:26 25 4
gpt4 key购买 nike

我在 Jlabel 中有一个图像,我想在用户按下按钮时将其旋转 90 度。我自己尝试过,但出现了各种错误。有人告诉我最好的方法是使用 Graphics2D?

主类:

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

按钮:

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

最佳答案

您永远不应该使用 Component.getGraphics() 在组件上绘图。相反,您应该始终覆盖paintComponent并使用传递给它的Graphics对象。

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

关于java - 将 JLabel 旋转 90 度 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com