Search code examples
javaswingjcomboboxactionlistenercardlayout

Changing the value of a JComboBox in Java


I'm trying to change the value of a JComboBox, from an ActionListener, and having no luck.

I have a JComboBox that when changed changes the CardLayout (switched to another GUI).

I have a Menu Bar with options for the user, that I'd like to have automatically change the JComboBox selectedItem. Essentially, my end desire is to have it where the menu bar can change the CardLayout (but I haven't been able to get close to changing the card layout with my ActionListener).

It looks like the code can't find the JComboBox, from the inner listener class.

Any help at all, including references for me to go read about, would be greatly appreciated.

Here is my current code (still very much in development):

package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.rmi.*;

public class InventoryTrackingSystem implements ItemListener {
  JPanel mainPanel;
  JFrame frame;

  JPanel cards; //a panel that uses CardLayout
  final static String MAINPANEL = "Main";
  final static String CHECKITEMSPANEL = "Check Items";
  final static String NEWITEMPANEL = "New Item";
  final static String CHECKOUTITEMPANEL = "Check Out Item";
  final static String ITEMINFOPANEL = "Item Information";
  JPanel comboBoxPane;
  private JComboBox cb;
  static String comboBoxItems[] = {MAINPANEL,CHECKITEMSPANEL,NEWITEMPANEL,CHECKOUTITEMPANEL,ITEMINFOPANEL};

  public static void main(String[] args) {
    final InventoryTrackingSystem ITS = new InventoryTrackingSystem();
    /* Use an appropriate Look and Feel */
    try {
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
    } catch (IllegalAccessException ex) {
      ex.printStackTrace();
    } catch (InstantiationException ex) {
      ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
//    javax.swing.SwingUtilities.invokeLater(new Runnable() {
//      public void run() {
        ITS.createAndShowGUI();
//      }
//    });

  }

  public void addComponentToPane(Container pane) {
    //Put the JComboBox in a JPanel to get a nicer look.
    comboBoxPane = new JPanel(); //use FlowLayout
    cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);

    //Create the "cards".
    JPanel main = new guiBuilder().buildGui("main");
    JPanel checkItems = new guiBuilder().buildGui("checkItems");
    JPanel newItems = new guiBuilder().buildGui("newItems");
    JPanel checkOutItems = new guiBuilder().buildGui("checkOutItems");
    JPanel itemInfo = new guiBuilder().buildGui("itemInfo");

    //Create the panel that contains the "cards".
    cards = new JPanel(new CardLayout());
    cards.add(main, MAINPANEL);
    cards.add(checkItems, CHECKITEMSPANEL);
    cards.add(newItems, NEWITEMPANEL);
    cards.add(checkOutItems, CHECKOUTITEMPANEL);
    cards.add(itemInfo, ITEMINFOPANEL);

    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(cards, BorderLayout.CENTER);
  }

  public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
  }

  /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private void createAndShowGUI() {
      //Create and set up the window.
      frame = new JFrame("Inventory Tracking System");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.setLayout(new BorderLayout());
      Menu m1 = new Menu("Options");

      MenuItem mi1_0 = new MenuItem("Main Page");
        mi1_0.setActionCommand("main");
        mi1_0.addActionListener(new menuListener());

      MenuItem mi1_1 = new MenuItem("Check Item");
        mi1_1.setActionCommand("checkItem");
        mi1_1.addActionListener(new menuListener());
      MenuItem mi1_2 = new MenuItem("Add New Item");
        mi1_2.setActionCommand("addItem");
        mi1_2.addActionListener(new menuListener());
      MenuItem mi1_3 = new MenuItem("List All Items");
        mi1_3.setActionCommand("listAllItems");
        mi1_3.addActionListener(new menuListener());
      MenuItem mi1_4 = new MenuItem("Exit");
        mi1_4.setActionCommand("exit");
        mi1_4.addActionListener(new menuListener());

      Menu m2 = new Menu("Help");
      MenuItem mi2_0 = new MenuItem("About");
        mi2_0.setActionCommand("about");
        mi2_0.addActionListener(new menuListener());

      m1.add(mi1_0);
      m1.add(mi1_1);
      m1.add(mi1_2);
      m1.add(mi1_3);
      m1.add(mi1_4);

      m2.add(mi2_0);

      MenuBar mb = new MenuBar();
      frame.setMenuBar(mb);
      mb.add(m1);
      mb.add(m2);

      //Create and set up the content pane.
      InventoryTrackingSystem setGUI = new InventoryTrackingSystem();
      setGUI.addComponentToPane(frame.getContentPane());

      //Display the window.
      frame.pack();
      frame.setVisible(true);

      frame.setSize(500, 500);
      frame.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent we){
          System.exit(0);
        }
        public void windowClosed(WindowEvent we){
          System.exit(0);
        }
      });

    }

    class menuListener implements ActionListener{
      public void actionPerformed(ActionEvent ev){
        String thisAction=ev.getActionCommand();

        if(thisAction.equals("main")){
          cb.setSelectedItem(MAINPANEL);
        }else if(thisAction.equals("checkItem")){
          //change GUI
        }else if(thisAction.equals("addItem")){
          //change GUI
        }else if(thisAction.equals("listAllItems")){
          //change GUI
        }else if(thisAction.equals("exit")){
          System.exit(0);
        }else if(thisAction.equals("about")){
          JOptionPane.showMessageDialog(frame, "About This App");
        }
      }
    }
}

The Error that I'm getting when I try to use the menu is as follows:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
  at inventorytrackingsystem.InventoryTrackingSystem$menuListener.actionPerformed(InventoryTrackingSystem.java:161)
  at java.awt.MenuItem.processActionEvent(MenuItem.java:627)
  at java.awt.MenuItem.processEvent(MenuItem.java:586)
  at java.awt.MenuComponent.dispatchEventImpl(MenuComponent.java:337)
  at java.awt.MenuComponent.dispatchEvent(MenuComponent.java:325)
  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:646)
  at java.awt.EventQueue.access$000(EventQueue.java:84)
  at java.awt.EventQueue$1.run(EventQueue.java:602)
  at java.awt.EventQueue$1.run(EventQueue.java:600)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
  at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
  at java.awt.EventQueue$2.run(EventQueue.java:616)
  at java.awt.EventQueue$2.run(EventQueue.java:614)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
  at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
  at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 6 seconds)

Solution

  • The root problem appears to be related to the fact that you instantiate two instances of your InventoryTrackingSystem. The cb field in one instance is set while the same field in the other instance is still null. I am not sure why you are setting up two instances of this class, but I suspect if you examine that you will uncover your problem.

    Good luck.