gpt4 book ai didi

java - 按钮 Action 监听器

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:01 25 4
gpt4 key购买 nike

好的,所以我编写了一个简单的程序,每次单击按钮时都会将值添加到计数器中。现在,我想添加“自动”按钮功能以在单击“自动”按钮时增加计数器的值。我遇到了问题,因为它不会在屏幕上呈现每个计数器值,而是在循环完成时更新值。这是我的代码:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
import javax.swing.JFrame;


public class Gui extends JFrame{

private static final long serialVersionUID = 1L;

private JButton uselesButton;

private JButton autoButton;

private FlowLayout layout;
private long counter = 0;

public Gui() {
super("Button");
layout = new FlowLayout(FlowLayout.CENTER);
this.setLayout(layout);

uselesButton = new JButton(String.format("Pressed %d times", counter));
add(uselesButton);
uselesButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
counter++;
uselesButton.setText(String.format("Pressed %d times", counter));
}

});

autoButton = new JButton("Auto");
add(autoButton);
autoButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
for(long i =0; i < 99999999;i++) {
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e1) {
System.out.println("ERROR");
}
counter = i;
uselesButton.setText(String.format("Pressed %d times", counter));
}
}
});
}
}

请记住,我是初学者...感谢所有帮助:)

最佳答案

查看有关如何使用的教程 Swing Timer然后看看我的解决方案:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Gui extends JFrame {

private static final long serialVersionUID = 1L;
private JButton uselesButton;
private JButton autoButton;
private FlowLayout layout;
private long counter = 0;
private javax.swing.Timer timer;

public Gui() {
super("Button");
layout = new FlowLayout(FlowLayout.CENTER);
setLayout(layout);
setDefaultCloseOperation(3);
setSize(300, 300);
setLocationRelativeTo(null);

//initialing swing timer
timer = new javax.swing.Timer(100, getButtonAction());

autoButton = new JButton("Auto");
add(autoButton);
autoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!timer.isRunning()) {
timer.start();
} else {
timer.stop();
}
}
});
}

private ActionListener getButtonAction() {
ActionListener action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
autoButton.setText(String.format("Pressed %d times", ++counter));
if (counter > 1000) {
timer.stop();
}
}
};
return action;
}

public static void main(String... args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Gui().setVisible(true);
}
});
}
}

关于java - 按钮 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com