How to resolve an error in ActionPerformer Method

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

Vanavah EdwardsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vanavah EdwardsAuthor 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)
0
for_yanCommented:
What error do you see and from which line - post stack trace
0
for_yanCommented:
which is line 42
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

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


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

like that:

 cb2 = new JComboBox(elements);

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
for_yanCommented:
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
0
for_yanCommented:
You need to understand the difference between instance variable and local vraibles - this is fundamental issue for java
0
for_yanCommented:

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
0
Vanavah EdwardsAuthor 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.
0
for_yanCommented:
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.
0
Vanavah EdwardsAuthor Commented:
i think you would have to determine if th tab, enter, and mouse selected.
0
for_yanCommented:
Normal combobox triggers actionPerformed only when these special events happen, each letter typed in - should not trigger actionPerformed
They should have retained this functionality
0
Vanavah EdwardsAuthor 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.

0
for_yanCommented:

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
0
Vanavah EdwardsAuthor Commented:
How do I determine the if the tab or enter key is selected?
Can you set the key listener for a combobox field?
0
Vanavah EdwardsAuthor 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.

0
for_yanCommented:
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.
0
for_yanCommented:
I don't think that it will be easy to do - check if it really triggers keyEEvents
0
Vanavah EdwardsAuthor 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.
0
Vanavah EdwardsAuthor 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

0
for_yanCommented:
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.
0
Vanavah EdwardsAuthor 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

0
Vanavah EdwardsAuthor Commented:
Can you say what is wrong with the last code posted?
0
for_yanCommented:
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.




0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.