我试图编写一个模拟力的程序,并且我被困在我需要按照用户输入的角度旋转图形的部分。
这里到目前为止图形的代码。
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);
}
}
由于
答案 0 :(得分:0)
至于问题的旋转部分。您可以将Graphics对象转换为具有rotate方法的Graphics2D对象。
Graphics2D g2 = (Graphics2D)g;
然后你可以通过调用来旋转你要绘制的内容:
g2.rotate(radians);
请注意,旋转将以弧度给出,而不是以度为单位。但你可以使用数学类来转换度数和弧度,如下所示:
double rad = Math.toRadians(degrees);
对于用户输入,有许多不同的方法可以获得它。您可以使用JOptionPane作为GUI样式输入,也可以使用Scanner类从命令行读取旋转。之后,您可以将给定的旋转作为变量存储在代码中的某个位置,并在paint方法中使用它。
我希望这会有所帮助:)