我想在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中的绘画应该在画布组件
方法的上下文中完成。
您应该做的是设置一个变量,该变量充当您的鼠标点击
方法中的当前旋转角度并调用repaint
然后,在您的画家组件
方法中,您执行以下操作…
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){
如果您使用了@Overwrite
注释,编译器会告诉您正在尝试覆盖父类层次结构中不存在的方法,这将是您的第一个警钟。
这意味着,您的画布组件
方法将永远不会被调用,因为顶级容器,如JFrame
实际上没有画布组件
方法。出于多种原因,您还应该避免从顶级容器扩展或直接绘制到顶级容器。
除了双缓冲问题之外,这将使您进入单个容器,难以重用UI。相反,您应该尝试在JPanel
上创建UI作为基础,这允许您决定何时何地应该使用组件,使其更有用。
查看在AWT和Swing中执行自定义绘画和绘画,了解有关在Swing中绘画的更多详细信息
错误#3:
jLabel1.repaint();
不会做太多,因为它包含对未修改的图像引用的引用,所以重新绘制它不会做太多,事实上,因为你试图自己绘制图像,使用标签只是浪费时间
错误#4:
当您真的不确定自己在做什么时,请依赖表单编辑器。表单编辑器是一个强大的工具,但是在真正使用它之前,您需要了解UIAPI的工作原理。
我还鼓励开发人员首先将代码交给UI,它将让您更好地了解可以实现的目标以及何时使用和何时不使用编辑器。
自定义绘画不是一个简单的话题,尤其是当你对底层API没有太多经验的时候。花些时间熟悉SwingAPI中的可用内容,它是如何工作的,以及何时应该投入并做自己的事情。
作为一个例子…
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();
}
}
}