resize JMenuPopup component

I cannot get a JMenuPopup component to resize. See the code below (2 classes). To see the problem, run main in MyTable_TextField, then in the table, click in the first cell, type "aa" to see menu popup, then type "a" again to refine menu. The menu changes, but the size does not. I've created an "invisible" popup that should be the size I want, but setting the preferred size to that doesn't seem to work.


import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class MyTable_TextField extends JTable {

	private DefaultTableModel defaultTableModel;

	private Object[][] dataArray;
	private Object[] columnNameArray;

	private final int TEXT_COLUMN = 0;	

	// column headers
	private static final String TEXT_COLUMN_HEADER = "Text";

	// text field editor (one line)
	private JTextField  jTextField;

	// text field editor
	private MyTextFieldEditor textFieldEditor;

	private List<String> nameList;

	/**
	 * constructor
	 * 
	 * @param dataNameArray
	 * @param columnNameArray
	 */
	public MyTable_TextField(Object[][] dataNameArray, Object[] columnNameArray, List<String> nameList) {

		this.dataArray = dataNameArray;
		this.columnNameArray = columnNameArray;

		defaultTableModel = new DefaultTableModel(dataNameArray, columnNameArray);
		this.setModel(defaultTableModel)	;

		this.nameList = nameList;

		// text field
		jTextField = new JTextField();

		TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);

		DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); // renderer
		//renderer.setToolTipText("Double click to type"); // tooltip
		modelColumn.setCellRenderer(renderer);

		textFieldEditor = new MyTextFieldEditor(jTextField, nameList);
		modelColumn.setCellEditor(textFieldEditor); // editor

		MyDocumentListener documentListener = new MyDocumentListener(nameList);
		jTextField.getDocument().addDocumentListener(documentListener);

	}

	/**
	 * nested class
	 *
	 */
	class MyDocumentListener implements DocumentListener {
		private String newline = "\n";
		private List<String> nameList;
		
		/**
		 * constructor
		 * 
		 * @param nameList
		 */
		public MyDocumentListener (List<String> nameList) {
			this.nameList = nameList;
		}
		
		@Override
		public void insertUpdate(DocumentEvent e) {
			System.out.println ("insert update");
			doSomething(e);
		}

		@Override
		public void removeUpdate(DocumentEvent e) {
			System.out.println ("remove update");
			doSomething(e);
		}
		@Override
		public void changedUpdate(DocumentEvent e) {
			//Plain text components do not fire these events
		}

		/**
		 * 
		 * @param documentEvent
		 */
		public void doSomething(DocumentEvent documentEvent) {
			
			Document document = (Document) documentEvent.getDocument();
			
			int stringLength = document.getLength();
			if (stringLength >= 2) {
				String refineString= "";
				try {
					refineString = document.getText(0, document.getLength());
				} catch (BadLocationException e2) {
					System.out.println ("MyDocumentListener.doSomething() ");
					e2.printStackTrace();
				}

				// popup variable list
				NamePopupMenu namePopupMenu = NamePopupMenu.getInstance();
				namePopupMenu.initialize(nameList, refineString);
				
			}
			
			//int changeLength = e.getLength();
			//System.out.println ("document.length(): " + document.getLength() + "\tchangeLength: " + changeLength);
			//try {
			//	System.out.println ("doc.getText(): " + document.getText(0, document.getLength() ) );
			//} catch (BadLocationException e1) {
			//	e1.printStackTrace();
			//}			
		}
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		try{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}
		catch (Exception e){
			e.printStackTrace();
		}

		final String[] FAKE_NAMES_ARRAY = {
				"aaa", "aab",	"aac","aaab", "aaac", "aaad","aaaab", "aaaac", "aaaad","aaaaab", "aaaaac", "aaaaad",
				"bba", "bbb",	"bbc",
				"cca", "ccb", 	"ccc", "ccd",
				"dda", "ddb",	"ddc",
				"eea", "eeb",	"eec",
				"ffa", "ffb",	"ffc",
				"gga", "ggb",	"ggc",
				"hha", "hhb",	"hhc",
				"gga", "ggb",	"ggc",
				"hha", "hhb",	"hhc",
				"iia", "iib",	"iic",
				"jja", "jjb",	"jjc",
				"kka", "kkb",	"kkc",
				"lla", "llb",	"llc",
				"mma", "mmb",	"mmc",
				"nna", "nnb",	"nnc",
				"ooa", "oob",	"ooc",
				"ppa", "ppb",	"ppc",
				"qqa", "qqb",	"qqc",
				"rra", "rrb",	"rrc",
				"ssa", "ssb",	"ssc","sssa", "sssb",	"sssc","ssssa", "ssssb","ssssc","sssssa", "sssssb",	"sssssc",
				"tta", "ttb",	"ttc",
				"uua", "uub",	"uuc",
		};

		List<String> nameList = new ArrayList<String>();
		// fake data for now
		for (String name : FAKE_NAMES_ARRAY) {
			nameList.add(name);
		}

		String[] columnNameArray = {
				TEXT_COLUMN_HEADER,
				"1",
				"2",
		};

		Object[][]  dataArray = { 	{"", "", ""}, 	};

		final MyTable_TextField panel = new MyTable_TextField(dataArray, columnNameArray, nameList);

		final JFrame frame = new JFrame();
		frame.getContentPane().add(new JScrollPane(panel));
		frame.setTitle("MyTable_TextField");
		frame.setPreferredSize(new Dimension(500, 200));
		frame.addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e) {
			}
		});

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setLocation(300, 200);
		frame.pack();
		frame.setVisible(true);

	}

}

