刷新jtable而不显示结果多次

时间:2016-04-27 00:11:12

标签: java button jtable refresh

我有一个通过单击按钮刷新的jtable。但每次单击刷新按钮时,都会再次显示相同的结果。

*例如,我第一次点击刷新jtable上显示的结果是:

名称

*我第二次点击刷新结果是:

名称

姓氏

名称

同样的结果是重复的。 即使我多次单击刷新按钮,我应该如何获得一次结果?

包含刷新按钮的类:ModalityWorklist.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author Dell
 */



public class ModalityWorklist extends javax.swing.JFrame {
    private String[] args;
   public static File file;
    public static String Name;
    public static String id;
    public static Object[] row;

    /**
     * Creates new form ModalityWorklist
     */
    public ModalityWorklist(){
        initComponents();


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        modalityWorklist = new javax.swing.JTable();
        refresh = new javax.swing.JButton();
        ok = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        modalityWorklist.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Patient ID", "Patient Name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        modalityWorklist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                modalityWorklistMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(modalityWorklist);

        refresh.setText("refresh");
        refresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshActionPerformed(evt);
            }
        });

        ok.setText("OK");
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 451, Short.MAX_VALUE)
                        .addComponent(refresh)))
                .addGap(23, 23, 23))
            .addGroup(layout.createSequentialGroup()
                .addGap(221, 221, 221)
                .addComponent(ok, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(refresh)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                .addComponent(ok)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void refreshActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        GetMwl_3.main(args);

    }                                       

    private void modalityWorklistMouseClicked(java.awt.event.MouseEvent evt) {                                              
        if(evt.getClickCount()==2){
        int i = modalityWorklist.getSelectedRow();
        TableModel model =modalityWorklist.getModel();  
        id=model.getValueAt(i, 0).toString();
        Name=model.getValueAt(i, 1).toString();
        selectedPatient.main(args,Name,id);
        }
    }                                             

    private void okActionPerformed(java.awt.event.ActionEvent evt) {                                   
     dispose();
    }                                  

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ModalityWorklist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ModalityWorklist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ModalityWorklist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ModalityWorklist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {


                new ModalityWorklist().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTable modalityWorklist;
    private javax.swing.JButton ok;
    private javax.swing.JButton refresh;
    // End of variables declaration                   
}

检索工作清单的类:GetMwl_3.java

public class GetMwl_3 {
 private String[] args;
    /**
     * @param args
     */
    public static void main(String[] args/*,String aet, String host, Integer port*/) {
        new GetMwl_3(/*aet,host,port*/);
    }

    private static final int[] RETURN_KEYS = {
        Tag.AccessionNumber,
        Tag.ReferringPhysicianName,
        Tag.PatientName,
        Tag.PatientID,
        Tag.PatientBirthDate,
        Tag.PatientSex,
        Tag.PatientWeight,
        Tag.MedicalAlerts,
        Tag.Allergies,
        Tag.PregnancyStatus,
        Tag.StudyInstanceUID,
        Tag.RequestingPhysician,
        Tag.RequestingService,
        Tag.RequestedProcedureDescription,
        Tag.AdmissionID,
        Tag.SpecialNeeds,
        Tag.CurrentPatientLocation,
        Tag.PatientState,
        Tag.RequestedProcedureID,
        Tag.RequestedProcedurePriority,
        Tag.PatientTransportArrangements,
        Tag.PlacerOrderNumberImagingServiceRequest,
        Tag.FillerOrderNumberImagingServiceRequest,
        Tag.ConfidentialityConstraintOnPatientDataDescription,
    };

    private static final int[] SPS_RETURN_KEYS = {
        Tag.Modality,
        Tag.RequestedContrastAgent,
        Tag.ScheduledStationAETitle,
        Tag.ScheduledProcedureStepStartDate,
        Tag.ScheduledProcedureStepStartTime,
        Tag.ScheduledPerformingPhysicianName,
        Tag.ScheduledProcedureStepDescription,
        Tag.ScheduledProcedureStepID,
        Tag.ScheduledStationName,
        Tag.ScheduledProcedureStepLocation,
        Tag.PreMedication,
        Tag.ScheduledProcedureStepStatus
    };

    private static final String[] LE_TS = {
        UID.ExplicitVRLittleEndian, 
        UID.ImplicitVRLittleEndian };

    private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };

    private Device device;
    private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
    private final NetworkConnection remoteConn = new NetworkConnection();
     private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
     private final NetworkConnection conn = new NetworkConnection();
     private final DicomObject keys = new BasicDicomObject();
     private final DicomObject spsKeys = new BasicDicomObject();
     private Association assoc;
     private int priority = 0;
     private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок

     private boolean fuzzySemanticPersonNameMatching;
    private Component emptyLabel;

    public GetMwl_3(/*String aet, String host, Integer port*/) {
        String name = "DCMMWL";
        device = new Device(name);
        NewThreadExecutor executor = new NewThreadExecutor(name);
        remoteAE.setInstalled(true);
        remoteAE.setAssociationAcceptor(true);
        remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });

        device.setNetworkApplicationEntity(ae);
        device.setNetworkConnection(conn);
        ae.setNetworkConnection(conn);
        ae.setAssociationInitiator(true);
        ae.setAETitle(name);
        for (int i = 0; i < RETURN_KEYS.length; i++) {
            keys.putNull(RETURN_KEYS[i], null);
        }        
        keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
                new BasicDicomObject());
        keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
        for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
            spsKeys.putNull(SPS_RETURN_KEYS[i], null);
        }
        spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
                new BasicDicomObject());

        /////////
       // remoteAE.setAETitle(aet);
       // remoteConn.setHostname(host);
       // remoteConn.setPort(port);
        remoteAE.setAETitle("DCM4CHEE");
        remoteConn.setHostname("localhost");
        remoteConn.setPort(11112);

       // addSpsMatchingKey(Tag.Modality, "CR");
        //addSpsMatchingKey(Tag.Modality, "CR");
