问题描述
我用Java创建了一个JSlider,它改变了线需要倾斜的角度。
I made a JSlider with Java that changes the angle the line needs to be slanted at.
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角度的那条线。
I want the code to draw that line that implements the angle from the 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);
}
给定值旋转一条线后面的数学是什么?
What is the mathematics behind rotating a line given a value?
推荐答案
第1步:扩展 JPanel
并覆盖的paintComponent()
。您已经提到已经执行了此步骤,但有更多信息可供 。
Step 1: Extend JPanel
and override paintComponent()
. You've mentioned you already do this step, but more info is available here.
第2步:将 JSlider
的值输入 paintComponent()
方法。
Step 2: Get the value of your JSlider
into your paintComponent()
method.
步骤3:向 JSlider
添加一个监听器,告诉你的 JPanel
每当值发生变化时重绘自己。
Step 3: Add a listener to the JSlider
that tells your JPanel
to repaint itself whenever the value changes.
步骤4:使用基本三角法计算X和Y坐标要绘制的线,然后绘制它。它可能看起来像这样:
Step 4: Use basic trigonometry to figure out the X and Y coordinates of the line to draw, then draw it. It might look something like this:
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);
}
这篇关于Java Swing,以特定角度绘制一条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!