好的,首先要注意的是:
- 不要使用
Thread.sleep()
它更新您的GUI,这会阻止EDT - 您没有将程序放在EDT上,请参见此答案中的第2点
- 不要扩展Jframe,而是创建它的实例,请参见:扩展Jframe与在程序内部创建它
setVisible(...)
在将所有组件添加到程序之前,不要使其可见(即,调用)。这可能会导致您的程序以错误的方式运行。尝试不要创建自己的线程,而是使用
aSwing Timer
或aSwing Worker
(问题注释中的链接)
因此,考虑到所有这些因素后,我决定创建一个
遵循上述所有规则的新程序,并
在这段时间过后使单元格变蓝3秒钟或变白,并更新JButton
以及禁用防止一次执行多个计时器。import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.Jframe;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;public class Test {
private Jframe frame;
private JPanel pane;
private JPanel cellsPane;
private MyCell[][] cells;
private JButton button;
private Timer timer;private int counter = 3;private boolean isFinished = false;public static void main(String[] args) { SwingUtilities.invokeLater(() -> new Test().createAndShowGui());}private void createAndShowGui() { frame = new Jframe(getClass().getSimpleName()); pane = new JPanel(); cellsPane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS)); cellsPane.setLayout(new GridLayout(4, 4, 5, 5)); cells = new MyCell[4][4]; for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[i].length; j++) { cells[i][j] = new MyCell(Color.WHITE); cellsPane.add(cells[i][j]); } } button = new JButton("Press me!"); timer = new Timer(1000, listener); button.addActionListener(e -> { button.setEnabled(false); isFinished = false; updateCellsColors(); timer.start(); }); pane.add(cellsPane); pane.add(button); frame.add(pane); frame.pack(); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.setVisible(true);}private void updateCellsColors() { for (int i = 0; i < cells.length; i++) { for (int j = 0; j < cells[i].length; j++) { cells[i][j].setCellColor(isFinished ? Color.WHITE : Color.BLUE); } }}private ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (counter == 0) { timer.stop(); counter = 3; isFinished = true; button.setEnabled(true); updateCellsColors(); } if (isFinished) { button.setText("Press me!"); } else { button.setText("You have " + counter + " seconds remaining"); } counter--; }};
}
@SuppressWarnings(“serial”)
class MyCell extends JPanel {
private Color cellColor;public Color getCellColor() { return cellColor;}public void setCellColor(Color cellColor) { this.cellColor = cellColor; this.setBackground(cellColor);}public MyCell(Color cellColor) { this.cellColor = cellColor; this.setOpaque(true); this.setBackground(cellColor);}@Overridepublic Dimension getPreferredSize() { // TODO Auto-generated method stub return new Dimension(30, 30);}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)