当用户点击按钮时,我有一个正在旋转的图像.但它没有用.
我想看到图像逐渐旋转到90度直到它停止但它没有.单击按钮时,图像必须逐渐旋转90度.
我创建了一个SSCCE来演示这个问题.请使用CrossingPanelSSCE您选择的任何图像替换班级中的图像.只需将图像放入您的images文件夹并命名即可images/railCrossing.JPG.
RotateButtonSSCE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
public class RotateButtonSSCE extends JPanel implements ActionListener{
private JButton rotate = new JButton("Rotate");
private VisualizationPanelSSCE vis = new VisualizationPanelSSCE();
public RotateButtonSSCE() {
this.setBorder(BorderFactory.createTitledBorder("Rotate Button "));
this.rotate.addActionListener(this);
this.add(rotate);
}
public void actionPerformed(ActionEvent ev) {
vis.rotatetheCrossing();
}
}
Run Code Online (Sandbox Code Playgroud)
CrossingPanelSSCE
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import …Run Code Online (Sandbox Code Playgroud) 我试图在JPanel中绘制一个矩形,它可以平移,然后自行旋转以模仿汽车的运动.我已经能够使矩形平移和旋转,但它围绕(0,0)的原点旋转.我非常高兴能够让矩形移动和旋转,因为我是Java GUI的新手,但我似乎无法得到如何使矩形围绕自身旋转,因为我尝试了更多它,当我初始化矩形并将其旋转45度,它的位置发生了变化,我假设是旋转方法附加的变换矩阵.
我通过网站查看了如何解决这个问题,但是我只找到了如何旋转矩形而不是如何旋转和移动模拟汽车的运动.我认为它关注它的变换矩阵,但我只是在猜测.所以我的问题是如何让矩形能够旋转并在自身周围移动而不是JPanel中的一个点.
这是我到目前为止提出的代码:
public class Draw extends JPanel implements ActionListener {
private int x = 100;
private int y = 100;
private double theta = Math.PI;
Rectangle rec = new Rectangle(x,y,25,25);
Timer timer = new Timer(25,this);
Draw(){
setBackground(Color.black);
timer.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.white);
rec.x = 100;
rec.y = 100;
g2d.rotate(theta);
g2d.draw(rec);
g2d.fill(rec);
}
public void actionPerformed(ActionEvent e) {
x = (int) (x + (Math.cos(theta))*1);
y = (int) (y + (Math.sin(theta))*1);
theta = …Run Code Online (Sandbox Code Playgroud) 我试图通过特定的theta旋转Rectangle2D对象.但是我不能这样做,因为Rectangle2D的方法转换(AffineTransform)是未定义的.有关如何做到这一点的任何想法?谢谢.
Rectangle2D.Double currentVehic = new Rectangle2D.Double(bottomLeft[0], bottomLeft[1],vehicWidth, vehicHeight);
// Rotate the vehicle perimeter about its center
AffineTransform rotate = new AffineTransform();
//Rectangle2D rotatedVehic = AffineTransform.getRotateInstance(theta,x,y);
rotate.setToRotation(theta, x, y);
currentVehic.transform(rotate);
return currentVehic;
Run Code Online (Sandbox Code Playgroud)