When using OSXAdapter to handle double-clicking JAR files associated with your application on macOS, you may encounter issues with lag or the application terminating. This could be due to blocking the event dispatch thread (EDT).
Solution:
To resolve this issue, consider the following:
Use SwingWorker or Runnable:
Remove the Sleep on the EDT:
Alternative Approaches:
Avoid JAR Bundler:
MVC Architecture:
Addendum:
Code Snippet:
The following code demonstrates how to use a Runnable to perform the task and avoid blocking the EDT:
import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class TableAddTest extends JPanel implements Runnable { private static final int N_ROWS = 8; private static String[] header = {"ID", "String", "Number", "Boolean"}; private DefaultTableModel dtm = new DefaultTableModel(null, header); private JTable table = new JTable(dtm); private JScrollPane scrollPane = new JScrollPane(table); public TableAddTest() { this.setLayout(new BorderLayout()); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); this.add(scrollPane, BorderLayout.CENTER); JPanel panel = new JPanel(); panel.add(new JButton(new AbstractAction("Add Row") { @Override public void actionPerformed(ActionEvent e) { EventQueue.invokeLater(TableAddTest.this); } })); this.add(panel, BorderLayout.SOUTH); } private void addRow() { dtm.addRow(new Object[]{ Character.valueOf('A' + dtm.getRowCount()), Character.valueOf('A') + dtm.getRowCount(), Integer.valueOf(dtm.getRowCount()), Boolean.valueOf(dtm.getRowCount() % 2 == 0) }); } @Override public void run() { addRow(); table.scrollRectToVisible(table.getCellRect(dtm.getRowCount() - 1, 0, true)); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new TableAddTest()); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); new Thread(new TableAddTest()).start(); } }); } }
Note: The highlighted portions of the code show how to use EventQueue.invokeLater() to update the GUI on the EDT while using a Runnable to perform the task.
The above is the detailed content of Why is my macOS JAR application lagging or crashing when using OSXAdapter, and how can I fix it?. For more information, please follow other related articles on the PHP Chinese website!