I have created a form that contains various Jtextfields to display data. The data comes from an internet source and changes very frequently (every few seconds). I'm not sure the best way about doing it.
So far I have a class that retrieves the data upon request and stores the data locally. The data then can be retrieved using the getters and a timer.
eg.
class Grabber(){
static String data;
static void update(String source){
//update data from source
}
static String getData(){
return data;
}
}
Then in the form file, MyForm.java I have:
Timer timer = new Timer(2000, performUpdate);
timer.start();
....
ActionListener performUpdate = new ActionListener(){
public void actionPerformed(ActionEvent evt){
Grabber.update();
jTextField1.setText(Grabber.getData());
}
};
I believe this would work, but I'm not sure if this is the best way to do it and I just want to check I'm not doing something stupid. I thought about having the timer inside the Grabber function, and then calling a function inside MyForm updateData(String data)
I think this would be nicer, but then it adds a dependency on the GUI which doesn't seem right.
Another issue is that I intend to have a few sources. Performing the updates in my proposed manner would require serial 开发者_Python百科internet requests which may be better done in parallel? I would like the data to be as up to date as possible.
Apologies if this is not a typical question, but I'm just looking for other ideas on how to implement this.
Update your model in a separate thread at whatever rate is appropriate for the source, perhaps using SwingWorker
as suggeted in this example. Publish those results to interested views only when the data actually changes.
精彩评论