/**
 * nested class
 */
class MyTextFieldEditor extends DefaultCellEditor {

	private JTextField  jTextField;
	private List<String> nameList;
	private String value;

	/**
	 * constructor
	 */
	public MyTextFieldEditor(JTextField jTextField, List<String> nameList) {

		//super(new JTextField());
		super(jTextField);
		this.jTextField = jTextField;
		this.nameList = nameList;
	}

	@Override
	public Object getCellEditorValue() {
		System.out.println("getCellEditorValue(): " + value);
		return value;
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
			int row, int column) {
		System.out.println("getTableCellEditorComponent(): " + value);

		this.value = (String) value;
		jTextField = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);

		if (value != null) {
			jTextField.setText(value.toString());
			if (value.toString().length() <= 1) {
				// do something
			}
			else { // length is 2 or more
				// do something else
			}
		}

		return jTextField;
	}

}

--------------------------------

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.border.BevelBorder;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

public class NamePopupMenu extends JPanel implements EditorConstants {
	
	private static NamePopupMenu instance = null; // singleton
	
	private JPopupMenu popup;
	private JPopupMenu invisiblePopup;

	private JComponent parent;
	
	private List<String> nameList;
	
	private int xCoordinate;
	private int yCoordinate;

	private String SELECT_NAME = "Select a name below";

	/**
	 * constructor
	 * do nothing because of singleton, call initialize() instead
	 */
	public NamePopupMenu() {

	} // end constructor
	
	/**
	 * singleton
	 * 
	 * @return
	 */
	public static NamePopupMenu getInstance()
	{
		if (instance == null) {
			instance = new NamePopupMenu();
		}
		return instance;
	}
	


	/**
	 * constructor
	 * 
	 * @param name list
	 * @param String to refine name list by
	 */
	public void initialize(List<String> bigNameList, String refineString) {
		
		// if popup doesn't exist yet, create it
		if (popup == null) {
			popup = new JPopupMenu();
		}
		else { // popup does exist, so remove any previous menu items
			popup.removeAll();
			// need to resize
		}

		this.nameList = new ArrayList<String>();
		Iterator<String> bigNameIterator = bigNameList.iterator();
		while (bigNameIterator.hasNext()) {
			String name = new String(bigNameIterator.next());
			// if this name starts with same characters as refineString then remove it from the list
			if ( name.startsWith(refineString)) {
				this.nameList.add(name);
			}
		}		

		xCoordinate = 0;
		yCoordinate = 0;
				
		setComponent();		
	}
	
