想為按鈕添加線程,點擊後讓組件按速度移動。
**不需要也不建議為按鈕創建線程**。Swing/AWT 事件分發線程(EDT)處理 UI 更新,若在新線程中直接操作組件會導致併發問題,仍需 `SwingUtilities.invokeLater` 回到 EDT,等同單線程。
Timer timer = new Timer(50, new ActionListener() { // 50ms 間隔
@Override
public void actionPerformed(ActionEvent e) {
component.setLocation(component.getX() + 5, component.getY()); // 移動邏輯
if (到達目標) ((Timer)e.getSource()).stop();
}
});
button.addActionListener(e -> timer.start());
不要用 `Thread.sleep` 循環或 `new Thread` 直接操作組件屬性。