This program is one part of the GUI part for my reminder program.
I would like to update the JTable which shows all the task and will refresh every 2 second.
I have questions...
(1)the SwingWorker never executes( I put println in the code but it shows nothing )
How to make it work?
(2) If I remove SwingWorker, but I have the timer, there will be a lot of exceptions appear.. why?
(3) Is there a way to refresh everytime data(taskHashMap) change???
Thank you very much
package gui;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import Storage.Task;
import Storage.TaskHashMap;
public class AutoUpdateJTable {
private JTable jTable;
private DefaultTableModel model;
private Vector<String> listLabel = new Vector<String>();
AutoUpdateJTable(final JTable jTable){
this.jTable = jTable;
model = (DefaultTableModel) this.jTable.getModel();
SwingWorker<JTable, Void> worker = new SwingWorker<JTable, Void>() {
@Override
protected JTable doInBackground() throws Exception {
// TODO Auto-generated method stub
System.out.println("enter swing");
Timer timer = new Timer(2000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//updateJTable();
makeJLabel(new Task());
setAppearance();
System.out.println(listLabel.get(0).toString());
}
});
timer.start();
timer.setRepeats(true);
return null;
}
};
}
private void setAppearance() {
jTable.setRowHeight(30);
while(model.getRowCount()>0)
model.removeRow(0);
jTable.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
model.addRow(listLabel);
System.out.println(listLabel.toString());
}
private void makeJLabel(Task task) {
task = new Task("test");
String str;
str = "<HTML><b>"
+ task.getName() + " "
//+ task.getDescription() + " "
+ "</HTML>";
listLabel.add(str);
System.out.println(listLabel.toString());
}
private void makeAllJLabel(TaskHashMap taskHashMap) {
int length = 0;
for(int i=0; i<length; i++) {
makeJLabel(new Task());
}
}
private void updateJTable() {
//retrieve TaskHashMap
listLabel = new Vector<String>();
TaskHashMap taskHashMap = new TaskHashMap();
makeAllJLabel(taskHashMap);
setAppearance();
}
class MyRenderer extends DefaultTableCellRenderer {
/*
* @see TableCellRenderer#getTableCellRendererComponent(JTable, Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
JLabel label = new JLabel(value.toString());
return label;
}
}
}