0

I have a java form using JCombobox. There is a "text field", "combobox" and "add" button. When I enter text in the text field, then click Add button, the text in the text field will fill into combobox, but it doesn't sort by a-z.

form screenshot

Below is my code in Add button.

private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if(MyInput.checkText(txtField)){   //MyInput is my own method code to check if the text is entered.
        String st=txtField.getText();
        combox.addItem(st);
        String st1="";
        String st2="";
        int com=st1.compareTo(st2);
        if(com<0){     //I create this string comparison
                       //I need to add the "sort" code here
        }else{

        }
    }else
        JOptionPane.showMessageDialog(this, "Please enter text.");  //When no text is entered, this message appears.
}   

Full source code:

import PlugIn.MyInput;
import javax.swing.JOptionPane;

public class JCombo extends javax.swing.JFrame {

    /**
     * Creates new form JCombo
     */
    public JCombo() {
        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() {

        txt = new javax.swing.JTextField();
        combo = new javax.swing.JComboBox();
        cmdAdd = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtActionPerformed(evt);
            }
        });

        combo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboActionPerformed(evt);
            }
        });

        cmdAdd.setText("Add");
        cmdAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAddActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(88, 88, 88)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txt)
                    .addComponent(combo, 0, 188, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmdAdd)
                .addContainerGap(63, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdAdd))
                .addContainerGap(206, Short.MAX_VALUE))
        );

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

    private void txtActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
    }                                   

    private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
        if(MyInput.checkText(txtField)){   //MyInput is my own method code to check if the text is entered.
            String st=txtField.getText();
            combox.addItem(st);
            String st1="";
            String st2="";
            int com=st1.compareTo(st2);
            if(com<0){     //I create this string comparison
                           //I need to add the "sort" code here
            }else{

            }
        }else
            JOptionPane.showMessageDialog(this, "Please enter text.");  //When no text is entered, this message appears.
    }                                      

    private void comboActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    /**
     * @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(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JCombo.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 JCombo().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton cmdAdd;
    private javax.swing.JComboBox combo;
    private javax.swing.JTextField txt;
    // End of variables declaration                   
}
tarzanbappa
  • 4,930
  • 22
  • 75
  • 117
Steve.K
  • 1
  • 3

2 Answers2

0

Use a SortedComboBoxModel: (How to sort the jComboBox elements in java swing?)

String[] items = { "one", "two", "three" };
SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(items);
JComboBox<String> comboBox = new JComboBox<String>(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");
Community
  • 1
  • 1
wake-0
  • 3,918
  • 5
  • 28
  • 45
0

You have to take care of the order yourself.

  • Use getModel() for getting the current list
  • Figure out where the item should go
  • Use insertItemAt(E item, int index) to place the item int the correct position.
kenny_k
  • 3,831
  • 5
  • 30
  • 41