多线程Swing

时间:2017-09-14 17:29:38

标签: java multithreading swing swingworker cups

我的代码存在问题。我需要监控CUPS服务器,每台打印机都是一个线程:

public static void startCupsMonitor() throws Exception {

    for (CupsPrinter cupsPrinter : PrintJobsUtils.getAllPrinters()) {
        new Thread( new PrinterTask( cupsPrinter.getName() ), cupsPrinter.getName() ).start();
    }
}

如您所见,我为ListJobsUtils.getAllPrinters()中的每个元素启动一个Thread。到目前为止,非常好。

但是我有一个带有JTable的Modal(带有setModal的JDialog设置为true),当新的打印服务到达CUPS服务器时,它将被更新。所以...我创建了一个实现了Runnable接口的类和这个东西:

@Override
public void run() {

    CupsPrinter cupsPrinter;
    PrintQueue printQueue = new PrintQueue();

    try {
        cupsPrinter = PrintJobsUtils.getPrinter( "http://"
                                                     + ApplicationUtils.getApplicationProperties().getProperty( "cups.hostname" )
                                                     + ":" + ApplicationUtils.getApplicationProperties().getProperty( "cups.port" )
                                                     + "/printers/"
                                                     + pName.toUpperCase() );


        while (true) {

            SwingUtilities.invokeLater( () -> {
                List<PrintJobAttributes> printJobAttributesList;
                try {
                    printJobAttributesList = PrintJobsUtils.getAllJobDetails( cupsPrinter );
                    if (!printJobAttributesList.isEmpty()) {
                        for (PrintJobAttributes printJobAttributes : printJobAttributesList) {
                            if (printJobAttributes.getJobState() == JobStateEnum.PENDING_HELD) {
                                printQueue.setVisible( true );
                                if (!ApplicationUtils.cotainsId( printJobAttributes, printQueueArrayList )) {
                                    printQueueArrayList.add( printJobAttributes );

                                    for (PrintJobAttributes jobAttributes : printQueueArrayList) {
                                        printQueue.getDefaultTableModel().addRow( new Object[]{jobAttributes.getJobID(),
                                            jobAttributes.getJobName(), jobAttributes.getSize()} );
                                    }

                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } );
            Thread.sleep( 1000 );
        }
    } catch (Exception e) {

    }

但是这不能正常工作。我期望jtable填充但我得到上面的错误和重复的行。那我该怎么做呢?我试过SwingWorker,但我读过这个课不能重复使用。

编辑

我使用SwingWorker解决了这个问题。谢谢大家

1 个答案:

答案 0 :(得分:0)

Swing无法绑定对象。 然后你可以创建一个包含Jtable的线程并操纵这个对象,并关联模态的Jtable的这个对象,然后它将反映模态。

public class ThRefreshTable extends Thread{
    private JProgressBar barraProgresso = null;

// setJtable      //运行等     }

modal:
 ThRefreshTable th = new ThRefreshTable();
                   th.setJTable(this.table);
th.start();
相关问题