How to resolve an error in ActionPerformer Method

Vanavah Edwards
Vanavah Edwards used Ask the Experts™
on
This is a simple program for determing the item selected from an auto-completion JComboBox.  The code seems correct.  However, I am getting an error that I am unable to resolve. This simple isolation program principle is to be used as part of a larger program.  Please help.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

public class SimpleSwingX_VE  {

	private static JComboBox cb2;
	
	public static void main(String[] args) {
		JFrame f = new JFrame();
		JPanel p = new JPanel();
		Object[] elements = {"","Ester","Jordi","Jordina","Jorge","Sergi","Tarion","Riano","Tammy","Debbie","Stephen"};
		JComboBox cb2 = new JComboBox(elements);
		cb2.setEditable(true);
//		AutoCompleteDecorator.decorate(cb2);  // auto-complete feature
		ActionPerformer ap = new ActionPerformer();
		cb2.addActionListener(ap);
		p.add(cb2);
		f.add(p);
		f.setSize(200, 300);
		f.setVisible(true);
	}

	private static class ActionPerformer implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			if (e.getSource().equals(cb2)) {
		          System.out.println("You've seleccted - "+cb2.getSelectedItem());
			}
		}	
	}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
HERE IS THE ERROR I FORGOT TO POST :-
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
      at autocompletion.SimpleSwingX_VE$ActionPerformer.actionPerformed(SimpleSwingX_VE.java:42)
      at javax.swing.JComboBox.fireActionEvent(Unknown Source)
      at javax.swing.JComboBox.setSelectedItem(Unknown Source)
      at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
      at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
      at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
      at java.awt.Component.processMouseEvent(Unknown Source)
      at javax.swing.JComponent.processMouseEvent(Unknown Source)
      at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(Unknown Source)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Window.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForFilter(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)
Awarded 2011
Awarded 2011

Commented:
What error do you see and from which line - post stack trace
Awarded 2011
Awarded 2011

Commented:
which is line 42
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

Author

Commented:
This error happend in line 33 System.out.println("You've seleccted - "+cb2.getSelectedItem());
The main caused is the command  - getSelectedItem());
Awarded 2011
Awarded 2011
Commented:


Remove declaraio from here:
JComboBox cb2 = new JComboBox(elements);

like that:

 cb2 = new JComboBox(elements);

Awarded 2011
Awarded 2011
Commented:
we already went through that once
  This leads to the situation when your cb2 checkbox - is no longer insatnce varuiable - but becomces local
      JComboBox cb2 = new JComboBox(elements);

so your instance cb2 remains null - and therefore you have null pointer execeoption
Awarded 2011
Awarded 2011
Commented:
You need to understand the difference between instance variable and local vraibles - this is fundamental issue for java
Awarded 2011
Awarded 2011

Commented:

cb2 is null as you instantiated  not instance variable but local vraiable cb2
therefore you are trying to invoke method on null - hence null pointer excepion:
cb2.getSelectedItem

Author

Commented:
You are right.  I forgot, I will make a note.  I made the change and it worked.  However, how can I ensure a final selection because each time I type thorough the auto-complete list if goes to the actionperformed method.
Awarded 2011
Awarded 2011

Commented:
That can potentially be a big problem - it should trigger only when you actually select.
It this autocomplete has this issue then it may be necessary to find workaround - check if it is indeed happening without actual selection.

Author

Commented:
i think you would have to determine if th tab, enter, and mouse selected.
Awarded 2011
Awarded 2011

Commented:
Normal combobox triggers actionPerformed only when these special events happen, each letter typed in - should not trigger actionPerformed
They should have retained this functionality

Author

Commented:
I think the solutionn is one of 2 things:
(1) if (e.getSource().equals(cb1)) + tab key or (e.getSource().equals(cb1)) + mouseselection
But I need to know how do you determing the tab, enter selection code in java  for this method
(2) May be the auto-completion list has a setting.

Awarded 2011
Awarded 2011

Commented:

I am afraid this idea about auto-completion is rather too complicated; perhaps you need some commercial third-party library for that; don't know

Author

