这是我的第一个 Swing 应用程序,所以我使用了 NetBeans GUI Builder。有一个开始按钮开始模拟(两个循环:外部按天和内部按小时)。在每次迭代中,循环都应该暂停。当您单击停止按钮时,模拟应该停止。我尝试了以下方法:1)
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
Timer timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
while(presentDay <= numberOfDays){
jTextField2.setText(Integer.toString(presentDay));
for(; presentTime <= 18; presentTime++){
jTextField6.setText(Integer.toString(presentTime));
StringBuilder res = new StringBuilder();
for(Event ev: schedule[presentDay-1].day){
if((presentTime <= ev.getTimeFinish()) && (presentTime >= ev.getTimeStart())){
res.append(ev);
ev.setStatus(1);
}
}
currentEvent.setText(res.toString());
// Pause should here
}
presentTime = 9;
presentDay++;
}
}
});
timer.start();
}
2) 在主类构造函数中添加 Timer
public PlanningSystem() {
initComponents();
...
timer = new Timer(5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
while(presentDay <= numberOfDays){
jTextField2.setText(Integer.toString(presentDay));
for(; presentTime <= 18; presentTime++){
jTextField6.setText(Integer.toString(presentTime));
StringBuilder res = new StringBuilder();
for(Event ev: schedule[presentDay-1].day){
if((presentTime <= ev.getTimeFinish()) && (presentTime >= ev.getTimeStart())){
res.append(ev);
ev.setStatus(1);
}
}
currentEvent.setText(res.toString());
// Pause here
}
presentTime = 9;
presentDay++;
}
}
});
}
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
timer.start();
}
但两种方法都不起作用。我希望你能帮助解决这个问题。对不起我的英语:)
==================================================== ===================== 编辑后:
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
if(presentDay <= numberOfDays){
jTextField2.setText(Integer.toString(presentDay));
Timer tim = new Timer (5000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(presentTime <= 18){
jTextField6.setText(Integer.toString(presentTime));
StringBuilder res = new StringBuilder();
for(Event ev: schedule[presentDay-1].day){
if((presentTime <= ev.getTimeFinish()) && (presentTime >= ev.getTimeStart())){
res.append(ev);
ev.setStatus(1);
}
}
currentEvent.setText(res.toString());
presentTime++;
}
}
});
tim.start();
presentTime = 9;
presentDay++;
}
}