ImG*_*e98 0 java user-interface swing
你怎么画一条线,但不是在瞬间,而是慢慢地像你实际上在一张纸上画一条线.另外你如何控制画线的速度?主要是在另一个刚刚启动程序的类中.
public class Moving extends JPanel implements ActionListener {
Timer time = new Timer(5000, this);
boolean rotation1 = false;
public Moving() {
addKeyListener(new TAdapter());
setFocusable(true);
initGame();
}
public void initGame() {
time.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.RED);
if(rotation1) {
for(int p = 0; p < 600; p++) {
this.setBackground(Color.BLUE);
g.drawRect(10, p, 20, 20);
}
}
}
public void start() {
Moving game = new Moving();
JFrame frame = new JFrame("Frame");
frame.setSize(320, 340);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_1) {
rotation1 = true;
}
}
public void keyReleased(KeyEvent e) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
您无法在该paintComponent方法中尝试执行动画.这将阻止事件调度线程,防止实际绘制任何东西(除其他外).
你需要做的是在后台等待一段特定的时间,然后更新状态并重新绘制.
虽然,有很多方法可以实现这一点,最简单的就是使用a javax.swing.Timer
这允许您指定延迟时段,当触发时,它会在EDT的上下文中进行回调,从而可以安全地从内部更新UI
查看Event Dispatching Thread以及如何使用Swing Timers获取更多详细信息
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |