【发布时间】:2023-04-11 03:27:02
【问题描述】:
我同时打开了两个窗口,所以现在单击第一个窗口框架中的 Jbutton 我的 Jlabel 值应该在第二个窗口框架中更新或更改....我的问题是我在我的情况下使用观察者模式代码工作得很好我能够捕捉到最新的更新值,但是在更新标签时给 settext 它没有得到更新
1] 这是我的函数(在更改临时值并单击第一帧中的更新按钮时调用).. 我在 Observable 类中使用的这个函数--
public void updatetemp(int temp) {
System.out.println("when temp is updated "+temp);
this.temp = temp;
setChanged(); // it says that we have changed somethoing so you need to notify observers
System.out.println("uiyh");
notifyObservers(temp); //notify
System.out.println("notified");
}
2] 现在它会通知观察者这里有温度变化,我期待我的 curTempLbl.setText("" + curTempupd);在代码中应该更新第二帧中的更改值......但它没有得到更新...... 注意:如果您看到我在设置 jlabel 之前和之后给出了 system.out.println,我能够捕捉到正确的更新值......但它没有在 Jlabel 中得到更新,请帮助
public void update(Observable obj, Object arg1) {
// TODO Auto-generated method stub
if(arg1 instanceof Integer){
int curTempupd = ((Integer)arg1).intValue();
System.out.println("inside update value --------"+curTempupd);
WeatherTablePanel frame = new WeatherTablePanel(weatherDb);
frame.setVisible(true);
curTempLbl.setText("" + curTempupd);
//curTempLbl.repaint();
System.out.println("after update value --------"+curTempupd);
}
这是我希望我的 Jlabel 更新的框架的代码
public WeatherTableFrame(WeatherDb weatherdb) {
weatherTblUI = new WeatherTableUI(weatherdb);
WindowListener exitListener = new FrameTerminator();
addWindowListener(exitListener);
setTitle("Weather Table");
setSize(575,265);
add(weatherTblUI);
}
// another class
public WeatherTableUI(WeatherDb weatherDb) {
weatherTblPanel = new WeatherTablePanel(weatherDb);
addNewLocPanel = new AddNewLocPanel(weatherDb, weatherTblPanel);
setLayout(new BorderLayout());
add(weatherTblPanel, "Center");
add(addNewLocPanel, "South");
removeBtnPanel.add(removeLocBtn);
add(removeBtnPanel, "East");
removeLocBtn.addActionListener(this);
}
3] 在weatherTblPanel 中我正在尝试更新Jlabel 值
我在更新函数代码中使用了线程,但仍未更新,请帮助
@Override
public void update(Observable obj, Object arg1) {
// TODO Auto-generated method stub
if(arg1 instanceof Integer){
int curTempupd = ((Integer)arg1).intValue();
System.out.println("inside update value --------"+curTempupd);
//
new Thread(){
public void run(){
try{Thread.sleep(2000);
}catch(InterruptedException ie){ie.printStackTrace();}
SwingUtilities.invokeLater(new Runnable(){
public void run(){
curTempLbl.setText("" + 89);
}
});
}
}.start();
//
//setVisible(true);
//curTempLbl.repaint();
System.out.println("after update value --------"+curTempupd);
}
【问题讨论】:
-
所以,...没有您的代码...我们应该猜测您可能做错了什么...。怎么办?说真的,请给我们足够的信息,这样我们就不必做出疯狂的猜测,最好是MCVE。请查看链接了解这个非常有用的工具的详细信息。
-
1] 这是我的 Observable 类的函数 /*12280sv*/ public void updatetemp(int temp) { System.out.println("when temp is updated "+temp); this.temp = 温度; setChanged(); // 它说我们有 chansomethoing //所以你需要通知观察者 System.out.println("before");通知观察者(临时); //通知 System.out.println("notified"); } /*12280sv*/
-
1) 请不要在 cmets 中发布代码,因为它会丢失格式使其无法读取。相反,通过editing your question 将任何新代码发布到原始问题的底部。 2) 你真的应该考虑创建和发布minimal code example program 以便我们了解你的问题。
-
嘿,我猜对了。请参阅编辑以回答。
标签: java swing thread-sleep observable