gpt4 book ai didi

java - 定期更改 JButton 文本

转载 作者:行者123 更新时间:2023-11-29 07:19:01 25 4
gpt4 key购买 nike

我想创建一个 JButton,它在第一次单击后定期更改其文本。我对 Swing 库不是很熟悉。什么是好的起点?我可以不采取任何行动来更新其文本吗?

谢谢。

最佳答案

对于 Swing 中的所有定期事件,我只建议 javax.swing.Timer

使用Timer输出应该是,例如

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;

public class CrazyButtonTimer {

private JFrame frame = new JFrame(" Crazy Button Timer");
private JButton b = new JButton("Crazy Colored Button");
private Random random;

public CrazyButtonTimer() {
b.setPreferredSize(new Dimension(250, 35));
frame.getContentPane().add(b);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
javax.swing.Timer timer = new Timer(500, new TimerListener());
timer.setInitialDelay(250);
timer.start();
}

private class TimerListener implements ActionListener {

private TimerListener() {
}

@Override
public void actionPerformed(final ActionEvent e) {
Color c = b.getForeground();
if (c == Color.red) {
b.setForeground(Color.blue);
} else {
b.setForeground(Color.red);
}
}
}

public static void main(final String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
CrazyButtonTimer crazyButtonTimer = new CrazyButtonTimer();
}
});
}
}

关于java - 定期更改 JButton 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6912615/

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