如题 想达到像 https://www.xiwnn.com/piano/ 的效果
目前的问题是无法使用第二次线程 只能用一次 想要能重复使用并同时使用这个线程 达到连续的效果 不知道要改repaint还是怎么样的
请教一下各位要怎么改 或是 各位遇到这个题目会如何去实现 感谢各位 !
JAVA
目前的程式码
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.ArrayList;
import java.util.EventObject.*;
import java.util.logging.Handler;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class FrameTest extends JFrame {
private final JLabel label1;
private final JButton button1;
private final int SCREEN_WIDTH = 1000;
private final int SCREEN_HEIGHT = 1000;
private final int LIGHT_ORIGINAL_Y_POS = 910;
private int lightYPos = LIGHT_ORIGINAL_Y_POS;
Timer timer;
public FrameTest() {
super();
setLayout(null);
setTitle("视窗名");
setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
MouseAdapter handler = new MyMouseAdapter();
label1 = new JLabel("钢琴动画测试");
label1.setBounds(10, 0, 100, 50);
add(label1);
button1 = new JButton("我是白键");
button1.addMouseListener(handler);
button1.setBounds(450, 900, 100, 50);
add(button1);
}
public void update(Graphics g) {
this.paint(g);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.fillRect(458, lightYPos, 100, 20);
}
public class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
new Thread(new ActionThread()).start();
// SwingUtilities.invokeLater(new ActionThread()); 有人告诉我试试看用这个 可是用这个图形无法移动
}
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
}
private class ActionThread implements Runnable {
public void run() {
System.out.print("线程启动\n");
int i = 1;
while (true) {
if (lightYPos < 0) {
// thread = null;
break;
}
repaint();
lightYPos -= 5;
System.out.print(i++ + "\n");
try {
Thread.sleep(10);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
JFrame frameObject = new FrameTest();
frameObject.setVisible(true);
}
}