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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (JTablePopupMenuDemo.zip)JTablePopupMenuDemo.zip[Full source code and executable jar file]10 kB

Add comment

   


Comments 

#11Bob2024-07-17 00:36
TableMouseListener ---> error: cannot find symbol
Quote
#10Nam2018-06-03 22:17
Quoting Ave:
Thanks for the code.
In case the click is outside a row, how do I make the TableMouseListener class prevent the popup from showing?

Maybe you need to add checking code in the mousePressed() method. Check if there's any row in the current mouse position. If no, setComponentPopupMenu(null). Let try it.
Quote
#9Ave2018-05-30 15:31
Thanks for the code.
In case the click is outside a row, how do I make the TableMouseListener class prevent the popup from showing?
Quote
#8Jimmy2016-03-15 10:29
no funciona si el jtable no tiene filas, alguna solucion?, gracias
Quote
#7Nitin Rathour2015-12-17 01:15
hi

pop up window not showing. what sud i do
Quote