Java新手需要有关如何显示按钮移动的建议

时间:2015-03-26 15:29:47

标签: java loops jbutton

当我将文本输入文本屏幕时,我试图让一个按钮在屏幕上移动,我想出了这个代码但是当我真正想要看到它移动时它最终显示结束位置:

if (TextDemo.textField.getText().equals("moveCar"))
    {

        for (int x = 0; x<250;x++)
        {

            try
            {
            Thread.sleep(10);
            }catch
            (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }   
            jOneCarOne.setLocation(130 + x, 210);
            }                                   
    }

我确实有一个重绘方法,但它没有任何区别,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

查看此MCVE

public class TextDemo {
    static JFrame frame;
    static JTextField textField;
    static Component jOneCarOne;

    public static void main(String[] args) {
        frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLayout(null);
        frame.setSize(640, 480);
        frame.setLocationRelativeTo(null);

        textField = new JTextField();
        textField.setBounds(0, 0, 640, 20);
        textField.addActionListener(getTextFieldAction());
        frame.add(textField);

        jOneCarOne = new JLabel("<html><b><u>CAR");
        jOneCarOne.setBounds(130, 210, 64, 64);
        frame.add(jOneCarOne);

        frame.setVisible(true);
    }

    static ActionListener getTextFieldAction() {
        return new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (TextDemo.textField.getText().equals("moveCar")) {
                    moveCar();
                }
            }
        };
    }

    static void moveCar() {
        final int endX = jOneCarOne.getX() + 250;
        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerTask() {
            //execute this every 10 ms
            @Override
            public void run() {
                if(jOneCarOne.getX() == endX) {
                    //break condition, cancel periodic execution
                    this.cancel();
                }
                jOneCarOne.setLocation(jOneCarOne.getX() + 1, jOneCarOne.getY());
            }
        }, 0, 10);
    }
}