Java 摆动,以特定角度画一条线?

Java Swing, draw a line at a specific angle?

我用 Java 制作了一个 JSlider,它改变了线条需要倾斜的角度。

angle = new JSlider(SwingConstants.HORIZONTAL, 0, 180, 90);
angle.setSize(300, 50);
angle.setLocation(650, 60);
angle.setPaintTicks(true);
angle.setPaintTrack(true);
angle.setMinorTickSpacing(10);
angle.setMajorTickSpacing(30);
angle.setPaintLabels(true);
angle.addChangeListener(this);

thepanel.add(angle);

我希望代码绘制实现 JSlider 角度的线。

这是我的代码:

public void paintComponent(Graphics g){
    super.paintComponent(g);

    int angle = intAngle;
    Graphics2D graphics = (Graphics2D)g;

    int startX = getWidth()/2;
    int startY = getHeight()/2;
    int length = 200;


    int endX = startX + length * (int)Math.cos(Math.toRadians(angle));
    int endY = startY + length * (int)Math.sin(Math.toRadians(angle));

    graphics.drawLine(startX, startY, endX, endY);

}

给定值旋转直线背后的数学原理是什么?

第 1 步:扩展 JPanel 并覆盖 paintComponent()。您已经提到您已经完成了这一步,但我们提供了更多信息 here

第 2 步:将 JSlider 的值放入 paintComponent() 方法中。

第 3 步:向 JSlider 添加一个侦听器,告诉您的 JPanel 在值更改时重新绘制自身。

第四步:用基本的三角函数计算出要画的线的X和Y坐标,然后画出来。它可能看起来像这样:

public void paintComponent(Graphics g){
   super.paintComponent(g);
   int angle = getSliderValue(); //you have to implement this function

   int startX = getWidth()/2;
   int startY = getHeight()/2;
   int length = 100;

   int endX = startX + (int)Math.cos(Math.toRadians(angle)) * length;
   int endY = startY + (int)Math.sin(Math.toRadians(angle)) * length;

  g.drawLine(startX, startY, endX, endY);
}