Java 通过用户输入旋转图形(动画)
我正试图编写一个模拟力的程序,我被困在一个需要按用户输入的角度旋转图形的部分 这里是迄今为止图形的代码Java 通过用户输入旋转图形(动画),java,animation,rotation,Java,Animation,Rotation,我正试图编写一个模拟力的程序,我被困在一个需要按用户输入的角度旋转图形的部分 这里是迄今为止图形的代码 private class MomentsAnimation extends JPanel { int width = 440; int height = 300; int rotationAngle = 60; public MomentsAnimation() { setSize(width, height); setM
private class MomentsAnimation extends JPanel {
int width = 440;
int height = 300;
int rotationAngle = 60;
public MomentsAnimation() {
setSize(width, height);
setMaximumSize(new Dimension(width, height));
setMinimumSize(new Dimension(width, height));
setPreferredSize(new Dimension(width, height));
}
@Override
public void paint(Graphics g) {
int xcentre = width / 2;
int ycentre = height / 2;
g.setColor(Color.lightGray);
g.drawRect(0, 0, width - 1, height - 1);
g.setColor(Color.BLACK);
g.fillOval(xcentre - 5, ycentre - 5, 10, 10); // draw the point of rotation, does not move in the animation
g.setColor(Color.red);
g.fillArc(xcentre - 150, ycentre - 50, 100, 100, 0, 45);
g.setColor(Color.blue);
g.drawLine(xcentre - 100, ycentre, xcentre, ycentre - 100); // draws the diagonal force line
g.setColor(Color.black);
g.drawLine(xcentre - 100, ycentre, xcentre, ycentre); // draws horizontal line of distance from point of rotation
g.drawString("θ", xcentre - 70, ycentre - 10);
}
}
谢谢你的问题的旋转部分。可以将图形对象强制转换为具有旋转方法的Graphics2D对象
Graphics2D g2 = (Graphics2D)g;
然后,您可以通过调用以下命令旋转要绘制的内容:
g2.rotate(radians);
请注意,旋转以弧度为单位,而不是以度为单位。但您可以使用math类在度和弧度之间进行转换,如下所示:
double rad = Math.toRadians(degrees);
至于用户输入,有许多不同的方法可以获得。您可以使用JOptionPane进行GUI样式的输入,也可以使用Scanner类从命令行读取旋转。之后,您可以将给定的旋转作为变量存储在代码中的某个位置,并在绘制方法中使用它
我希望这有帮助:)