我正在尝试根据当前时间启用/禁用jbutton。应用程序更大,我有一套药物有一套药物。如果当前时间在某个药物摄入间隔内,则我要启用一个按钮。按钮只是拒绝启用。这是我的密码:
public class MainPanel implements Runnable {
private Thread thread;
public MainPanel(){
....ui code
contentPanel.add(yourMedicationPlansLabel);
...
root.setLayout(null);
root.add(contentPanel);
root.setSize(200, 200);
thread = new Thread(this);
thread.start();
}
@Override
public void run() {
if(medicationPlanSet != null){
updateMedicationPlans(medicationPlanSet);
}
while(thread.isAlive()) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM yyyy, EEEE, HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
time.setText("Today is " + dtf.format(now) + ".");
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
root.getRootPane().updateUI();
}
}
这是更新方法:
public void updateMedicationPlans(Set<MedicationPlan> medicationPlanSet)
for (MedicationPlan medicationPlan : medicationPlanSet) {
for (Medication medication : medicationPlan.getMedicationSet()) {
JLabel medicationLabel = new JLabel(medication.getName() + " " + medication.getDosage() + " mg");
medicationLabel.setBounds(10, y, 200, 30);
medicationLabel.setForeground(Color.decode("#3e0103"));
button = new JButton("Taken");
button.setBounds(320, y, 80, 30);
button.setForeground(Color.decode("#3e0103"));
button.setEnabled(false);
JPanel checksPanel = new JPanel();
checksPanel.setLayout(null);
checksPanel.setBackground(Color.white);
checksPanel.setBounds(210, y + 5, 100, 20);
int x = 0;
boolean inTime = false;
String[] intakeIntervals = medicationPlan.getIntakeInterval().split(",");
for(String intakeInterval : intakeIntervals) {
String from = intakeInterval.split("-")[0].concat(":00");
String to = intakeInterval.split("-")[1].concat(":00");
if(checkTime(from, to)){
inTime = true;
}
System.out.println(inTime);
JLabel canBeTakenLabel = new JLabel();
canBeTakenLabel.setBounds(x, 0, 20, 20);
canBeTakenLabel.setIcon(canBeTakenImage);
checksPanel.add(canBeTakenLabel);
x += 25;
}
if(inTime) {
button.setEnabled(true);
root.repaint();
}
contentPanel.add(button);
contentPanel.add(medicationLabel);
contentPanel.add(checksPanel);
y += 30;
}
}
}
还尝试将update方法放入while(isalive)和root.updateui()中,但没有任何效果。
1条答案
按热度按时间ih99xse11#
我不知道什么有效,试试看
button.repaint()
或者尝试重新绘制父面板(在这种情况下-contentPanel
). 有时重新粉刷不起作用,如果我不知道为什么,我会设置vibisle:这是肯定的,但不是一个很好的解决方案