我有一个带有几个JPanel的JFrame。一个是带有JButtons的GridLayout(4乘4)的boardPanel。另一个是controlPanel,它有一个包含JTextField和两个JButton的FlowLayout。
我有两个方法enableBoard()和disableBoard()。在那些方法中,我通过for循环将boardPanel和controlPanel中的每个组件setEnabled()设置为true或false。这一切都发生在摆动计时器运行时。当我启动计时器并因此启动enableBoard()(它通过disableBoard禁用)它有点工作,但往往有一个延迟,所以不是所有按钮在同一时刻被禁用,我怀疑它与计时器有关因为延迟似乎在几秒钟内发生......以下是重要的方法:
public void disableBord() {
Component[] boardcomps = boardPanel.getComponents();
for(int i = 0; i < bordcomps.length; i++) {
boardcomps[i].setEnabled(false);
}
Component[] checkComps = controlPanel.getComponents();
for(int i = 0; i < checkComps.length; i++) {
checkComps[i].setEnabled(false);
}
}
public void enableBord() {
Component[] boardcomps = boardPanel.getComponents();
for(int i = 0; i < bordcomps.length; i++) {
boardcomps[i].setEnabled(true);
}
Component[] checkComps = controlPanel.getComponents();
for(int i = 0; i < checkComps.length; i++) {
checkComps[i].setEnabled(true);
}
}
运行的计时器:
timer = new Timer(1000, new ActionListener() {
int time = game.getSeconds()+4;
@Override
public void actionPerformed(ActionEvent e) {
if (time == game.getSeconds()+4) {
lblFeedback.setText("3");
lblTime.setText(game.secToMinSec(game.getSeconds()));
time--;
} else if (time == game.getSeconds()+3) {
lblFeedback.setText("2");
lbltime.setText(game.secToMinSec(game.getSeconds()));
time--;
} else if (time == game.getSeconds()+2) {
lblFeedback.setText("1");
lblTime.setText(game.secToMinSec(game.getSeconds()));
time--;
} else if (time == game.getSeconds()+1) {
lblFeedback.setText("Start!");
lblTime.setText(game.secToMinSec(time));
time--;
enableBord();
} else if(time == 0) {
lblTime.setText("0:00");
lblFeedback.setText("Game finished!");
disableBord();
game.endeGame();
timer.stop();
} else if (time == game.getSeconds()) {
lblTime.setText(game.secToMinSec(time));
time--;
} else {
lblTime.setText(game.secToMinSec(time));
time--;
}
}
});
延迟看起来像这样:
答案 0 :(得分:1)
适当的重绘();循环中的每个setEnable()似乎都解决了我的问题!