Table Selection Event

package tabledemo;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JT3 {
	public static void main(String arg[]) {
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JTable table = new JTable(4, 5);

		SelectionListener listener = new SelectionListener(table);
		table.getSelectionModel().addListSelectionListener(listener);
		table.getColumnModel().getSelectionModel()
				.addListSelectionListener(listener);

		frame.add(new JScrollPane(table));
		frame.setSize(300, 200);
		frame.setVisible(true);
	}
}

class SelectionListener implements ListSelectionListener {
	JTable table;

	// It is necessary to keep the table since it is not possible
	// to determine the table from the event's source
	SelectionListener(JTable table) {
		this.table = table;
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		int first = 0, last = 0;
		// If cell selection is enabled, both row and column change events are
		// fired
		if (e.getSource() == table.getSelectionModel()
				&& table.getRowSelectionAllowed()) {
			// Column selection changed
			first = e.getFirstIndex();
			last = e.getLastIndex();
		} else if (e.getSource() == table.getColumnModel().getSelectionModel()
				&& table.getColumnSelectionAllowed()) {
			// Row selection changed
			first = e.getFirstIndex();
			last = e.getLastIndex();
		}

		if (e.getValueIsAdjusting()) {
			// The mouse button has not yet been released
		}
		System.out.println("First " + first + "Last " + last);
	}
}
/*
  
  
 */

Download

Table in Swing

Simple Table with fixed value in Swing
Table with Editable cell in Swing
Events in Table in Swing


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code