Search code examples
javaswingjcombobox

JComboBox dynamically updating values


I am trying to update the items of the combo box with the xml nodes, I get the nodes when I run the loop, however somehow I am not able to add them as the items of ComboBox

public class XMLtoExcelGUI extends javax.swing.JFrame {

    public  java.io.File file;

    public XMLtoExcelGUI() {
        initComponents();
    }
    public void  setProgressBarValue(String s){

        jProgressBar1.setString(s);

    }

    @SuppressWarnings("unchecked")

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("XMLToExcel");

        jButton1.setText("Choose File");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Select Measures");

        jProgressBar1.setStringPainted(true);

        jButton3.setText("Get Measure Data");

        jScrollPane1.setViewportView(jTextPane1);

        jComboBox1.setMaximumRowCount(30);
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {}));

        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(137, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(127, 127, 127))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(117, 117, 117))))
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(63, 63, 63)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        final JFileChooser  fileDialog = new JFileChooser();
        int returnVal = fileDialog.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fileDialog.getSelectedFile();

            TestVDT call = new TestVDT(file);
            jTextPane1.setText(file.toString());

            }          

    }                                        

    public static void main(String args[]) {
        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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(XMLtoExcelGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new XMLtoExcelGUI().setVisible(true);
            }
        });
    }


    public javax.swing.JButton jButton1;
    public javax.swing.JButton jButton3;
    public javax.swing.JComboBox jComboBox1;
    public javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel2;
    public javax.swing.JProgressBar jProgressBar1;
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextPane jTextPane1;
    // End of variables declaration                   
}

public class TestVDT {

    public int setNumberOfMeasures = 0;
    public String[]  Measures = new String[30];

    public void setMeasureValues(String S[], int length) {
        Vector comboBoxItems = new Vector();
        for (int i = 1; i < length; i++) {
            comboBoxItems.add(S[i]);
        //    System.out.println(S[i]);
        }
         XMLtoExcelGUI call = new XMLtoExcelGUI();
         DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(comboBoxItems);

        call.jComboBox1.setModel(defaultComboBoxModel);



    }

    public TestVDT(java.io.File FName) {

        try {
            File f = new File(FName.toString());
            FileInputStream fis = new FileInputStream(f);
            byte[] ba = new byte[(int) f.length()];
            fis.read(ba);
            VTDGen vg = new VTDGen();
            vg.setDoc(ba);
            vg.parse(false);
            VTDNav vn = vg.getNav();

            FileOutputStream fout = new FileOutputStream("E:\\Data.xls");

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet worksheet = workbook.createSheet("Data");

            Row row1 = worksheet.createRow(0);
            row1.createCell(0).setCellValue("Measure_id");
            row1.createCell(1).setCellValue("Denominator");
            row1.createCell(2).setCellValue("Numerator");
            row1.createCell(3).setCellValue("exclusion");
            row1.createCell(4).setCellValue("performance criteria");

            //for(int i=0;i<3;i++)
            int rowIndex = 1;
            int j = 1;
            vn.toElement(VTDNav.FIRST_CHILD);
            do {

                if (vn.matchElement("practice_data")) {
                    vn.toElement(VTDNav.FIRST_CHILD);
                }
                if (vn.matchElement("provider_data")) {
                    vn.toElement(VTDNav.FIRST_CHILD);
                }

                if (vn.matchElement("provider_identification")) {
                    vn.toElement(VTDNav.FIRST_CHILD);

                }
                if (vn.matchElement("measure")) {
                    vn.toElement(VTDNav.FIRST_CHILD);
                    do {
                        Row row = worksheet.createRow(rowIndex++);
                        int cellIndex = 0;

                       String temp = vn.toString(vn.getAttrVal("measure_id"));
                        System.out.println(temp);

                        Measures[j] = temp;
                        row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("measure_id")));
                        System.out.print(" -- ");

                        System.out.print(vn.toString(vn.getAttrVal("denominator")));
                        row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("denominator")));

                        System.out.print(" -- ");

                        System.out.print(vn.toString(vn.getAttrVal("numerator")));
                        row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("numerator")));

                        System.out.print(" -- ");

                        System.out.print(vn.toString(vn.getAttrVal("exclusion")));
                        row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("exclusion")));
                        System.out.print(" -- ");

                        System.out.println(vn.toString(vn.getAttrVal("performance_rate")));
                        row.createCell(cellIndex++).setCellValue(vn.toString(vn.getAttrVal("performance_rate")));
                        setNumberOfMeasures++;
                        j++;
                    } while (vn.toElement(VTDNav.NEXT_SIBLING));

                }

            } while (vn.toElement(VTDNav.NEXT_SIBLING));

            System.out.println(setNumberOfMeasures);
            workbook.write(fout);
            fout.flush();

            setMeasureValues(Measures, setNumberOfMeasures);
        } catch (Exception e) {
            System.out.println("exception occurred ==>" + e);
        }
    }

    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {

    }

}

By default the values of Jcombo box is blank and when the function setMeasureValues() is called it should update the items of the combo box but is not


Solution

  • Your XMLtoExcelGUI variable, call, is local to the setMeasureValues(...) method. Any changes made to the object that it refers to will only be reflected in this local object and not on any other object of similar type. A guess, but perhaps you want to pass into the method a valid reference to the displayed XMLtoExcelGUI object. Otherwise if this doesn't help, you're going to likely have to improve your question by telling and showing more.


    Yes, I was right -- you're setting the model of a combo box in a completely different non-displayed XMLtoExcelGUI instance. Changing the state of one instance will not and should not have an effect on another. The solution is to change the state of the correct displayed instance.

    Change this:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
        final JFileChooser  fileDialog = new JFileChooser();
        int returnVal = fileDialog.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fileDialog.getSelectedFile();
    
            TestVDT call = new TestVDT(file);  
            jTextPane1.setText(file.toString());
    
            }          
    
    }
    

    to something like this:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
        final JFileChooser  fileDialog = new JFileChooser();
        int returnVal = fileDialog.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fileDialog.getSelectedFile();
    
            TestVDT call = new TestVDT(this, file);  // ****** changed
            jTextPane1.setText(file.toString());
    
            }          
    

    And then this

    public class TestVDT {
    
        public int setNumberOfMeasures = 0;
        public String[]  Measures = new String[30];
    
        public TestVDT(java.io.File FName) {
    

    to something like:

    public class TestVDT {
    
        public int setNumberOfMeasures = 0;
        public String[]  Measures = new String[30];
        private XMLtoExcelGUI gui;
    
        public TestVDT(XMLtoExcelGUI gui, java.io.File FName) {
            this.gui = gui;
    

    This way your method can use a reference to the actual displayed GUI:

    public void setMeasureValues(String S[], int length) {
        Vector comboBoxItems = new Vector();
        for (int i = 1; i < length; i++) {
            comboBoxItems.add(S[i]);
        }
    
        //  XMLtoExcelGUI call = new XMLtoExcelGUI(); // **** no!
         DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(comboBoxItems);
    
        // give XMLtoExcelGUI a public method that sets 
        // its own combo box's model
        gui.setComboModel(defaultComboBoxModel);
    
    
    
    }