画一条线不是瞬间的

时间:2014-01-27 01:31:55

标签: java swing user-interface

你怎么画一条线,但不是瞬间,但慢慢地就像你实际上在一张纸上画一条线。另外你如何控制画线的速度?主要是在另一个刚刚启动程序的类中。

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) {
        }
    }
}

1 个答案:

答案 0 :(得分:6)

您无法在paintComponent方法中尝试执行动画。这将阻止事件调度线程,防止实际绘制任何东西(除其他外)。

您需要做的是在后台等待一段特定时间,然后更新状态并重新绘制。

虽然有很多方法可以实现这一点,但最简单的方法是使用javax.swing.Timer

这允许您指定一个延迟期,当触发时,它会在EDT的上下文中进行回调,从而可以安全地从内部更新UI

请查看Event Dispatching ThreadHow to use Swing Timers了解详情