JComboBox listeners

I'm trying to use a JComboBox, but I'm having trouble adding a listener. Here is the relevent code:
JComboBox categoryCombo;
JComboBox colorCombo;
StyleListener styleListener;     // Action listener for combo boxes
categoryCombo = new JComboBox(categories);
categoryCombo.addActionListener(styleListener);
colorCombo = new JComboBox(colors);
colorCombo.addActionListener(styleListener);
public class StyleListener implements ActionListener
     public void actionPerformed(ActionEvent e)
          String category = (String)categoryCombo.getSelectedItem();
          String color = (String)colorCombo.getSelectedItem();
Nothing seems to happen when I change the selection in the combo box.

Hi Mark,
According to the code you have posted, your "styleListener" variable is null. Nowhere, in the code you posted, did I see an instance of "StyleListener" being created. Therefore, I suggest you replace this line:
StyleListener styleListener;with this line:
StyleListener styleListener = new StyleListener();Hope this helps.
Good Luck,
Avi.

Similar Messages

  • Where oh where is my FOCUS (arghhh)

    O.K., I'm goin nutz here. I am using SDK 1.2.2, and have a JFrame that is composed of four main panels. Some panels are composed of sub-panels. All panels have JComponents (almost all JTextFields and Labels).
    When the window is displayed, none of the fields has a focus. So... at the end of my init, I requestFocus() on the first Field.... nothing.
    I did the following:
    JComponent.isRequestFocusEnabled() == true
    JComponent.isFocusTraversable() = true
    JComponent.requestFocus()
    JComponent.hasFocus = false;
    Am I nutz?
    If I click with the mouse on the first field it works.
    Sorry for not posting code, it is quite lengthy, thought maybe someone had seen this before.
    Thanx
    sfav

    I hope this is not too much
    This creates the invoice instance
    else if(source == m_New_Invoice)
    if(Rm.selectedCompany == null)
    JOptionPane.showMessageDialog(this.getContentPane(),
    "No Company Selected!",
    "Operational Warning",
    JOptionPane.WARNING_MESSAGE);
              return true;
    RmInvoice rm_New_Invoice = new RmInvoice();
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = rm_New_Invoice.getSize();
    if (frameSize.height > screenSize.height)
    frameSize.height = screenSize.height;
    if (frameSize.width > screenSize.width)
    frameSize.width = screenSize.width;
    rm_New_Invoice.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    rm_New_Invoice.setVisible(true);
    Here is the RmIncoice class. At the bottom of the invoice_Init is where I invNumFld.requestFocus() which does not work.
    public class RmInvoice extends JFrame implements ActionListener,
                                       WindowListener,
                                       KeyListener,
                                       ListSelectionListener,
                                       TableModelListener
    JFrame dialogFrame = new JFrame("Edit Product Description");
    VendorObj vendors;
    TermsObj terms;
    InvoiceObj invoices;
    CategoryObj categories;
    ProductObj products;
    static final int MAX_INV_NUMS = 10;
    static final int MAX_AMOUNT_NUMS = 8;
    // InvoiceTable column offsets.
    static final int INVOICE_COL = 0;
    static final int DATE_COL = 1;
    static final int VENDOR_COL = 2;
    static final int CHECK_COL = 3;
    static final int AMOUNT_COL = 4;
    // Line item column offsets.
    static final int LINEINVOICE_COL = 0;
    static final int CATEGORY_COL =1;
    static final int DESCRIPTION_COL = 2;
    static final int QUANTITY_COL = 3;
    static final int UNIT_COL = 4;
    static final int TOTALCOST_COL = 5;
    static final int UNITCOST_COL = 6;
    static final int PRODCODE_COL = 7;
    StringBuffer unapplied = new StringBuffer();
    boolean escaped = false;
    Locale currentLocale = new Locale("en", "US");
    Date systemDate = new Date();
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss", currentLocale);
    SimpleDateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd", currentLocale);
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy", currentLocale);
    String dateTimeString;
    String dateString;
    Font boldFont = new Font("serif", Font.PLAIN, 12);
    Font largeFont = new Font("serif", Font.BOLD, 20);
    Font buttonFont = new Font("serif", Font.BOLD, 18);
    JPanel invoicePanel = new JPanel(); // Hold invoiceFieldPanel and buttonPanel.
    JPanel invoiceFieldPanel = new JPanel(); // Hold invoice fields.
    JPanel ip1 = new JPanel();
    JPanel ip2 = new JPanel();
    JPanel ip3 = new JPanel();
    JPanel ip4 = new JPanel();
    JPanel detailPanel = new JPanel();
    JPanel dp1 = new JPanel();
    JPanel dp2 = new JPanel();
    JPanel dp3 = new JPanel();
    JPanel buttonPanel = new JPanel();
    InvoiceTableModel invoiceModel = new InvoiceTableModel();
    JTable invoiceTable = new JTable(invoiceModel);
    LineTableModel lineModel = new LineTableModel();
    JTable lineTable = new JTable(lineModel);
    JScrollPane invoiceScroller = new JScrollPane(invoiceTable);
    JScrollPane lineScroller = new JScrollPane(lineTable);
    // This vector will hold product descriptions.
    Vector prodVector = new Vector();
    Vector codeVector = new Vector();
    Vector costVector = new Vector();
    Vector offsetVector = new Vector(); // Actual position in the database.
    // Vector for units of measure.
    Vector uomVector = new Vector();
    // The following vectors will hold invoice data.
    // All data is String data.
    Vector invoiceVector = new Vector();
    Vector dateVector = new Vector();
    Vector checkVector = new Vector();
    Vector amountVector = new Vector();
    Vector termsVector = new Vector();
    Vector taxVector = new Vector();
    Vector vendorVector = new Vector();
    ProductDocument productDoc = new ProductDocument();
    // Labels and fields for the invoiceFieldPanel.
    JLabel dateLbl = new JLabel("Date:");
    JLabel vendorLbl = new JLabel("Vendor:");
    JLabel invNumLbl = new JLabel("Invoice#:");
    JLabel venNameLbl = new JLabel("Vendor Name:");
    JLabel taxLbl = new JLabel("Sales Tax:");
    JLabel termsLbl = new JLabel("Terms:");
    JLabel amountLbl = new JLabel("Amount:");
    JLabel checkLbl = new JLabel("Check#:");
    JLabel unappliedLbl = new JLabel("Unapplied:");
    JTextField dateFld = new JTextField(7);
    JComboBox vendorFld = new JComboBox();
    // Normally, a JTextField has a default document
    // associated with the field.
    // These custom documents that are associated with
    // the JTextField, limit the amount of data in the
    // field. Not all fields require a custom document.
    // InvNumDocument invoiceDoc = new InvNumDocument(MAX_INV_NUMS);
    // JTextField invNumFld = new JTextField(invoiceDoc, "", 10);
    JTextField invNumFld = new JTextField(10);
    JTextField venNameFld = new JTextField(30);
    JTextField taxFld = new JTextField(8);
    JComboBox termsFld = new JComboBox();
    CurrencyDocument amountDoc = new CurrencyDocument(MAX_AMOUNT_NUMS);
    JTextField amountFld = new JTextField(amountDoc, "", 8);
    JTextField unappliedFld = new JTextField(8);
    JTextField checkFld = new JTextField(8);
    // Labels and Fields for the detailPanel.
    JLabel catLbl = new JLabel("Catagory:");
    JLabel prodLbl = new JLabel("Prod Code:");
    JLabel descLbl = new JLabel("Description:");
    JLabel qtyLbl = new JLabel("Qty Received:");
    JLabel unitLbl = new JLabel("Unit:");
    JLabel lastCostLbl = new JLabel("Last Cost:");
    JLabel totalCostLbl = new JLabel("Total Cost:");
    JComboBox catFld = new JComboBox();
    JComboBox prodFld = new JComboBox();
    JTextField descFld = new JTextField(40);
    JTextField qtyFld = new JTextField(5);
    JTextField unitFld = new JTextField(5);
    JTextField lastCostFld = new JTextField(7);
    JTextField totalCostFld = new JTextField(7);
    // Fields for the productDialog.
    JTextField prodcodeField = new JTextField();
    JTextField descriptionField = new JTextField();
    JButton addBtn = new JButton("Add Invoice");
    JButton saveBtn = new JButton("Save Invoices");
    JButton clearBtn = new JButton("Clear All");
    JButton updateBtn = new JButton("Update Description");
    JButton deleteBtn = new JButton("Delete");
    // These two button are for the productDialog.
    JButton updateDescBtn = new JButton("Update");
    JButton cancelBtn = new JButton("Cancel");
    public RmInvoice()
    try
    invoice_Init();
    catch (Exception e)
    e.printStackTrace();
    vendors = new VendorObj(this);
    terms = new TermsObj(this);
    invoices = new InvoiceObj(this);
    categories = new CategoryObj(this);
    products = new ProductObj(this);
    // Get the ComboBox data.
    loadVendors();
    loadTerms();
    loadCategories();
    // loadProducts();
    private void invoice_Init()
    // Get the time and date/time stamps.
    systemDate = new Date();
    // Format the date with yyyy/mm/dd hh:mm:ss.
    // Use the SimpleDateFormat Class.
    dateTimeString = dateTimeFormat.format(systemDate);
    dateString = dateFormat.format(systemDate);
    // Format to U.S. currency.
    NumberFormat currencyFormatter;
    currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
    // See if the database object created earlier,
    // was able to establish a connection, and set
    // the JFrame title accordingly.
    if(Rm.is_Connected)
    this.setTitle("Invoice Entry: " + Rm.selectedCompany);
    else
    // Buffer data to a text file here, to be read back
    // and appended to the database when a connection
    // is re-established.
    this.setTitle("Invoice Entry: BUFFERED MODE");
    // Set the screen size.
    this.setSize(new Dimension(850, 700));
    // Set scroll window size.
    invoiceTable.setPreferredScrollableViewportSize(new Dimension(150, 100));
    lineTable.setPreferredScrollableViewportSize(new Dimension(150, 100));
    // Set some colors.
    invoicePanel.setBackground(Color.cyan);
    invoiceFieldPanel.setBackground(Color.cyan);
    detailPanel.setBackground(Color.cyan);
    buttonPanel.setBackground(Color.cyan);
    invoiceTable.setSelectionBackground(Color.yellow);
    lineTable.setSelectionBackground(Color.yellow);
    ip1.setBackground(Color.cyan);
    ip2.setBackground(Color.cyan);
    ip3.setBackground(Color.cyan);
    ip4.setBackground(Color.cyan);
    dp1.setBackground(Color.cyan);
    dp2.setBackground(Color.cyan);
    dp3.setBackground(Color.cyan);
    // set the current locale for formatting numbers.
    currentLocale = new Locale("en", "US");
    // Set the Layout Managers.
    this.getContentPane().setLayout(new GridLayout(4,0));
    invoicePanel.setLayout(new BorderLayout());
    detailPanel.setLayout(new GridLayout(3,0));
    invoiceFieldPanel.setLayout(new GridLayout(4,0));
    buttonPanel.setLayout(new GridLayout(6,1));
    ip1.setLayout(new FlowLayout());
    ip2.setLayout(new FlowLayout());
    ip3.setLayout(new FlowLayout());
    ip4.setLayout(new FlowLayout());
    dp1.setLayout(new FlowLayout());
    dp2.setLayout(new FlowLayout());
    // Set the panel borders.
    invoiceScroller.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder(
    "Invoices"),
    BorderFactory.createEmptyBorder(5,5,5,5)));
    invoiceFieldPanel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder(
    "Invoice Detail"),
    BorderFactory.createEmptyBorder(0,0,0,0)));
    detailPanel.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder(
    "Item Detail"),
    BorderFactory.createEmptyBorder(0,0,0,0)));
    lineScroller.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createTitledBorder(
    "Line Items"),
    BorderFactory.createEmptyBorder(5,5,5,5)));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 50, 10,50));
    // Create a Line Border for the invoice number.
    invNumFld.setBorder(BorderFactory.createLineBorder(Color.red));
    unappliedFld.setBorder(BorderFactory.createLineBorder(Color.black));
    // Set which fields are editable.
    unappliedFld.setEditable(false);
    unitFld.setEditable(false);
    descFld.setEditable(false);
    lastCostFld.setEditable(false);
    prodcodeField.setEditable(false);
    venNameFld.setEditable(false);
    vendorFld.setEditable(true); // JComboBox.
    catFld.setEditable(true); // JComboBox.
    prodFld.setEditable(true); // JComboBox.
         // This is so only one row may be selected in the JTables.
         invoiceTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         lineTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         ListSelectionModel invoiceSM = invoiceTable.getSelectionModel();
         ListSelectionModel lineSM = lineTable.getSelectionModel();
         // Add ListSelectionListeners.
         invoiceSM.addListSelectionListener(this);
         lineSM.addListSelectionListener(this);
         // Add a listener for the table data changing.     
         lineModel.addTableModelListener(this);
    // Set the selection mode for the JTables.
    invoiceTable.setCellSelectionEnabled(true);
    // lineTable.setCellSelectionEnabled(true);
    lineTable.setRowSelectionAllowed(true);
    // Set button colors.
    addBtn.setBackground(Color.green);
    saveBtn.setBackground(Color.green);
    clearBtn.setBackground(Color.pink);
    updateBtn.setBackground(Color.yellow);
    deleteBtn.setBackground(Color.pink);
    // Set button fonts.
    addBtn.setFont(buttonFont);
    saveBtn.setFont(buttonFont);
    clearBtn.setFont(buttonFont);
    updateBtn.setFont(buttonFont);
    updateDescBtn.setFont(buttonFont);
    cancelBtn.setFont(boldFont);
    deleteBtn.setFont(buttonFont);
    // Set the alignment for fields.
    venNameFld.setAlignmentX(Component.LEFT_ALIGNMENT);
    descFld.setAlignmentX(Component.LEFT_ALIGNMENT);
    // Now the JComboBoxes.
    vendorFld.setAlignmentX(Component.LEFT_ALIGNMENT);
    catFld.setAlignmentX(Component.LEFT_ALIGNMENT);
    prodFld.setAlignmentX(Component.LEFT_ALIGNMENT);
    // Set the date.
    dateFld.setText(dateString);
    // Add the Window Listener.
    this.addWindowListener(this);
    // Add field JComboBox listeners.
    vendorFld.addActionListener(this);
    dateFld.addActionListener(this);
    invNumFld.addActionListener(this);
    taxFld.addActionListener(this);
    amountFld.addActionListener(this);
    checkFld.addActionListener(this);
    catFld.addActionListener(this);
    prodFld.addActionListener(this);
    qtyFld.addActionListener(this);
    totalCostFld.addActionListener(this);
    addBtn.addActionListener(this);
    saveBtn.addActionListener(this);
    clearBtn.addActionListener(this);
    deleteBtn.addActionListener(this);
    updateBtn.addActionListener(this);
    updateDescBtn.addActionListener(this);
    cancelBtn.addActionListener(this);
    this.addKeyListener(this);
    // Preset unapplied to $0.00.
    String str = currencyFormatter.format(0.00);
    unappliedFld.setText(str);
    unapplied.append("0.00");
    // Add labels and fields.
    buildInvoicePanel();
    buildDetailPanel();
    buildButtonPanel();
    // Now compose our window.
    this.getContentPane().add(invoiceScroller);
    invoiceFieldPanel.add(ip1);
    invoiceFieldPanel.add(ip2);
    invoiceFieldPanel.add(ip3);
    invoiceFieldPanel.add(ip4);
    invoicePanel.add(invoiceFieldPanel, BorderLayout.WEST);
    invoicePanel.add(buttonPanel, BorderLayout.CENTER);
    detailPanel.add(dp1);
    detailPanel.add(dp2);
    detailPanel.add(dp3);
    this.getContentPane().add(invoicePanel);
    this.getContentPane().add(detailPanel);
    this.getContentPane().add(lineScroller);
    invNumFld.requestFocus();

  • How to add key listeners to jcombobox

    i have been trying to add an key listener to jcombobox so that i can identify when an enter key is pressed.

    You should use an ActionListener to handle the enter key. See the section from the Swing toturial on "Using Combo Boxes":
    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#listeners

  • JComboBox event notification when select first entry in pop-up menu JDK 6

    I recently began testing a Java GUI, I originally developed with JDK 1.5.0_11, with JDK 1.6.0_3. I have used the JComboBox in several applications developed using JDK 1.3.x and 1.4.x over the years. In every one of these earlier JDKs the JComboBox widgets all behaved the same. When you select the JComboBox widget, the pop-up menu appears and you can select any of the items from the menu list. Having made the selection with either a mouse click or a key press, an event notification is sent. Typically, an ActionEvent as well as either a mouse click event or a keypressed event may be sent. When testing with 1.6.0_x versions of the JDK and JRE, I can't account for any event notification being sent when selecting the first item at the top of the pop-up menu as the initial selection. If I select some other item on the list and then the first item, it works as it is supposed to work, but only after selecting another item first.
    I've placed the JComboBox in a JDialog and a JPanel. There are NO AWT widgets in any containers of the application. The same behavior seems to exist regardless of what other containing Swing component I place the JComboBox in. I'm running these applications on Windows XP, service pack 2. The system is an AMD 64 bit dual processor with 4Gb of RAM. The essential code follows:
    private JComboBox getJcboAlias()
        /* Note here that I am using a defaultComboModel as I have always done */
       jcboAliases = new JComboBox(urls);
       *jcboAliases.setEditable(false);*                               // Note here that the JComboBox is NOT editable
       jcboAliases.addActionListener(new ActionListener()   // ActionListener only receives a notification if the second or
       {                                                                            // another item in the pop-menu list is selected...but never the
          public void actionPerformed(ActionEvent ae)           // first item in the list
             String s = (String) jcboAliases.getSelectedItem();
             for (int i = 0; i < connections.size(); i++)
                conAlias = (String[]) connections.get(i);
                if (s.equals(conAlias))
    isSelected = true;
    break;
    jlblName.setVisible(true);
    jlblAlias.setVisible(true);
    jlblUID.setVisible(true);
    jlblPWD.setVisible(true);
    jtxtName.setText(conAlias[0]);
    jtxtName.setVisible(true);
    jtxtAddress.setText(conAlias[1]);
    jtxtAddress.setVisible(true);
    jtxtUID.setText(conAlias[2]);
    jtxtUID.setVisible(true);
    jtxtPWD.setVisible(true);
    jtxtPWD.setText("");
    jtxtPWD.requestFocus();
    return jcboAliases;
    }    I'm using a non-editable JComboBox because there is a pop-up menu with this and not with the JList widget.  JComboBox behaves more like the JList MicroSoft counterpart.  Another code snippet follows in which the JComboBox is editable.  The same errant behavior occurs when selecting the first item from the pop-up menu: private JComboBox getJcboPCMember()
    jcboPCMember = new JComboBox(PCViewerCustom.getCurrentMembers());
    jcboPCMember.setBounds(250, 103, 180, 20);
    jcboPCMember.setToolTipText("PATHCHECK(ER) member name - Example: CKPPTHCK");
    jcboPCMember.setSelectedIndex(Integer.valueOf(PCViewerCustom.getCurrentHost(3)));
    jcboPCMember.setEditable(true); // Note here that this JComboBox IS editable
    jcboPCMember.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    if (ae.getActionCommand().equals("comboBoxEdited"))
    boolean copy = false;
    for (int i = 0; i < jcboPCMember.getItemCount(); i++)
    if (jcboPCMember.getSelectedItem().equals(jcboPCMember.getItemAt(i)))
    copy = true;
    break;
    if (!copy)
    if (jcboPCMember.getItemCount() > 0)
    if (jcboPCMember.getItemAt(0).equals("No Entries"))
    jcboPCMember.removeItem("");
    jcboPCMember.removeItem("No Entries");
    jcboPCMember.insertItemAt((String) jcboPCMember.getSelectedItem(), 0);
    else
    jcboPCMember.removeItem("");
    jcboPCMember.addItem((String) jcboPCMember.getSelectedItem());
    enableJbtnOK();
    else
    if (jcboPCMember.getSelectedIndex() >= 0)
    PCViewerCustom.setCurrentHost(3, Integer.toString(jcboPCMember.getSelectedIndex()));
    enableJbtnOK();
    else
    JOptionPane.showMessageDialog(null, "Name not selected", "Error", JOptionPane.ERROR_MESSAGE);
    return jcboPCMember;
         I am able to add a new entry to the JComboBox, however, I am still unable to select the first item from the pop-up menu and fire any kind of notification event.  I have not seen this behavior before in any earlier versions of the JDK and it's playing havoc with my ability to deploy the application into a JDK or JRE V6 environment, without adding a bunch of additional code to pre-select the first item on the list, which pretty much defeats the purpose of the JComboBox.  I'll be the first to admit I've done something wrong, but i've built a number of test scenarios now on two systems runing Win XP SP2 and I get the same errant behavior.  I've also added in event listeners for a MouseListerner, a KeyListener and an ItemListener.  Still no event notification on this first item in the list.  Again, however, if I select one of the other items from the pop-up menu list and then select the first item, all is well.  Imagine selling that method of operation to a user....  It occurs to me that this must be a bug in the V6 JComboBox.  I wanted to post this here first, however, in order to determine if this is, in fact, a bug - in other words, am I the only one seeing this, or is this a more widespread issue?  Any assistance in making this determination is greatly appreciated.
    David Baker
    Edited by: Galstuk on Nov 27, 2007 12:21 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    here is the other file as well:
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Attachments:
    VI2.vi ‏5 KB

  • NullPoniter Exception while Adding in JComboBox

    Hi All, My application is a Applet - EJB based and Server is sending Serialized Objects to add in to the JCOMBOBOX object.
    I have the following Exception coming up after a few iteratons ( 200 ) of opening up the screen and closing it which I am doing at a normal speed.
    Code......
    List lstSeverities = (List)e.getReturnValue();
    if(lstSeverities!=null){
    Iterator oIterator = lstSeverities.iterator();
    while (oIterator.hasNext())
    CaseSeverity oCaseSeverity = (CaseSeverity)oIterator.next();
    if(oCaseSeverity != null && oCaseSeverity.getSeverityName() != null)
    m_cbxSeverity.addItem(oCaseSeverity); /* This Statement is throwing exception.*/}
    StackTrace.......
    java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicComboBoxUI$ListDataHandler.contentsChanged(Unknown Source)
    at javax.swing.plaf.basic.BasicComboBoxUI$ListDataHandler.intervalAdded(Unknown Source)
    at javax.swing.AbstractListModel.fireIntervalAdded(Unknown Source)
    at javax.swing.DefaultComboBoxModel.addElement(Unknown Source)
    at javax.swing.JComboBox.addItem(Unknown Source)
    at sync.client.contactmgmt.activity.CaseGeneral.handleResponse(CaseGeneral.java:1382)
    at sync.client.gateway.ServerProxy.handleResponse(ServerProxy.java:96)
    at sync.client.gateway.UniversalGateway$1.run(UniversalGateway.java:142)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Note - 1. This Exception is coming only once in some 200 repetitions.
    2. The issue is with only this ComboBox , I have another 10 ComboBox.
    3. This ComboBox is populated with Serialized objects.
    Please help to identify the cause and to resolve this.
    Thanks.

    I have looked in Sun sources:
    Regarding the stack trace u post:
    from AbstractListModel source
    protected void fireIntervalAdded(Object source, int index0, int index1)
         Object[] listeners = listenerList.getListenerList();
         ListDataEvent e = null;
         for (int i = listeners.length - 2; i >= 0; i -= 2) {
         if (listeners[i] == ListDataListener.class) {
              if (e == null) {
              e = new ListDataEvent(source, ListDataEvent.INTERVAL_ADDED, index0, index1);
              ((ListDataListener)listeners[i+1]).intervalAdded(e);
    it fires an event that is hanled in nested class ListDataHanlder of
    BasicComboBoxIUI:
    public void intervalAdded( ListDataEvent e ) {
         isDisplaySizeDirty = true;
         contentsChanged( e );
    it invokes the contentChanged mothod of the same nested class
    public void contentsChanged( ListDataEvent e ) {
         if ( !(e.getIndex0() == -1 && e.getIndex1() == -1) ) {
              isMinimumSizeDirty = true;
              comboBox.revalidate();
    Now:
    The 2 objects that might be null are
    1) e: the event
    Improbably, is the event dispatched from the JComboxBox add method
    2) the comboBox Object
    Most probably.
    I imagine that, when the event is disptached, the JComboBox is valid
    (not equals to null)
    But when the events reaches contentChange method, the comboBox
    pointer in BasicComboBoxUI is just null.
    This pointer is setted by installUI method and is forced to null
    in uninstallUI method.
    So, it semmes to be not a Swing bug, but, most probably,
    somothing in your code cause the call of unistallUI method or,
    simply, destroys the JComboBox after that the event is shipped.
    Take a look.

  • A clear workaround for JComboBox bug 4199622 please.

    Hi,
    I'm writing a project management software where you assign a project leader to a project via combo box and in the same step this user must be added to the team member list. Now look what happened! When I open the combo and navigate via arrow keys all project leaders are added just because they are highlighted. This is very funny but I need only 1 project leader, that which is finally selected by the user. So I've spent several hours looking for a solution and find this amazing bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4199622. So regarding JComboBox since 1998 you dont have a way to identify a final selection, is this true (I'm using java 1.6 already)? Anyway, I applied
    projectLeadC.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
    and now finally I can make a difference by receiving a new action "comboBoxEdited"
    if (event.getActionCommand().equals("comboBoxEdited") && !item.equals(oldItem)) {
    pushMember(item);
    So now keyboar navigation is ok. But now how can I identify a selection commited by mouse click????? All I get is "comboBoxChanged" but both keyboard and mouse based selections issue this command, so I never know if an item was selected by mouse. I'd need "comboBoxEdited" issued by click or even better something like "CommitedByMouseClick". So can someone help me find a solution, preferably by subclassing JComboBox and fixing the action commands (I dont want to use itemSelectionChange listeners or other listeners just because of this, I dont care which item is selected before commiting, I just care for the action)? Note also, that if my combo is in a table this issue is not that severe, because I can call stopCellEditing on the table which issues a "comboBoxEdited" command.
    Thanks for the help,
    Marton Bokor

    You could use a popup listener to identify the final selection. The popup listener will store the previous selection, and everytime the popup is made invisible you can check whether the new selection is different from the previous selection. If it is, then you notify whoever you need to notify. Example program,
    import javax.swing.*;
    import javax.swing.event.PopupMenuListener;
    import javax.swing.event.PopupMenuEvent;
    public class Tester {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Tester();
        JComboBox theBox;
        public Tester() {
            JFrame frame = new JFrame();
            theBox = new JComboBox(new String[]{"One","Two","Three"});
            theBox.addPopupMenuListener(new FinalSelectionListener());
            frame.setContentPane(theBox);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        private class FinalSelectionListener implements PopupMenuListener {
            private Object oldSelectedItem;
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                Object newSelectedItem = theBox.getSelectedItem();
                if(newSelectedItem != oldSelectedItem) {
                    oldSelectedItem = newSelectedItem;
                    selectionChanged(newSelectedItem);
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
            public void popupMenuCanceled(PopupMenuEvent e) {}
        private void selectionChanged(Object changedTo) {
            System.out.println("The selection was changed to: " + changedTo);
    }This way new selections can be made only when the combo box popup is closed. Hence it will still work with the mouse, and it won't have the action event problem mentioned in the bug.

  • Tricky error on JComboBoxes

    Hi!
    I�m working on a GUI and
    I have two JComboBoxes, say c1 an c2
    My class is using anotherClass that is creating
    the JcomboBoxes like this:
    public myClass
    JCombBox c1, c2 ;
    public myClass()
      anotherClass a  = new anotherClass() ;
      c1 = a.c1 ;
      c2  =a.c1 ;
    //addItemListener on both c1 c2
    public void itemStateChanged
                  if(y.getSource() == c1 && y.getStateChange() == ItemEvent.SELECTED) 
                  //something happens
              if(y.getSource() == c2 && y.getStateChange() == ItemEvent.SELECTED) 
              //something else happens
    public anotherClass
          public JComboBox c1
      public antotherClass()
    ///initiating c1
    The problem is that when the c1 menu is activade by clicking
    on it:  the program enters both the c1-if in itemStateChange
    and the c2.
    c1, c2 are refering to the same object but the item-if
    should not react if not the correct referens is activated.
    This works in an almost identical application I have
    Does anyone ever seen anything like this?
    It�s not logical? Or did I oversee something?
    KR//jF

    Hi!
    I�m working on a GUI and
    I have two JComboBoxes, say c1 an c2
    My class is using anotherClass that is creating
    the JcomboBoxes like this:
    public myClass
    JCombBox c1, c2 ;
    public myClass()
    anotherClass a  = new anotherClass() ;
    c1 = a.c1 ;
    c2  =a.c1 ;
    So both c1 and c2 point to the same Combo box i.e. a.c1! Are you sure you wanted this because it would explain your porblem.
    //addItemListener on both c1 c2Why not use separate listeners fo each combo box?
    public void itemStateChanged
    if(y.getSource() == c1 &&
    rce() == c1 && y.getStateChange() ==
    ItemEvent.SELECTED)
    //something happens
    if(y.getSource() == c2 &&
    ) == c2 && y.getStateChange() == ItemEvent.SELECTED)
    //something else happens
    public anotherClass
    public JComboBox c1
    public antotherClass()
    ///initiating c1
    The problem is that when the c1 menu is activade by
    clicking
    on it: the program enters both the c1-if in
    itemStateChange
    and the c2.
    c1, c2 are refering to the same object but the
    item-if
    should not react if not the correct referens is
    activated.
    This works in an almost identical application I have
    Does anyone ever seen anything like this?
    It�s not logical? Or did I oversee something?
    KR//jF

  • JComboBox event confusion: not enough generated? :-(

    Hi,
    I am slightly confused about the events generated by the combobox.
    I have a combobox and and actionlistener registered on it. If I programmatically use setSelectedIndex on the combobox, and event is generated and the actionlistener is triggered. If I do a setSelectedIndex on the same combobox within the code of the action listener, no event is generated, though the index does get updated. Though I am happy it doesn't generate that event, I don't understand why it doesn't. Anyone?
    Rene'

    Instead of using ActionListener you should use ItemListener for combo box. This is an example
    comboBox.addItemListener(new java.awt.event.ItemListener() {
         public void itemStateChanged(ItemEvent e) {
         try {
         JComboBox box = (JComboBox) e.getSource();
         System.out.println(box.getSelectedItem());
         } catch (ArrayIndexOutOfBoundsException exp) {}
    });Note: Item Listener only listens when you change something in Combo Box. If you click on a combo box, and selects the same value, item listeners doesn't call.
    Hope this helps.

  • Customized JComboBox Editor for JTable

    Hi,
    I am new to swing development and have gotten my self stuck on an issue. Basically I have a JTable that is dynamically populated from the database, in which one of the columns has a customized JComboBox Renderer and Editor. The default values load up fine when the page loads up but when I selected a new value in the combo box and select a new row in the JTable, the combo box defaults back to the original value. How can I make sure that the new selection is maintain.
    Thanks, Anthony
    Here are my Driver, Renderer and Editor:
    excerpts from the Driver
    contract.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    keys = contractSelectedEvent.getKeys();
    String sql = contractSelectedEvent.getSchdSql(keys);
    table = contractSelectedEvent.getStatusTable(sql);
    table.setDefaultRenderer(CashFlow.class, new CashFlowRenderer());
    table.setDefaultEditor(CashFlow.class, new CashFlowEditor());
    public class CashFlowRenderer extends JComboBox implements TableCellRenderer {
    protected QueryComboBoxModel comboModel;
    /** Creates a new instance of CashFlowRenderer */
    public CashFlowRenderer() {
    super();
    comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where
    Ref_Typ_ID = 910 order by Ref_ID ");
    super.setModel(comboModel);
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column) {
    if(value == null) {
    return this;
    if(value instanceof CashFlow) {
    //set the cashflow equal to the value
    CashFlow cashFlow = new CashFlow(((CashFlow) value).getCashFlow());
    setSelectedItem(cashFlow);
    else {
    //default the cashflow
    CashFlow cashFlow = new CashFlow();
    setSelectedItem(cashFlow.getCashFlow());
    return this;
    public boolean isCellEditable() {
    return true;
    public class CashFlowEditor extends JComboBox implements TableCellEditor {
    protected transient Vector listeners;
    protected transient String originalValue;
    protected QueryComboBoxModel comboModel;
    /** Creates new CashFlowEditor */
    public CashFlowEditor() {
    super();
    comboModel = new QueryComboBoxModel("Select Ref_ID, Ref_Desc From Ref Where Ref_Typ_ID = 910 order by Ref_ID ");
    super.setModel(comboModel);
    listeners = new Vector();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    if(value == null) {
    return this;
    if (value instanceof CashFlow) {
    setSelectedItem(((CashFlow)value).getCashFlow());
    else {
    CashFlow cashFlow = new CashFlow();
    setSelectedItem(cashFlow.getCashFlow());
    table.setRowSelectionInterval(row, row);
    table.setColumnSelectionInterval(column, column);
    originalValue = (String) getSelectedItem();
    return this;
    public void cancelCellEditing() {
    fireEditingCanceled();
    public Object getCellEditorValue() {
    return (String)getSelectedItem();
    public boolean isCellEditable(EventObject eo) {
    return true;
    public boolean shouldSelectCell(EventObject eo) {
    return true;
    public boolean stopCellEditing() {
    CashFlow cashflow = new CashFlow((String)getSelectedItem());
    setSelectedItem(cashflow.getCashFlow());
    fireEditingStopped();
    return true;
    public void addCellEditorListener(CellEditorListener cel) {
    listeners.addElement(cel);
    public void removeCellEditorListener(CellEditorListener cel) {
    listeners.removeElement(cel);
    protected void fireEditingCanceled() {
    setSelectedItem(originalValue);
    ChangeEvent ce = new ChangeEvent(this);
    for(int i = listeners.size(); i >= 0; i--) {
    ((CellEditorListener)listeners.elementAt(i)).editingCanceled(ce);
    protected void fireEditingStopped() {
    ChangeEvent ce = new ChangeEvent(this);
    for(int i = listeners.size() - 1; i >= 0; i--) {
    ((CellEditorListener)listeners.elementAt(i)).editingStopped(ce);

    First off, I wouldn't subclass JComboBox to create a custom renderer/editor. I would have a renderer/editor component that makes use of a JComboBox. But that is just me.
    In order for setSelectedItem to work, the items in your combo box have to compare against each other correctly with equals(). Since you are creating new instances, your objects (even though they contain the same data) are going to be different instances and aren't going to be considered equal. Write your own equals() method in your CashFlow object that tests for equality based on the actual values in the objects and you should be fine.

  • 3 JComboBox in one panel

    Hi,
    I am using Java 1.3.1.
    I have a panel in which i am putting 3 JComboBox objects(typically a date ie day,mth,yr)
    the class implements ActionListener and in the actionPerformed i am tracking the events of tbese JComboBoxs'.However I want to indentify which combo box was cliked..ie was it day,mth,yr and accordingly write futher logic.
    How can i find which JComboBox is changed?
    Thanx a lot..it seems to be pretty simple..but somehow i am not able to get it..:(

    Never mind getActionCommand, you aren't required to set one, or you could change it in your code somewhere and break your listener. Use getSource() to the the object that caused the event. Then use 'if' to see if that object is cb1, cb2, or cb3..
    I'd make a small inner class for this panel that implements a listener, and add it to all 3 comboboxes.. Put the listeners on the comboboxes themselves, I wouldnt have the class implement a listener in this case..
    if(ae.getActionCommand().equals("comboBoxChanged"))
    JComboBox cb = (JComboBox)ae.getSource();

  • JTable with editable JComboBoxes

    For some reason once I added editable JComboBoxes to a JTable I can no longer tab among the fields in the table. If I just select a cell, I can tab to the other cells in that row, and then to proceeding rows as I reach the end of each. However if I double click the cell and enter data or select from the combobox. I no longer can tab to the next cell. At that point once I do hit tab, I am taken to the next table. Not the next cell in the row, or the next row in the current table.
    I have tried messing with a bunch of listeners, but I am not using the right listener on the right object? What listerner and object should the listener belong to? Table, model, cell editor, combobox, jpanel, jframe ? I hope this is not to vague.

    Well I am starting to think it's an implementation issue. Like I am not doing it how I should. I am basically doing
    JComboBox jcb = new JComboBox();
    jcb.setEditable(true);
    column.setCellEditor(new DefaultCellEditor(jcb));
    When I think I should be inheriting, and creating my own editor and/or renderer? Now my combobox vars are globally available in the class, so I can set and clear their contents. It does not matter that each row in the table has the same content in the combo boxes, that's basically what I want. User to be able to select an existing entry or make a new one.
    What I am trying to do is on tables have a drop down box that shows up when a user types a matching entry. If no entry matches, no popup box. If entry matches, box pops up and shows possible entries starting with what they are typing. Like code completion in IDE's like Netbeans. However I am doing this in a table. I thought a JComboBox would be a good widget to start with?

  • JComboBox is driving me crazy!!  Help,please??

    Hello!!
    The problem is that i have to get the MouseEvents whenever a user enters or exits or clicks mouse on an item inside JComboBox.
    Is there anyway to get the mouseEvents? I ve tried adding a lot of listeners but nothing works.
    Thanks a lot!

    Try this.
    When you click on the comboBox, the label is updated.
    Hope this help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ListDemo extends JFrame {
      JPanel jPanel1 = new JPanel();
      JLabel jLabel1 = new JLabel();
      JComboBox jComboBox1 = new JComboBox();
      public ListDemo() {
        for(int i = 0 ; i < 10 ; i++){
          jComboBox1.addItem("item n?"+i);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel1.setText("jLabel1");
        jComboBox1.addActionListener(new ListDemo_jComboBox1_actionAdapter(this));
        this.getContentPane().add(jPanel1, BorderLayout.NORTH);
        jPanel1.add(jComboBox1, null);
        this.getContentPane().add(jLabel1, BorderLayout.CENTER);
      void jComboBox1_actionPerformed(ActionEvent e) {
        this.jLabel1.setText(this.jComboBox1.getSelectedItem().toString());
        System.out.println("event for the comboBox");
      public static void main(String[] args){
           ListDemo temp = new ListDemo();
           temp.pack();
           temp.setVisible(true);
    * listener for the comboBox
    class ListDemo_jComboBox1_actionAdapter implements java.awt.event.ActionListener {
      ListDemo adaptee;
      ListDemo_jComboBox1_actionAdapter(ListDemo adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jComboBox1_actionPerformed(e);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Disabling selection of JSeparator in a JComboBox

    Does anyone know how to disable the selection of a JSeparator in a JComboBox?
    I'm using JRE 1.1.8.

    The BlockComboBox example doesn't allow the selection of the separator, however there is no way to move past the separator by using the arrow keys of the keyboard.
    I've tried to add a key listener, but for some reason the code never gets executed when hitting a key.
    Is there a problem with using key listeners with a JComboBox?

  • Color trouble with JComboBox

    I'm having trouble setting the background and foreground colors for disabled combo boxes. The thing is that the nasty Java system code uses the ComboBox.disabledForeground and ComboBox.disabledBackground UI values to set a combo boxes colors when it is disabled. They do NOT use the combo boxes (or renderers) background and foreground colors and overwrites whatever you set them to. This is all well and good if you plan to have ALL of your combo boxes use the same color schema as you can use the commands
    UIManager.getDefaults().put( "ComboBox.disabledForeground", color1 );
    UIManager.getDefaults().put( "ComboBox.disabledBackground", color2 );
    Unfortunately I have two separate panals where I want different color schemas to be used. Dang!
    I know very little about UI stuff. Is there any way to set attributes for components under specific panels? Is there any way to bypass the nasty Java system code? Do I have any hope at all?

    I handled it this way....
    * Copyright UPMC Health System, 2001 - All rights reserved.
    * This notice must not be removed or modified under any circumstances.
    package upmc.dsi.editor;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    import upmc.dsi.util.*;
    * JComboBoxEditor is an extension of JComboBox that implements the
    * EditingComponent interface. It also sets up listeners so that if any child
    * components fire an action, listeners to this component will be notified. This
    * is particularly necessary since events like focusGained are not reported to
    * listeners otherwise.
    * @author     $Author: kellymt $
    * @version     $Revision: 1.11 $ $Date: 2003/12/05 18:08:11Z $
    public class JComboBoxEditor extends JComboBox
        implements EditingComponent, FocusListener, KeyListener
        // A editor that uses the colors of this combo box to display the
        // items. If the user elects to use a different editor, it will be
        // up to him to use the appropriate colors.
        class LocalEditor extends BasicComboBoxEditor
            public Component getEditorComponent()
                Component pEditorComponent = super.getEditorComponent();
                pEditorComponent.setBackground( getBoxBackground() );
                pEditorComponent.setForeground( getBoxForeground() );
                return pEditorComponent;
        // A renderer that uses the colors of this combo box to render the
        // items. If the user elects to use a different renderer, it will be
        // up to him to use the appropriate colors.
        class LocalRenderer extends DefaultListCellRenderer
            public LocalRenderer()
                super();
            public Component getListCellRendererComponent(
                JList list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus )
                Component pLabel = super.getListCellRendererComponent(
                    list,
                    value,
                    index,
                    isSelected,
                    cellHasFocus );
                if ( ! isSelected )
                    setForeground( getBoxForeground() );
                    setBackground( getBoxBackground() );
                return pLabel;
         * Constructs an instance of this class and registers as a listener to all
         * of it's children for those events that need to be propagated.
        public JComboBoxEditor()
            super();
            setRenderer( new LocalRenderer() );
            setEditor( new LocalEditor() );
        protected Color getBoxForeground() {return getForeground();};
        protected Color getBoxBackground() {return getBackground();};
    }

  • JComboBox events as TableCellEditor

    I'm using a subclass of JComboBox as a TableCellEditor, and it isn't firing the same events as it does outside the table. For instance, when the combobox has editable focus, I can use the arrow keys to move the selection up and down the menu, and outside the Table, everytime I move the selection in this way, it sets the appropriate SelectedItem and SelectedIndex properties of the ComboBox to match my selection. But in the table, it doesn't set these properties just by chaning the selection in this way. It also doesn't fire an ItemChangeEvent like it does outside the table.
    Anyone know why this is happening and how I can work around it?
    Thanks.

    well, the keyinputhandler was a class in JClass's table extension!
    there was a traverse() method which we had to stick a requestFocus() in to make sure that all the right listeners were invoked from a 'move' event....
    not entirely sure where you'd stick it in normal swing JTables....!
    (apols!)

Maybe you are looking for