我想用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
}
图像如下: 什么可能是错的?
由于
答案 0 :(得分:2)
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,这样您就可以决定组件的使用时间和位置,使其更加实用。
有关在Swing中绘画的更多详情,请查看Performing Custom Painting和Painting in AWT and 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();
}
}
}