Java Swing Popup Menu Example

In this article, we are going to show you how to create a popup menu for JTable component like this:

JTable popup menu demo program

This popup menu is shown up when the user right clicks over the table rows area. It provides three commands:

    • Add New Row: Appends a new empty row at the end of the table.
    • Remove Current Row: Deletes the currently selected row.
    • Remove All Rows: Deletes all rows in the table.

Notice that we will make the row at the mouse-clicked position automatically selected, which is a typical behavior. Let's go through the steps to create such a program in Java Swing.

1. Creating popup menu for a JTable

It's trivial to create a popup menu with some menu commands, for example:

JPopupMenu popupMenu = new JPopupMenu(); JMenuItem menuItemAdd = new JMenuItem("Add New Row"); JMenuItem menuItemRemove = new JMenuItem("Remove Current Row"); JMenuItem menuItemRemoveAll = new JMenuItem("Remove All Rows");  popupMenu.add(menuItemAdd); popupMenu.add(menuItemRemove); popupMenu.add(menuItemRemoveAll);

Add this popup menu for a JTable as follows:

JTable table = new JTable(); // set data model for the table...  // sets the popup menu for the table table.setComponentPopupMenu(popupMenu);

2. Making a row selected when the popup menu is displayed

It's a little trick to make a row automatically selected when the user right clicks on the table. Create a handler class for mouse-clicking events as follows:

package net.codejava.swing.jtable;  import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;  import javax.swing.JTable;  /**  * A mouse listener for a JTable component.  * @author www.codejava.neet  *  */ public class TableMouseListener extends MouseAdapter { 	 	private JTable table; 	 	public TableMouseListener(JTable table) { 		this.table = table; 	} 	 	@Override 	public void mousePressed(MouseEvent event) { 		// selects the row at which point the mouse is clicked 		Point point = event.getPoint(); 		int currentRow = table.rowAtPoint(point); 		table.setRowSelectionInterval(currentRow, currentRow); 	} }

And add this listener to the table like this:

table.addMouseListener(new TableMouseListener(table));        

3. JTable popup menu demo program

Following is a Swing demo program that incorporates the above stuffs. It creates a JTable with some dummy row data, and implements functions to add a new empty row, delete the selected row and delete all rows, as corresponding to the popup menu's commands. Here's the full source code:

package net.codejava.swing.jtable;  import java.awt.event.ActionEvent; import java.awt.event.ActionListener;  import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel;  /**  * A Swing program that demonstrates how to create a popup menu  * for a JTable component.  * @author www.codejava.net  *  */ public class JTablePopupMenuExample extends JFrame implements ActionListener {  	private JTable table; 	private DefaultTableModel tableModel;  	private JPopupMenu popupMenu; 	private JMenuItem menuItemAdd; 	private JMenuItem menuItemRemove; 	private JMenuItem menuItemRemoveAll; 	 	public JTablePopupMenuExample() { 		super("JTable Popup Menu Example"); 		 		// sample table data 		String[] columnNames = new String[] {"Title", "Author", "Publisher", "Published Date", "Pages", "Rating"}; 		String[][] rowData = new String[][] { 			{"Effective Java", "Joshua Bloch", "Addision-Wesley", "May 08th 2008", "346", "5"},	 			{"Thinking in Java", "Bruce Eckel", "Prentice Hall", "Feb 26th 2006", "1150", "4"},	 			{"Head First Java", "Kathy Sierra & Bert Bates", "O'Reilly Media", "Feb 09th 2005", "688", "4.5"},	 		}; 		 		 		// constructs the table with sample data 		tableModel = new DefaultTableModel(rowData, columnNames); 		table = new JTable(tableModel); 		 		// constructs the popup menu 		popupMenu = new JPopupMenu(); 		menuItemAdd = new JMenuItem("Add New Row"); 		menuItemRemove = new JMenuItem("Remove Current Row"); 		menuItemRemoveAll = new JMenuItem("Remove All Rows"); 		 		menuItemAdd.addActionListener(this); 		menuItemRemove.addActionListener(this); 		menuItemRemoveAll.addActionListener(this); 		 		popupMenu.add(menuItemAdd); 		popupMenu.add(menuItemRemove); 		popupMenu.add(menuItemRemoveAll); 		 		// sets the popup menu for the table 		table.setComponentPopupMenu(popupMenu); 		 		table.addMouseListener(new TableMouseListener(table)); 		 		// adds the table to the frame 		add(new JScrollPane(table)); 		 		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 		setSize(640, 150); 		setLocationRelativeTo(null); 	} 	 	public static void main(String[] args) { 		SwingUtilities.invokeLater(new Runnable() { 			@Override 			public void run() { 				new JTablePopupMenuExample().setVisible(true); 			} 		}); 	}  	@Override 	public void actionPerformed(ActionEvent event) { 		JMenuItem menu = (JMenuItem) event.getSource(); 		if (menu == menuItemAdd) { 			addNewRow(); 		} else if (menu == menuItemRemove) { 			removeCurrentRow(); 		} else if (menu == menuItemRemoveAll) { 			removeAllRows(); 		} 	} 	 	private void addNewRow() { 		tableModel.addRow(new String[0]); 	} 	 	private void removeCurrentRow() { 		int selectedRow = table.getSelectedRow(); 		tableModel.removeRow(selectedRow); 	} 	 	private void removeAllRows() { 		int rowCount = tableModel.getRowCount(); 		for (int i = 0; i < rowCount; i++) { 			tableModel.removeRow(0); 		} 	} }

Download the source code and demo program (executable jar file) in the Attachments section.

Related JTable Tutorials:

  • A Simple JTable Example for Display
  • Editable JTable Example
  • JTable Simple Renderer Example
  • 6 Techniques for Sorting JTable You Should Know
  • How to scroll JTable row to visible area programmatically
  • JTable column header custom renderer examples
  • Setting column width and row height for JTable
  • How to handle mouse clicking event on JTable column header
  • How to create JComboBox cell editor for JTable

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

desalvooptale.blogspot.com

Source: https://www.codejava.net/java-se/swing/jtable-popup-menu-example

0 Response to "Java Swing Popup Menu Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel