如何在每秒后自动点击JButton
?
我已尝试编辑已执行的按钮操作但该功能无效。
答案 0 :(得分:1)
使用SwingTimer
并在按钮上调用doClick
import javax.swing.JButton;
import javax.swing.Timer;
public class ButtonClicker implements ActionListener {
private JButton btn;
private Timer timer;
public ButtonClicker(JButton btn) {
this.btn = btn;
timer = new Timer(1000, this);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
@Override
public void actionPerformed(ActionEvent e) {
btn.doClick();
}
}
有关详细信息,请参阅How to use Swing Timers
答案 1 :(得分:1)
你可以使用swing的 计时器 类和
使用 AbstractButtondoClick 方法。 这是一个完整的源代码。
package stackoverflow;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class JButtonTimer extends JPanel {
private static final long serialVersionUID = 1L;
private static final int SCREEN_WIDTH = 500;
private static final int SCREEN_HEIGHT = 500;
public JButtonTimer() {
final JButton clickBtn = new JButton("clickMe");
clickBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
}
});
add(clickBtn);
Timer timer = new Timer(1 * 1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickBtn.doClick();
}
});
timer.start();
}
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new JButtonTimer());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
答案 2 :(得分:0)
您可以将其放入WindowOpened Frame事件
Timer t = new Timer(1000, jButton.doClick());
t.start();