完成此 *** 作后,我不完全相信SwingWorker是一个更简单(又称更好)的解决方案-仍然需要其他线程同步(在工作线程和传入文件/名称的“外部”线程之间)。无论如何(利用学习的机会,并避免错误:),以下是基本思想的概念证明示例:
- 将Controller实现为SwingWorker,它将来自外线程的输入汇集到EDT中
- 通过doWork(..)方法使其接受输入(来自适配器,fi),该方法将输入排队以便发布
- 实现doInBackground以成功发布输入
开放式问题
public class GUI { private Jframe frame = new Jframe(); private DefaultTableModel model = new DefaultTableModel(); private JTable table = new JTable(model); private JScrollPane pane = new JScrollPane(table); public GUI() { model.addColumn("Name"); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.add(pane); frame.pack(); frame.setVisible(true); } public void addRow(String name) { model.addRow(new Object[] { name }); } public static class Controller extends SwingWorker<Void, String> { private GUI gui; private List<String> pending; public Controller() { gui = new GUI(); } public void doWork(String newline) { if (pending == null) { pending = new ArrayList<String>(); pending.add(newline); execute(); } else { pending.add(newline); } } @Override protected Void doInBackground() throws Exception { while (pending.size() > 0) { publish(pending.remove(0)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } @Override protected void process(List<String> chunks) { for (String object : chunks) { gui.addRow(object); } } } public static class Adapter implements Runnable { Controller controller; public Adapter(Controller controller) { this.controller = controller; } @Override public void run() { for (int i=0; i<10; i++) { controller.doWork("Line "+(i+1)); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { System.err.println("Initializing controller"); new Adapter(new Controller()).run(); } @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(GUI.class.getName());}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)