I faced with one thing. I have data from the phone to the computer and they are displayed in the JFrame window. I decided to try to do with SwingWorker, so that it loads new data, without opening new windows. Now it looks like this: the answer came - a new window opens with the data loaded, while the old window remains open until the end of the program. I wrote the implementation of the doInBackground () method, but I'm sure I did everything wrong. Could you help to understand how this is best implemented, and also fix my method doInBackground (). The data, when received, is written to the HashMap and then passed to the SimpleTableDemo class. Thank you in advance.
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);
}
}