Commented:
How do I determine the if the tab or enter key is selected?
Can you set the key listener for a combobox field?

Author

Commented:
How do you return false or and prevent tabbing ot the next line?
I use
if(cb1.getSelectedItem().equals(null)) {
to determine if nothing is selected but the returing false and remain on that line is my problem.

Awarded 2011
Awarded 2011

Commented:
You could try to add KeyListener and then it is easy to check if key events will be triggered by combobox - just print out soemthing from the key event handler,
like in the methods keyTyped, keyPressed, etc.
Awarded 2011
Awarded 2011

Commented:
I don't think that it will be easy to do - check if it really triggers keyEEvents

Author

Commented:
I would like to close of this session.  If you can please give me this solution I will award point for the solution and close this session off or should I post it.  
Can I have the code to determine in the ActionPerformed if the tab or enter key was pressed or relesased? And how to return false or remain on that line say if tab was press and nothing was selected.  This would close this session off and solve the problem I originally asked.

Author

Commented:
Hi for_van
I found a solution.  The tab key is the common key that us use to go through a form.  It is best to elimante the current key set and only allow the "enter" key to be used per component.  Why?  Because the tab key does not trigger events sometimes in the actionPerformer especially with auto-completion.  But enter does on every component.  I used the attached code per component.  This works perfect for me and it looks like i can trigger test for every component.  What do you think?
//Set key to be used through the form (enter and disable tab) for each component
        Set set1 = new HashSet(cb1.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
        set1.clear();   // to eliminate the current key set
        set1.add(KeyStroke.getKeyStroke("ENTER"));
        cb1.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set1);

Open in new window

Awarded 2011
Awarded 2011

Commented:
I cannot say just looking at the code. This is a matter of experimenting. If that works for you, then it's good. In general, if the issue affects only the tab key, then it is not that dramatic, as tab key is operceived by most iusers as a special key which moves to the next element say in the browser for web applications, so that is not that dramatic. If yiu want to leave only enter and this worksfor youi then it is fine. I was rather under impression that typing any charcter in the box generates action event; that would have been  a real  probkem. I do have my test code with swingx autocompletion on one of my computers - I'll look more attentively at this event firing when I reach that computer of mine.

Author

Commented:
Now that I switch to the return key I still have the problem now with the enter key.  What I want is to trigger an action event in a field when the tab key is pressed.  It skips the fields when tabe is pressed without going to the actionPerformer method. I works with the enter key but then it wouldn't go to the next field.  How do you the tab trigger when tab is press for testing.  See simple code below.
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

public class ActionListenerTest1 {

	private static JTextField tf1, tf2;

  public static void main(String[] args) {
    MyActionListener mal = new MyActionListener();
    tf1 = new JTextField(15);
    tf1.addActionListener(mal);

    tf2 = new JTextField(15);
    tf2.addActionListener(mal);
    
    JPanel p = new JPanel();
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("ActionListener Test 1");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300,300);
    p.add(tf1);
    p.add(tf2);
    f.add(p);
    f.setVisible(true);
  }

  public static class MyActionListener implements ActionListener {

	  public void actionPerformed(ActionEvent e) {
		  System.out.println("You've entered "+tf1.getText());
		  if(tf1.getText().equals("")) {
//			  System.out.println(tf1.getText()); // gets what's entered
		  }
	}
  }
}

Open in new window

Author

Commented:
Can you say what is wrong with the last code posted?
Awarded 2011
Awarded 2011

Commented:
No, with textfields everything seesm quite obvious.

Only Enter in the textbox triggers ActionEvent

Tab moves the focus to the next box but doe not trigger ActionEvent

Howvere any typed or even pressed key will trigger KeyEvent so with KeyListener
you can do with any key whatever you want - that is more or lest the rule with JTextField.

Therefore if your goal is imply to get when user typed it and finished with enter - you use ActionListener
In more sophisticed cases you can achieve all your goals with KeyListener

What I was writing about my doubts - it was all concenring the JComboBox.
And you may think that it has a textfield incorposrated,
but I'm not quite sure that that apparent textfiled will respond in the same
way to the envents, as the real textfiled.




Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial