[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

resize JMenuPopup component

Posted on 2010-03-23
1
Medium Priority
?
604 Views
Last Modified: 2013-11-23
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

0
Comment
Question by:allelopath
1 Comment
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 28388011
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

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.

611 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question