更新时间:2023-12-04 15:50:58
以下是与闪存组件相关的问题和几个答案。
Here is a question and several answers related to flashing a component.
附录:您可以在文章 如何使用按钮中了解更多信息 。特别是,您可以使用 setForeground()
来更改按钮文本的颜色,但相应的 setBackground()
在某些平台上读得不好。使用 Border
是另一种选择;如下所示,彩色面板是另一个。
Addendum: You can learn more in the article How to Use Buttons. In particular, you can use setForeground()
to change the color of a button's text, but the corresponding setBackground()
doesn't read well on some platforms. Using a Border
is one alternative; a colored panel, shown below, is another.
package overflow;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class ButtonTest extends JPanel implements ActionListener {
private static final int N = 4;
private static final Random rnd = new Random();
private final Timer timer = new Timer(1000, this);
private final List<ButtonPanel> panels = new ArrayList<ButtonPanel>();
public ButtonTest() {
this.setLayout(new GridLayout(N, N, N, N));
for (int i = 0; i < N * N; i++) {
ButtonPanel bp = new ButtonPanel(i);
panels.add(bp);
this.add(bp);
}
}
@Override
public void actionPerformed(ActionEvent e) {
for (JPanel p : panels) {
p.setBackground(new Color(rnd.nextInt()));
}
}
private static class ButtonPanel extends JPanel {
public ButtonPanel(int i) {
this.setBackground(new Color(rnd.nextInt()));
this.add(new JButton("Button " + String.valueOf(i)));
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("ButtonTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonTest bt = new ButtonTest();
f.add(bt);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
bt.timer.start();
}
});
}
}