//        addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
//        addSpsMatchingKey(Tag.ScheduledProcedureStepStartTime,"11111");

        setTransferSyntax(LE_TS);

        long t1 = System.currentTimeMillis();
        try {
            assoc = ae.connect(remoteAE, executor);
        } catch (Exception e) {
            System.err.println("ERROR: Failed to establish association:");
            e.printStackTrace(System.err);
            System.exit(2);
        }

        long t2 = System.currentTimeMillis();
        System.out.println("Connected to " + remoteAE + " in "
                + ((t2 - t1) / 1000F) + "s");

        try {
            List<DicomObject> result = query();
            long t3 = System.currentTimeMillis();

            System.out.println("Received " + result.size()
                    + " matching entries in " + ((t3 - t2) / 1000F) + "s");



            for(DicomObject dcm : result) {

                worklist.main(args, dcm.getString(Tag.PatientName), dcm.getString(Tag.PatientID));

            }


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            assoc.release(true);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Released connection to " + remoteAE);
    }

    public void setTransferSyntax(String[] ts) {
        TransferCapability tc = new TransferCapability(
                UID.ModalityWorklistInformationModelFIND, ts,
                TransferCapability.SCU);
        if (fuzzySemanticPersonNameMatching)
            tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
        ae.setTransferCapability(new TransferCapability[]{tc});
    }

        public void addSpsMatchingKey(int tag, String value) {
        spsKeys.putString(tag, null, value);
    }

    public List<DicomObject> query() throws IOException, InterruptedException {
        TransferCapability tc = assoc.getTransferCapabilityAsSCU(
                UID.ModalityWorklistInformationModelFIND);
        if (tc == null) {
            throw new NoPresentationContextException(
                    "Modality Worklist not supported by "
                    + remoteAE.getAETitle());
        }
        //System.out.println("Send Query Request:");
        //System.out.println(keys.toString());
        DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
                priority, keys, tc.getTransferSyntax()[0], cancelAfter);
        List<DicomObject> result = new ArrayList<DicomObject>();
        while (rsp.next()) {
            DicomObject cmd = rsp.getCommand();
            if (CommandUtils.isPending(cmd)) {
                DicomObject data = rsp.getDataset();
                result.add(data);
                //System.out.println("\nReceived Query Response #"
                      //  + result.size() + ":");
                //System.out.println(data.toString());
            }
        }
        return result;

    }



}

这是将行添加到jtable:worklist.java

的类
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Dell
 */

public class worklist extends ModalityWorklist{
     public worklist(){

    }
    public static void main(String[] args,String Name,String ID) {

    DefaultTableModel model=(DefaultTableModel)modalityWorklist.getModel();
        model.setColumnIdentifiers(new String[]{"Patient ID","Patient Name"});
       row=new Object[2];
        row[0]=ID;
        row[1]=Name;
        model.addRow(row);


    }

}

2 个答案:

答案 0 :(得分:0)

当您刷新表格时,您正在复制模型中的项目。你能告诉我们你在点击刷新时执行的代码吗?

您的刷新按钮应该在JTable实例上调用fireTableDataChanged()。这应该是全部,如果您更新模型,表格应该正确更新。

答案 1 :(得分:0)

我必须删除行并再次显示

int rowCount = model.getRowCount();
            for (int i = rowCount - 1; i >= 0; i--) {
                model.removeRow(i);
            }