2017-09-14 107 views
0

我的代碼存在一些問題。我需要監控CUPS服務器至極每個打印機是一個線程:多線程擺動

public static void startCupsMonitor() throws Exception { 

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

正如你所看到的,我啓動一個線程在我的名單()的每個元素被稱爲在PrintJobsUtils.getAllPrinters。到現在爲止還挺好。

但我有一個Modal(JDialog,setModal設置爲true)帶有一個JTable,它將在新的打印服務到達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解決了這個問題。謝謝所有

+0

@JB Nizet,我的問題是不是空點。 –

+0

然後修復它,併發布您關心的實際問題。請注意,「它不起作用」並沒有告訴我們任何事情,關於你期望發生什麼以及發生什麼。另請注意,您**不得**在除EDT以外的任何線程中使用揮杆組件或其模型。 –

回答

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();