如何更换点击按钮?

时间:2015-07-05 15:21:26

标签: java button jbutton

嗨我想让我的按钮工作购买按住它一段时间而不是点击它,有问题的按钮只是打开一个新的JFrame,

 button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                frame.dispose();
                new SecondFrame();
            }
        });

感谢,

1 个答案:

答案 0 :(得分:0)

根据Codebender的建议,您可以使用MouseListener代替。mousePressed()mouseReleased()方法。我在每次连续按下/发布之间按currentTimeMillis()计算时间

JFrame f = new JFrame();
JButton b = new JButton();
f.add(b);
f.pack();
f.setVisible(true);
b.addMouseListener(new MouseListener() {
    long start_time, stop_time;
    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {
        start_time = System.currentTimeMillis();
        System.out.println("" + start_time);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        stop_time = System.currentTimeMillis();
        System.out.println("" + stop_time);
        if (stop_time - start_time > 1000) {
            new JFrame().setVisible(true);
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}
}); 

您可以增加或减少给定时间。另请查看MouseAdapter