java画直线_用Java画线

论坛 期权论坛 脚本     
已经匿名di用户   2022-3-21 23:59   3860   0

一个小动画向您展示了您需要在行旋转方面寻找的逻辑。可以把这条线想像成时钟上的指针。如何在时钟上设置一只手的动画。这几乎是完全相同的概念。唯一的不同是x1(指针的中心点的x点)而不是保持静止,而是在指针旋转时沿x轴线(y1恒定)移动。因此,对于时钟的每个刻度(指针旋转),x位置也会水平移动。我就是这样看的。

在此处输入图片说明

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import java.util.List;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.Timer;

public class Main {

public static void main(String[] a) {

JFrame window = new JFrame();

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

window.setResizable(false);

window.getContentPane().add(new MyCanvas());

window.pack();

window.setVisible(true);

}

}

class MyCanvas extends JPanel {

int x1 = 0;

int rotate = 50;

List lines;

Timer timer = null;

public MyCanvas() {

lines = new ArrayList<>();

timer = new Timer(75, new ActionListener() {

public void actionPerformed(ActionEvent e) {

if (rotate < -50) {

((Timer) e.getSource()).stop();

} else {

lines.add(new Line(x1, rotate));

repaint();

x1 += 5;

rotate--;

}

}

});

JButton start = new JButton("Start the Magic");

start.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

timer.start();

}

});

add(start);

}

public Dimension getPreferredSize() {

return new Dimension(502, 400);

}

private static final long serialVersionUID = 1L;

public void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(Color.BLACK);

g.fillRect(0, 0, getWidth(), getHeight());

for (Line line : lines) {

line.drawLine(g);

}

}

class Line {

int x1;

int rotate;

int y1 = 200;

public Line(int x1, int rotate) {

this.x1 = x1;

this.rotate = rotate;

}

void drawLine(Graphics g) {

int Radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);

int sLength = (int) (Radius * 0.9);

int xSecond = (int) (x1 + sLength * Math.sin(rotate * (2 * Math.PI / 100)));

int ySecond = (int) (y1 - sLength * Math.cos(rotate * (2 * Math.PI / 100)));

g.setColor(Color.GREEN);

g.drawLine(x1, y1, xSecond, ySecond);

}

}

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP