我面对一件事。我有从手机到计算机的数据,它们显示在JFrame窗口中。我决定尝试使用SwingWorker,以便在不打开新窗口的情况下加载新数据。现在它看起来像这样:答案来了 - 打开一个新窗口,加载数据,而旧窗口保持打开状态直到程序结束。我编写了doInBackground()方法的实现,但我确信我做错了。你能帮助理解如何最好地实现它,并修复我的方法doInBackground()。接收到的数据将写入HashMap,然后传递给SimpleTableDemo类。提前谢谢。
public class SimpleTableDemo extends JFrame {
private static final String[] columnNames = { "Судья", "Ответ" };
private final JTable table;
private static SwingWorker swingWorker;
public SimpleTableDemo() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 0));
table = new JTable(new Object[0][0], columnNames) {
@Override
public Class getColumnClass(int column) {
switch (column) {
case 1:
return String.class;
default:
return Object.class;
}
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
table.setPreferredScrollableViewportSize(new Dimension(500, 80));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
pack();
setVisible(true);
swingWorker = new SwingWorker() {
// I need help in this method
@Override
protected Object doInBackground() throws Exception {
Thread.sleep(1000);
return true;
}
};
}
//Receive data from another class
public void setData(Map<Object,String> map) {
Object[][] data = map.entrySet()
.stream()
.map(e -> new Object[] { e.getKey(), e.getValue() })
.toArray(Object[][]::new);
table.setModel(new DefaultTableModel(data, columnNames));
}
// setData in JFrame
private static void start() {
SimpleTableDemo demo = new SimpleTableDemo();
Map<Object,String> map = new HashMap<>();
demo.setData(map);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleTableDemo::start);
}
}