我想用 Java 旋转图片来执行此页面中的代码:
http://beginwithjava.blogspot.com/2009/02/rotating-image-with-java.html
到目前为止,我所做的是打开一个新的 JFrame,并在其中放置一个带有 jLabel 的 jPanel;这个 jLabel 使用 icon 属性将我的图像加载到标签中。之后,我从标签中选择了单击鼠标事件并输入以下代码:
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
Graphics2D g2d=(Graphics2D)g; // Create a Java2D version of g.
g2d.translate(170, 0); // Translate the center of our coordinates.
g2d.rotate(1); // Rotate the image by 1 radian.
g2d.drawImage(image, 0, 0, 200, 200, this);
}
它编译时没有错误,但是当我单击标签时,出现以下错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javaapplication74.NewJFrame.jLabel1MouseClicked(NewJFrame.java:94)
at javaapplication74.NewJFrame.access$000(NewJFrame.java:17)
at javaapplication74.NewJFrame$1.mouseClicked(NewJFrame.java:50)
at java.awt.Component.processMouseEvent(Component.java:6508)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
有什么办法可以解决这个问题吗?
第 94 行的错误指向:
g2d.translate(170, 0);
我添加了以下代码,但图像不旋转:
package javaapplication74;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
/**
*
* @author
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
// Create a constructor method
Image image;
Graphics g;
int angle;
public NewJFrame() {
initComponents();
image = Toolkit.getDefaultToolkit().getImage("download.jpg");
}
public void paintComponent(Graphics g){
Graphics2D g2d;
g2d=(Graphics2D)g; // Create a Java2D version of g.
g2d.translate(60, 0); // Translate the center of our coordinates.
g2d.rotate(angle); // Rotate the image by 1 radian.
g2d.drawImage(image, 0, 0, 200, 200, this);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\Documents\\NetBeansProjects\\JavaApplication74\\src\\javaapplication74\\download.jpg")); // NOI18N
jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel1MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel1)
.addContainerGap(20, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel1)
.addContainerGap(27, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(261, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(141, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
angle=20;
jLabel1.repaint();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
图片如下: 可能出了什么问题?
谢谢
最佳答案
Swing 中的绘制应该在 paintComponent
方法的上下文中完成,如您的示例所示。
您应该做的是在您的mouseClicked
方法中设置一个充当当前旋转角度的变量并调用repaint
然后,在您的 paintComponent
方法中,您执行以下操作...
Graphics2D g2d=(Graphics2D)g; // Create a Java2D version of g.
g2d.translate(170, 0); // Translate the center of our coordinates.
// You'll need to define angleOfRotatiomInRadians
// as an instance variable like image
g2d.rotate(angleOfRotatiomInRadians); // Rotate the image by 1 radian.
g2d.drawImage(image, 0, 0, 200, 200, this);
根据原始问题的更改进行更新
所以根据您的示例代码...
错误#1:
public class NewJFrame extends javax.swing.JFrame
因为...
错误#2:
public void paintComponent(Graphics g){
如果您使用了@Override
注释,编译器会告诉您您正在尝试重写父类层次结构中不存在的方法,这将是您首先要做的警钟长鸣。
这意味着,您的 paintComponent
方法永远不会被调用,因为顶级容器(如 JFrame
)实际上没有 paintComponent
> 方法。由于多种原因,您还应该避免从顶层容器延伸或直接绘制到顶层容器。
除了双缓冲问题之外,这还会将您置于单个容器中,从而导致难以重用 UI。相反,您应该尝试在 JPanel
上创建 UI 作为基础,这使您可以决定何时何地应使用该组件,从而使其更加可用。
看看Performing Custom Painting和 Painting in AWT and Swing有关在 Swing 中绘画的更多详细信息
错误#3:
jLabel1.repaint();
不会做太多事情,因为它包含对图像的未修改引用的引用,因此重新绘制它实际上不会做太多事情,因为您正在尝试自己绘制图像,使用标签根本就是浪费时间
错误#4:
当您确实不确定自己在做什么时,依赖表单编辑器。表单编辑器是一个强大的工具,但您需要先了解 UI API 的工作原理,然后才能真正使用它。
我还鼓励开发人员从 UI 开始编写代码,这将使您更好地了解可以实现的目标以及何时使用编辑器和何时不使用编辑器。
自定义绘画不是一个简单的话题,尤其是当您对底层 API 没有太多经验时。花一些时间熟悉 Swing API 中的可用功能、它的工作原理以及何时应该深入研究并做自己的事情。
举个例子...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RotateImage {
public static void main(String[] args) {
new RotateImage();
}
public RotateImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new RotatePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class RotatePane extends JPanel {
private double imageRotationAngle = 0;
private BufferedImage img;
public RotatePane() {
try {
img = ImageIO.read(new File("Java.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
imageRotationAngle += Math.toRadians(1);
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight()- img.getHeight()) / 2;
g2d.translate(x, y);
g2d.rotate(imageRotationAngle, img.getWidth() / 2, img.getHeight() / 2);
g2d.drawImage(img, 0, 0, this);
g2d.dispose();
}
}
}
关于java - 图像在 netbeans 中不旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24051573/