【发布时间】:2017-05-03 01:16:36
【问题描述】:
我有一个小程序,它从 JDateChooser 组件输入日期并计算从现在到输入日期的天数。它使用 MVC 模式,在 Netbeans IDE 中编码,并计算正确的天数,但不显示在 JLabel 的“labelDays”中。当我输入 labelDays.setText("29") 时,它可以工作,当我获得 labelDays.getText() 的值时,它会检索正确的未来天数,并且 strDays 是正确的,但标签不显示更新的价值。这是示例代码:
model:
public class CountDownModel {
public LocalDate getCurrentDate() {
return LocalDate.now();
}
public long getDays(LocalDate futureDate) {
long daysBetween = DAYS.between(LocalDate.now(), futureDate);
if(daysBetween <= 0) {
return 0;
}
return daysBetween;
}
view:
public class CountDownView extends javax.swing.JFrame {
...
private CountDownController controller = new CountDownController();
public CountDownView() {
initComponents();
Date input = new Date();
Instant instant = input.toInstant();
Date output = Date.from(instant);
future_date.setDate(output);
}
private void button_calculateMouseClicked(java.awt.event.MouseEvent evt) {
Date futureDate;
futureDate = future_date.getDate();
String strDate = DateFormat.getDateInstance().format(futureDate);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate localDate = LocalDate.parse(strDate, formatter);
controller.setDays(localDate);
}
...
public void setDays(long days) {
String strDays = String.valueOf(days);
System.out.print("strDays:");
System.out.println(strDays);
String oldValue = labelDays.getText();
labelDays.setText(strDays);
labelDays.paintImmediately(labelDays.getVisibleRect());
String newValue = labelDays.getText();
System.out.print("oldValue:");
System.out.println(oldValue);
System.out.print("newValue:");
System.out.println(newValue);
System.out.println("================");
}
}
controller:
public class CountDownController {
public void startApplication() {
CountDownView view = new CountDownView();
view.setDays(0);
view.setVisible(true);
}
public void setDays(LocalDate futureDate) {
CountDownModel model = new CountDownModel();
CountDownView view = new CountDownView();
long longDays = model.getDays(futureDate);
if(longDays <= 0) {
longDays = 0;
}
view.setDays(longDays);
}
}
main:
public class DateCountDown {
public static void main(String[] args) {
// TODO code application logic here
CountDownController controller = new CountDownController();
controller.startApplication();
}
}
Output:
run:
strDays:0
oldValue:200
newValue:0
================
strDays:28
oldValue:200
newValue:28
================
谢谢。我需要做什么才能让它工作? PS:我想知道我的错误是否是由于我设置 MVC 的方式造成的。
菲利普
【问题讨论】:
标签: model-view-controller netbeans jlabel jdatechooser