我正在尝试暂停我的程序并一直在使用Thread.Sleep()。在阅读了这个问题后,我试图实现一个Swing Timer。但是,似乎Swing计时器触发了ActionEvents ...我只想暂停程序执行并在以下内容之间进行JLabel更改
mPlayerLastRollLabel.setText("Player rolled: ...");
//PAUSE
mPlayerLastRollLabel.setText("Player rolled: " + mFaceNumber);
如何在下面的情况下使用计时器暂停我标记它的程序:
class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (mPlayerTurn && event.getSource() == playerRollButton) {
mFaceNumber = rollDie();
mPlayerLastRollLabel.setText("Player rolled: ...");
**// want to pause here //**
mPlayerLastRollLabel.setText("Player rolled: " + mFaceNumber);
if (mFaceNumber != 1) {
mSubTotal += mFaceNumber;
mPlayerSubtotalLabel.setText("Player's current subtotal: " + mSubTotal);
}
else {
mSubTotal = 0;
mPlayerSubtotalLabel.setText("Player's current subtotal: " + mSubTotal);
mPlayerTurn = false;
mComputerTurn = true;
}
}
if (mPlayerTurn && event.getSource() == playerEndTurnButton) {
mPlayerTotalScore += mSubTotal;
mPlayerCurrentTotalScoreLabel.setText("Player's current total score: " + mPlayerTotalScore);
mSubTotal = 0;
System.out.println(mPlayerTotalScore);
mPlayerTurn = false;
mComputerTurn = true;
}
if (mComputerTurn && event.getSource() == computerRollButton) {
mFaceNumber = rollDie();
mComputerLastRollLabel.setText("Computer rolled: " + mFaceNumber);
if (mFaceNumber != 1)
mSubTotal += mFaceNumber;
else {
mSubTotal = 0;
mPlayerTurn = true;
mComputerTurn = false;
}
}
if (mComputerTurn && event.getSource() == computerEndTurnButton) {
mComputerTotalScore += mSubTotal;
mSubTotal = 0;
System.out.println(mComputerTotalScore);
mPlayerTurn = true;
mComputerTurn = false;
}
}
}
答案 0 :(得分:3)
这是因为swing定时器是异步的。因此,您必须将代码的第二行(以及所有后续逻辑)放入动作侦听器中,如:
@Component({
selector: 'my-app',
template: `
<button (click)="addComponents()">Add HTML (dynamically using CRF)</button>
<h1>Angular2 AppComponent</h1>
<hr>
<div>
<h5>sub1.html goes here</h5>
<div class="container">
<template #subContainer1></template>
</div>
</div>
<hr>
<h5>sub2.html goes here</h5>
<div class="container">
<template #subContainer2></template>
</div>
`,
})
export class App {
name:string;
@ViewChild('subContainer1', {read: ViewContainerRef}) subContainer1: ViewContainerRef;
@ViewChild('subContainer2', {read: ViewContainerRef}) subContainer2: ViewContainerRef;
constructor(
private compFactoryResolver: ComponentFactoryResolver
) {
this.name = 'Angular2'
}
addComponents() {
let compFactory: ComponentFactory;
compFactory = this.compFactoryResolver.resolveComponentFactory(Part1Component);
this.subContainer1.createComponent(compFactory);
compFactory = this.compFactoryResolver.resolveComponentFactory(Part2Component);
this.subContainer2.createComponent(compFactory);
}
}
}
或者你可以将睡眠后的下半部分放入单独的函数中并从actionPerfomed方法调用它。这样做而不是Thread.sleep你释放图形线程(这是所有UI的一个),直到你的睡眠时间到了。如果不释放图形线程,那么你的UI就会冻结,因为没有线程可以对用户操作作出反应。