	/**
	 * 
	 */
	private void setComponent() {
		
		invisiblePopup  = new JPopupMenu();	
		
		ActionListener menuListener = new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				//System.out.println("Popup menu item [" + event.getActionCommand() + "] was pressed.");
				menuItemSelected(event.getActionCommand());

			}
		};
			
		// set items in menulist
		setMenuItem(menuListener, SELECT_NAME);

		setMenuItemInvisible(menuListener, SELECT_NAME);

		Iterator<String> nameIterator = nameList.iterator();
		while (nameIterator.hasNext()) {
			String name = nameIterator.next();
			setMenuItem(menuListener, name);
			setMenuItemInvisible(menuListener, name);
		}

		popup.setBorder(new BevelBorder(BevelBorder.RAISED));
		invisiblePopup.setBorder(new BevelBorder(BevelBorder.RAISED));
		
		popup.addPopupMenuListener(new PopupPrintListener());

		System.out.println ("invisiblePopup size: " + invisiblePopup.getPreferredSize());
		popup.setPreferredSize(invisiblePopup.getPreferredSize());
		//popup.setPreferredSize(new Dimension(200,300));
		
		popup.setVisible(true);
		popup.setLocation(xCoordinate, yCoordinate);

		addMouseListener(new MousePopupListener());	
	}


	private void setMenuItem(ActionListener menuListener, String name) {
		JMenuItem item = new JMenuItem(name);
		popup.add(item);
		item.setHorizontalTextPosition(JMenuItem.RIGHT);
		item.addActionListener(menuListener);
	}

	private void setMenuItemInvisible(ActionListener menuListener, String name) {
		JMenuItem item = new JMenuItem(name);
		invisiblePopup.add(item);
		item.setHorizontalTextPosition(JMenuItem.RIGHT);
		item.addActionListener(menuListener);
	}

	
	/**
	 * called when menu item is selected
	 */
	public void menuItemSelected(String actionCommand) {

		System.out.println("menuItemSelected(): " + actionCommand);
		
		if (actionCommand.equalsIgnoreCase(SELECT_NAME)) {
			System.out.println("\tdo nothing");
		}
		else { // its a name, so return it
			System.out.println("\treturn to cell with name");
			popup.setVisible(false); // hide popup menu
			// set value of operator button to the menu item selection
			//parent.setText(actionCommand);
		}

	}

	/**
	 * nested class to check whether mouse events are the popup trigger
	 */
	class MousePopupListener extends MouseAdapter {
		public void mousePressed(MouseEvent e) {
			checkPopup(e);
		}

		public void mouseClicked(MouseEvent e) {
			checkPopup(e);
		}

		public void mouseReleased(MouseEvent e) {
			checkPopup(e);
		}

		private void checkPopup(MouseEvent e) {
			if (e.isPopupTrigger()) {
				popup.show(NamePopupMenu.this, e.getX(), e.getY());
			}
		}
	}

	/**
	 * nested class to show when popup events occur
	 */
	class PopupPrintListener implements PopupMenuListener {

		public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
			System.out.println("Popup menu set to visible");
		}

		public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
			System.out.println("Popup set to invisible");
		}

		public void popupMenuCanceled(PopupMenuEvent e) {
			System.out.println("Popup menu is hidden");
		}
	}

	/**
	 * 
	 * @param s
	 */
	public static void main(String s[]) {

		String refineString = "";
		
		List<String> nameList = new ArrayList<String>();
		nameList.add("aaa");
		nameList.add("aab");
		nameList.add("aac");
		nameList.add("baa");
		nameList.add("bab");
		nameList.add("bac");
		nameList.add("caa");
		nameList.add("cab");
		nameList.add("cac");
		nameList.add("cad");
		
		JFrame frame = new JFrame("Popup Menu Example Visible");
		
		// popup name list
		NamePopupMenu variablePopupMenu = NamePopupMenu.getInstance();
		variablePopupMenu.initialize(nameList, refineString);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(variablePopupMenu);
		frame.setSize(300, 300);
		frame.setLocation(300,300);
		frame.setVisible(true);
	}
}

Open in new window

LVL 1
allelopathAsked:
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.

objectsCommented:
shouldn't you be hiding the old popup when you create a new one?

            else { // popup does exist, so remove any previous menu items
                  popup.setVisible(false);
                  popup.removeAll();
                  // need to resize
            }
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
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
Editors IDEs

From novice to tech pro — start learning today.