旋转 Java 图形 2D 矩形?
2022-09-02 09:28:32
我到处寻找,我只是找不到答案。
如何在java中旋转矩形?
这是我的一些代码:
package net.chrypthic.Space;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Space extends JPanel implements ActionListener{
Timer time;
public Space()
{
setVisible(true);
setFocusable(true);
addMouseMotionListener(new ML());
addMouseListener(new ML());
addKeyListener(new AL());
time=new Timer(5, this);
time.start();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.WHITE);
Rectangle rect2 = new Rectangle(100, 100, 20, 20);
g2d.draw(rect2);
g2d.fill(rect2);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
public class AL extends KeyAdapter
{
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
public class ML extends MouseAdapter
{
public void mouseMoved(MouseEvent e) {
}
public void mousePressed(MouseEvent e){
}
}
}
我试过g2d.rotate(100D);但它不起作用。提前致谢。
这是我编辑的代码:
package net.chrypthic.Space;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Space extends JPanel implements ActionListener{
Timer time;
public Space()
{
setVisible(true);
setFocusable(true);
setSize(640, 480);
setBackground(Color.BLACK);
time=new Timer(5, this);
time.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
Rectangle rect1 = new Rectangle(100, 100, 20, 20);
g2d.setColor(Color.WHITE);
g2d.translate(rect1.x+(rect1.width/2), rect1.y+(rect1.height/2));
g2d.rotate(Math.toRadians(90));
g2d.draw(rect1);
g2d.fill(rect1);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
}