Listener for selection in JTable
Hello everybody,
following problem. I have to check, if an selection in an JTable is valid or not. For this purpose I need to have a listener, which is invoked when a line or multiple lines of a JTable have been selected.
Thanks for your help
you can use myTable.addMouseListener() to add a listener to the table;
then to get the row index where the event happened you can use:
myTable.rowAtPoint(yourEvent.getPoint());
for instance:
myTable.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
//there you get the row index
int myIndex=myTable.rowAtPoint(me.getPoint());
});
Similar Messages
-
Document Listener for JTextArea in JTable
I am trying to implement a DocumentListener for JTextArea in JTable, but its not happening.
Can someone tell me what's wrong. SSCCE below.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.Document;
public class MyTable_TextArea extends JTable {
private DefaultTableModel defaultTableModel;
private Object[][] dataArray;
private Object[] columnNameArray;
public final int TEXT_COLUMN = 0;
// column headers
public static final String TEXT_COLUMN_HEADER = "Text";
// text area
TextFieldRenderer3 textFieldRenderer3;
* constructor
* @param variableNameArray
* @param columnNameArray
public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
this.dataArray = variableNameArray;
this.columnNameArray = columnNameArray;
defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
this.setModel(defaultTableModel) ;
// text field
textFieldRenderer3 = new TextFieldRenderer3();
MyDocumentListener myListener = new MyDocumentListener();
textFieldRenderer3.getDocument().addDocumentListener(myListener);
TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
modelColumn.setCellRenderer(textFieldRenderer3);
* nested class
class MyDocumentListener implements DocumentListener {
String newline = "\n";
public void insertUpdate(DocumentEvent e) {
System.out.println ("insert update");
updateLog(e, "inserted into");
public void removeUpdate(DocumentEvent e) {
System.out.println ("remove update");
updateLog(e, "removed from");
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
public void updateLog(DocumentEvent e, String action) {
Document doc = (Document)e.getDocument();
int changeLength = e.getLength();
textFieldRenderer3.append(
changeLength + " character" +
((changeLength == 1) ? " " : "s ") +
action + doc.getProperty("name") + "." + newline +
" Text length = " + doc.getLength() + newline);
* @param args
public static void main(String[] args) {
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception e){
e.printStackTrace();
String[] columnNameArray = {
TEXT_COLUMN_HEADER,
"1",
"2",
Object[][] dataArray = { {"", "", ""}, };
final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
final JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(panel));
frame.setTitle("My Table");
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);
class TextFieldRenderer3 extends JTextArea implements TableCellRenderer {
Icon defaultIcon;
boolean isChecked = false;
public TextFieldRenderer3() {
System.out.println ("TextFieldRenderer()");
setToolTipText("Double click to type");
@Override
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
System.out.println ("TextFieldRenderer.getTableCellRendererComponent() row/column: " + row + "\t"+ column);
return this;
}I've implemented in the cell editor. I don't see how to get the value being typed (and nothing appears in the text area)
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.Document;
public class MyTable_TextArea extends JTable {
private DefaultTableModel defaultTableModel;
private Object[][] dataArray;
private Object[] columnNameArray;
public final int TEXT_COLUMN = 0;
// column headers
public static final String TEXT_COLUMN_HEADER = "Text";
// text area
TextAreaEditor textAreaEditor;
* constructor
* @param variableNameArray
* @param columnNameArray
public MyTable_TextArea(Object[][] variableNameArray, Object[] columnNameArray) {
this.dataArray = variableNameArray;
this.columnNameArray = columnNameArray;
defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
this.setModel(defaultTableModel) ;
// text field
textAreaEditor = new TextAreaEditor();
MyDocumentListener myListener = new MyDocumentListener();
textAreaEditor.getDocument().addDocumentListener(myListener);
TableColumn modelColumn = this.getColumnModel().getColumn(TEXT_COLUMN);
modelColumn.setCellEditor(textAreaEditor);
* nested class
class MyDocumentListener implements DocumentListener {
String newline = "\n";
public void insertUpdate(DocumentEvent e) {
System.out.println ("insert update");
updateLog(e, "inserted into");
public void removeUpdate(DocumentEvent e) {
System.out.println ("remove update");
updateLog(e, "removed from");
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
public void updateLog(DocumentEvent e, String action) {
Document doc = (Document)e.getDocument();
int changeLength = e.getLength();
textAreaEditor.append(
changeLength + " character" +
((changeLength == 1) ? " " : "s ") +
action + doc.getProperty("name") + "." + newline +
" Text length = " + doc.getLength() + newline);
* @param args
public static void main(String[] args) {
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception e){
e.printStackTrace();
String[] columnNameArray = {
TEXT_COLUMN_HEADER,
"1",
"2",
Object[][] dataArray = { {"", "", ""}, };
final MyTable_TextArea panel = new MyTable_TextArea(dataArray, columnNameArray);
final JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(panel));
frame.setTitle("My Table");
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);
class TextAreaEditor extends JTextArea implements TableCellEditor {
Icon defaultIcon;
boolean isChecked = false;
public TextAreaEditor() {
System.out.println ("TextAreaEditor()");
setToolTipText("Double click to type");
@Override
public Component getTableCellEditorComponent(JTable arg0,
Object arg1,
boolean arg2,
int arg3,
int arg4) {
System.out.println ("TextAreaEditor() arg1: " + arg1 + "arg2: " + arg2 + " arg3: " + arg3 + " arg4: " + arg4 );
return null;
@Override
public void addCellEditorListener(CellEditorListener arg0) {
System.out.println ("TextAreaEditor().addCellEditorListener");
@Override
public void cancelCellEditing() {
System.out.println ("TextAreaEditor().cancelCellEditing");
@Override
public Object getCellEditorValue() {
System.out.println ("TextAreaEditor().getCellEditorValue");
return null;
@Override
public boolean isCellEditable(EventObject arg0) {
System.out.println ("TextAreaEditor().isCellEditable");
return true;
@Override
public void removeCellEditorListener(CellEditorListener arg0) {
System.out.println ("TextAreaEditor().removeCellEditorListener");
@Override
public boolean shouldSelectCell(EventObject arg0) {
System.out.println ("TextAreaEditor().shouldSelectCell");
return false;
@Override
public boolean stopCellEditing() {
System.out.println ("TextAreaEditor().stopCellEditing");
return false;
} -
Hi Experts,
My requirement is to set a checkbox upon selecting some dropdown properties in the "Basic" Tab. The checkbox that I need to set is in the "Advanced" Tab.
I got hold of the checkbox in the Advance tab from the listener and I set the value to true but it doesn't seem to be setting persistently.
Code:
var checkBox = this.findParentByType('tabpanel').find('title', 'Advanced')[0].find('name','./somecheckbox')[0];
console.log('Before' + checkBox.getValue()); // prints empty
checkBox.setValue(true);
console.log('After: ' + checkBox.getValue()); // prints true
But when I go to the Advanced tab the check box is not checked.
How do I make this persistent?
Thanks in advance.you can use myTable.addMouseListener() to add a listener to the table;
then to get the row index where the event happened you can use:
myTable.rowAtPoint(yourEvent.getPoint());
for instance:
myTable.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
//there you get the row index
int myIndex=myTable.rowAtPoint(me.getPoint());
}); -
Listener for CheckBoxes in JTable
Hi,
I have a table that displays a checkbox in one of the fields. Which event handler/ listener should I use? Eg: Checkbox listener, List listener or otherwise?
A change in the checkbox value (tick or untick) will trigger recalculation.
Thanks.I can't really understand your problem.
Here's a simple example that will print out the new check box state when you press the checkbox:
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class TableCheckboxListenerExample {
public static void main(String[] args) {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel(new Object[][] {{Boolean.FALSE, "Row 1"}, {Boolean.TRUE, "Row 2"}}, new String[] {"col1", "col2"}) {
public Class<?> getColumnClass(int columnIndex) {
if (getRowCount() > 0 && getValueAt(0, columnIndex) != null)
return getValueAt(0, columnIndex).getClass();
return super.getColumnClass(columnIndex);
model.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
Object data = model.getValueAt(row, column);
if (data instanceof Boolean)
System.out.println("Value changed in Row: " + row + " Column: " + column + " New Value = " + data);
JTable table = new JTable(model);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
catch (Exception e) {e.printStackTrace();}
} -
Way to listen for change in JTable cell?
I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
Currently, I can only get control of the application once the user has left the cell they are editing.
Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....If you want to know when the contents of a cell have been updated you should use a TableModelListener.
If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table. -
How to listen for resizing of JTable column
Is there anyway to tell when the columns in a JTable are being resized by the user? I couldn't find any listeners or anything that will tell you when the user is dragging the column width with the mouse.
Thanks.Use ColumnModelListener as shown below:-
table.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
public void columnMoved(TableColumnModelEvent e) {
public void columnRemoved(TableColumnModelEvent e) {
public void columnMarginChanged(ChangeEvent e) {
public void columnSelectionChanged(ListSelectionEvent e) {
}); -
Creating a generic selection listener for af:table
Hi,
I'm using JDeveloper 11.1.1.5.0, and I have a simple requirement to set up a custom selection listener for an af:table component.
So far, I was doing this by using a custom function to invoke the EL to perform the makeCurrent operation. However, I came across Frank Nimphius' PDF on how to build a generic selection listener, and this seemed like a better way to go about it. The problem is, the CollectionModel class used in the sample code is now deprecated. Is anyone aware of the currently supported way to implement a generic selection listener?
Thanks,
Gillthis snap shot of the code i write it to get the current employee id whcich is selected
public void select(SelectionEvent selectionEvent) {
// Add event code here...
RichTable _table = (RichTable)selectionEvent.getSource();
CollectionModel _tableModel = (CollectionModel)((RichTable)selectionEvent.getSource()).getValue();
JUCtrlHierBinding _adfTableBinding = (JUCtrlHierBinding)_tableModel.getWrappedData();
DCIteratorBinding _tableIteratorBinding = _adfTableBinding.getDCIteratorBinding();
//Acess the ADF iterator binding that is used with ADF table binding
Object _selectedRowData = _table.getSelectedRowData();
JUCtrlHierNodeBinding _nodeBinding =
(JUCtrlHierNodeBinding)_selectedRowData; //get the row key from the node binding and set it //as the current row in the iterator
Key _rwKey = _nodeBinding.getRowKey();
_tableIteratorBinding.setCurrentRowWithKey( _rwKey.toStringFormat(true));
DCIteratorBinding it = _adfTableBinding.getDCIteratorBinding();
System.out.println( it.getCurrentRow().getAttribute("EmployeeId"));
}this code i written 11.1.2 -
Multiple Buttons in JTable Headers: Listening for Mouse Clicks
I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
Here is relevant code:
public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
public MyTableHeaderRenderer() {
setOpaque(true);
// ... set colors...
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
setLayout(new FlowLayout(FlowLayout.LEADING));
setAlignmentY(Component.CENTER_ALIGNMENT);
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column){
if (table != null){
removeAll();
String valueString = (value == null) ? "" : value.toString();
add(new JLabel(valueString));
Insets zeroInsets = new Insets(0, 0, 0, 0);
final JButton sortAscendingButton = new JButton("1");
sortAscendingButton.setMargin(zeroInsets);
table.getTableHeader().addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
Rectangle buttonBounds = sortAscendingButton.getBounds();
Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
System.out.println(Revising based on (" + panelBounds.x + ", "
+ panelBounds.y + ")...");
buttonBounds.translate(panelBounds.x, panelBounds.y);
if (buttonBounds.contains(e.getX(), e.getY())){ // The click was on this button.
System.out.println("Calling sortAscending...");
((MyTableModel) table.getModel()).sortAscending(column);
else{
System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
+ sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
sortAscendingButton.setEnabled(true);
add(sortAscendingButton);
JButton button2 = new JButton("2");
button2.setMargin(zeroInsets);
add(button2);
//etc
return this;
}I found a solution to this: It's the getHeaderRect method in class JTableHeader.
table.getTableHeader().addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
Rectangle buttonBounds = sortAscendingButton.getBounds();
buttonBounds.translate(panelBounds.x, panelBounds.y);
if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){ // The click was on this button.
((MyTableModel) table.getModel()).sortAscending(column);
}); -
Mouse motion listener for JTable with JScrollpane
Hi All,
I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
Thanks in advance.
Regards,
TamizhanI am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
Is this the only way to do this? -
I need to know when a user clicks in a certain column in a JTable. This column displays checkboxes. How do i implement a listener for this and where do i put it? I've tried implementing actionlistener with an editor class, but the event never fires.
In the future, Swing related questions should be posted in the Swing forum.
You need to add a TableModelListener to the TableModel. It will notify you when the value of a cell is changed. -
Multiple selection in JTable for deletion
Dears,
I'm using Jdeveloper 9.0.3.3 on 8.1.7 Oracle DB.
I noticed that when a JTable is bound to a View object ==> only one row can be selected.
My situation -which I think is very common- I have a screen with JTable where I can edit a row and commit my updates or select multiple selection in JTable and delete them at once ; thats what I need.
It is very like the test of any application module but allow multiple selection and deletion in JTable for user's selected rows.
How this could be done in JClient?
Thankx in advance.Thanks for your suggestions! They both would work as workarounds, I think. I tried another way:
Following code changes a TableBinding bound JTable's selection model to Multi select (thanks to Shailesh!!).
void setMultiSelectionModel(JTable tbl)
class MultiSelectionListListener implements javax.swing.event.ListSelectionListener
ListSelectionModel defSelModel;
MultiSelectionListListener(ListSelectionModel model)
defSelModel = model;
public void valueChanged(javax.swing.event.ListSelectionEvent e)
if (!e.getValueIsAdjusting())
ListSelectionModel listModel = (ListSelectionModel)e.getSource();
int leadIndex = listModel.getLeadSelectionIndex();
if (leadIndex == listModel.getAnchorSelectionIndex()
&& leadIndex == listModel.getMaxSelectionIndex()
&& leadIndex == listModel.getMinSelectionIndex())
//change currency on the bound iterator only if
//one row is being selected.
defSelModel.setSelectionInterval(leadIndex, leadIndex);
ListSelectionModel newModel = new DefaultListSelectionModel();
newModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
newModel.addListSelectionListener(new MultiSelectionListListener(tbl.getSelectionModel()));
tbl.setSelectionModel(newModel);
This fixes the bug if you select some rows and then select a row before the first selected one. Seems to work great. -
SWF panel listener for changed selection
In short, my question is as follows. Is it possible to create a listener which
detects when the current selection in the Flash authoring tool has changed,
and informs my SWF panel? This does not have to be a listener per se,
it can be some hand-crafted process which consumes some reasonable amount of processor time.
I describe my question more precisely below.
Suppose that I want to create an SWF extension panel for Flash (in Flash or Flex),
and I would like the panel to display a property of the object currently selected on scene
in the Flash IDE -- like the instance name of the object (if it exists).
I can use JSFL to detect the instance name of the selected object, and pass the string to the
SWF panel using call(), for instance. The problem is that I don't know how
to detect that the user has selected the object, or that the selection has changed.
Ideally, I would like to add an event listener that listens for such an action in the flash authoring tool.
However, using JSFL, this does not seem to be possible (I can only listen to events such as frame changed
or layer changed, but not selection changed).
I tried the following solutions:
1. Periodically check in JSFL whether the current selection has changed.
The problem is that in JSFL, there is no sleep function, or anything alike. The javascript
methods setInterval and setTimeout do not work in JSFL. Therefore, in order to periodically check for changes,
one must actively loop. This is extremely resource-consuming -- in fact, it hangs the flash IDE.
2. The periodic check can be triggered by the SWF panel itself. In actionscript, I can use setInterval to periodically
invoke the selection update function via JSFL. I have set the interval to 400 milliseconds, which gives a reasonably quick
reaction to changes. However, the functionality I want to implement is in fact more complicated than just retrieving the
instance name of the selected object. As a consequence, performing this operation every 400 milliseconds still consumes
too much processor time (the flash IDE consumes 30% of my processor time, even if the user doesn't do anything).
Therefore, I still would like to find a solution which does not use the processor when the user does not do anything in the Flash IDE.I'm trying to do the same thing. Did you find a solution?
-
Hi ,
The problem is to select multiple rows and columns in the JTable like that of a excel application and have the focus on the first column of the last row. for example if select cells from ( 1,1 ) to ( 4,4), after selection the focus should be in cell (4,1). i have written a prgram( which is below) which uses listSelection to find out the cells which are selected. i found out the cells which are selected also. but i do not know how to get the focus on that cell. i have attached the code below also.. i want to know whether there is any method which set the focus to the particular cell. Can the problem above can be solved in any other way..or a simpler way..
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
class myTable {
public static void main(String a[] ) {
JFrame myframe = new JFrame();
JTable jtable = new JTable(10,10);
jtable.setCellSelectionEnabled(true);
// add the listener to the table
ListSelectionModel listSelectionModel;
OSSTableSelectionHandler obj = new OSSTableSelectionHandler(jtable,10,10);
listSelectionModel = jtable.getSelectionModel();
listSelectionModel.addListSelectionListener(obj);
myframe.getContentPane().add(jtable);
myframe.show();
} // end of public static void main
} // end of class of myTable
class OSSTableSelectionHandler implements ListSelectionListener {
JTable table;
int row;
int col;
OSSTableSelectionHandler(JTable tab, int r, int c ) {
table = tab;
row = r;
col = c;
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int i = 0,j = 0;
int firstIndex = e.getFirstIndex();
int lastIndex = e.getLastIndex();
boolean isAdjusting = e.getValueIsAdjusting();
if (lsm.isSelectionEmpty()) {
System.out.println(" Selection empty ");
} else {
// Find out which indexes are selected.
int maxrow = 0 ;
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
for ( i = minIndex; i <= maxIndex; i++) {
if (lsm.isSelectedIndex(i)) {
if ( maxrow < i )
maxrow = i;
for (j = 0;j < col ;j++ )
if ( table.isCellSelected(i,j) )
System.out.println("The selected index is " + i + " " + j);
} // end of if
} // end of for
// after this maxrow contains the last row that has beeb selected
// this for loop is to find out the first column in the maxrow that is selected
for (j = 0;j < col ;j ++ )
if ( table.isCellSelected(maxrow,j) )
break;
// set the focus to the column ( maxrow, j )
} // end of else
} // end of fucn value changed
} // end of class OSSTableSelectionHandlerWhic cell is focused depends on where you begin your selection. The cell that you press your mouse first will be the focused one. Here is how I implement the mutiple selection functionality in a JTable as what MS Excel provides. This class is independent of my any other package. your table has to have column headers and a upper left JLabel corner(int the scroll pane containing the table) in order to make this class which I named TableSelectionAdapter function properly. You can revise and imporve it as you need, however.
package petrochina.riped.gui.table.tableadapter;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.datatransfer.*;
import java.util.*;
* Enables multiple selection funtionality on <code>JTable</code>s.
* @author Guanglin Du,SEC of Riped, PetroChina,
* [email protected]
* @version 1.0 2002/09/16
public class TableSelectionAdapter extends MouseAdapter {
private String newline = "\n";
private boolean DEBUG = false;
// private boolean DEBUG = true;
private JTable myTable = null;
private boolean shiftKeyDown = false;
private boolean ctrlKeyDown = false;
private int firstSelectedColIndex = -1;
* Constructs with a <code>myTable</code> to simplify its reusability.
* Guanglin Du, 2002/09/19
* @param myTable a <code>JTable</code>
public TableSelectionAdapter(JTable myTable) {
this.myTable = myTable;
initTableSelection();
* The initTableSelection method: initializes the row/column/cell
* selection functionality of the table.
* Guanglin Du, 2002/09/19
public void initTableSelection() {
getMyTable().setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//Cell selection
myTable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myTable.setColumnSelectionAllowed(true);
myTable.setRowSelectionAllowed(true);
setMyKeyListener(); //shift/control key listener
//column selection functionality
JTableHeader myTableHeader = getMyTable().getTableHeader();
myTableHeader.addMouseListener(new TableHeaderListener());
//enalbles select-all functionality
setSelectAllFunction();
* This setSelectAllFunction isto set the select-all functionality
* when the upper left corner label of the JTable is clicked.
* Note: JTable's parent JScrollPane has to be found.
* Guanglin Du, 2002/09/19
public void setSelectAllFunction() {
Container firstParent = getMyTable().getParent();
if (firstParent instanceof JViewport) {
Container secondParent = firstParent.getParent();
if (secondParent instanceof JScrollPane) {
JScrollPane myScrollPane = (JScrollPane)secondParent;
JLabel myLabel =
(JLabel)myScrollPane.getCorner(JScrollPane.UPPER_LEFT_CORNER );
myLabel.addMouseListener(this);
* Detects shift/control key state.
* DGL, 2002/09/18
public void setMyKeyListener() {
getMyTable().addKeyListener(new KeyAdapter(){
//keyPressed
public void keyPressed(KeyEvent e){
//shift key state
if(e.isShiftDown()) shiftKeyDown = true;
//control key state
if(e.isControlDown()) ctrlKeyDown = true;
//keyReleased
public void keyReleased(KeyEvent e){
//shift key state
if( !e.isShiftDown() ) shiftKeyDown = false;
//control key state
if( !e.isControlDown() ) ctrlKeyDown = false;
* Adds the table header listener to enable single/multiple column selection.
* DGL, 2002/09/17
public void setTableHeaderListener() {
JTableHeader myTableHeader = myTable.getTableHeader();
myTableHeader.addMouseListener(new TableHeaderListener());
* Returns the <code>myTable</code> property value.
* @return myTable the table that this class handles
public JTable getMyTable() {
return myTable;
* Sets <code>myTable</code> property value of this class.
* @param myTable the table that this class handles
public void setJTable(JTable myTable) {
this.myTable = myTable;
* Returns the shiftKeyDown property value.
* @return boolean, Guanglin Du, 2002/09/18
public boolean getShiftKeyDown(){
return shiftKeyDown;
* Return the ctrlKeyDown property value.
* @return boolean, Guanglin Du, 2002/09/18
public boolean getCtrlKeyDown(){
return ctrlKeyDown;
* This inner class handles the column selection, the same
* behavior as MS Excel.
* Guanglin Du, 2002/09/18
class TableHeaderListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
stopLatestCellEditing(); //To save the data being edited
if(DEBUG) System.out.print("mousePressed on ");
JTableHeader myColumnHeader = (JTableHeader)e.getSource();
Point myPoint = e.getPoint();
int selectedColIndex = myColumnHeader.columnAtPoint(myPoint);
if(DEBUG) System.out.print("the header of column "
+ selectedColIndex+newline);
JTable table = myColumnHeader.getTable();
//The following column selection methods work only if these
//properties are set this way
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
int myRowCount = table.getRowCount();
//makes this table focused, so that setMyKeyListener method can
//listen for shift/control KeyEvent
table.requestFocus();
// System.out.println("myRowCount = " + myRowCount);
if( getShiftKeyDown() ){
table.clearSelection();
table.setRowSelectionInterval(0,myRowCount-1);
table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
if(firstSelectedColIndex > -1) {
table.addColumnSelectionInterval(firstSelectedColIndex, selectedColIndex);
firstSelectedColIndex = -1;//restore to -1
} else if( getCtrlKeyDown() ) {
table.addRowSelectionInterval(0,myRowCount-1);
table.addColumnSelectionInterval(selectedColIndex,selectedColIndex);
} else {
table.clearSelection();
table.setRowSelectionInterval(0,myRowCount-1);
table.setColumnSelectionInterval(selectedColIndex,selectedColIndex);
if(DEBUG) System.out.println("shiftKeyDown = " + shiftKeyDown
+";"+" ctrlKeyDown = " + ctrlKeyDown);
//saves the first selected column index
firstSelectedColIndex = selectedColIndex;
* MouseAdapter implemenation.
* mousePressed: sets the select-all functionality
* when upper left corner label of the table is clicked
* Guanglin Du, 2002/09/18
public void mousePressed(MouseEvent e) {
if(DEBUG) System.out.println("Select all");
stopLatestCellEditing();//To save the data in editing
getMyTable().selectAll();
* Triggers the latest <code>ActionEvent</code> in a table cell to save
* the latest data. Or, the newly input data will not be stored into the table
* model and cannot be retrieved.
public void stopLatestCellEditing() {
int editingRow = getMyTable().getEditingRow();
int editingCol = getMyTable().getEditingColumn();
if (editingRow != -1 && editingCol != -1){
TableCellEditor cellEditor =
getMyTable().getCellEditor(editingRow, editingCol);
cellEditor.stopCellEditing();
Here is how you can use it in your coding(where myTable is a JTable instance you create):
/* Adds TableSelectionAdapter to enable all kinds of selection action. */
TableSelectionAdapter tableSelect = new TableSelectionAdapter(myTable); -
Question on Selections from JTable
The code below is what I use for selection of a table row. In my table I have a colum for deleteing the time but I don't want the Listener to do anything if they check or uncheck a checkbox. I only what the listener to work when they click on a specific row and colum. Is this possible?
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel rowSM = table.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
//Ignore extra messages.
if (e.getValueIsAdjusting())
return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (lsm.isSelectionEmpty()) {
//no rows are selected
} else {
int selectedRow = lsm.getMinSelectionIndex();
//selectedRow is selected
});I only what the listener to work when they click on a specific row and colum. Is this possible?You can override JTable's editCellAt method as shown below:
JTable myTable=new JTable() {
public boolean editCellAt(int row, int col, EventObject e) {
if (e instanceof MouseEvent) {
if (row==? && col==?) { // replace ? with the specific row and column
// do whatever you want here
return super.editCellAt(row,col,e);
};;o)
V.V. -
Table event listener for both columns and rows
My table listener only gives me the printed values when I click on different rows and not when I click on different columns. Do I need 2 listeners (one inside the other one) to get a change recorded each time I click on a cell in the table? Here is the listener code:
ListSelectionModel rowSM1 = jTable1.getSelectionModel();
rowSM1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
System.out.println("I am here");
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (e.getValueIsAdjusting()) {
return;
if (lsm.isSelectionEmpty()) {
//no rows are selected
else {
selectedSiteRow = new Integer(lsm.getMinSelectionIndex() + 1).toString();
System.out.println("selectedSiteRow = " + selectedSiteRow);
SetupNum = selectedSiteRow; // row that the user selected
ObjectNum = "1";
objnum = "1";
dataModels.remove("O"); // remove the object tables from the dataModels hashtable
dataModels.remove("P"); // remove the object tables from the dataModels hashtable
for (int i = 0; i < wholefile.size(); i++) {
setupnum = selectedSiteRow;
if (wholefile.elementAt(i).toString().charAt(0) == 'O') {
processLine(wholefile.elementAt(i).toString(), columnNamesO);
String keyO = "O";
DefaultTableModel modelO = (DefaultTableModel)dataModels.get(keyO);
jTable2.setModel(modelO); // change the table to the new table model
if (wholefile.elementAt(i).toString().charAt(0) == 'P') {
processLine(wholefile.elementAt(i).toString(), columnNamesP);
String keyP = "P";
DefaultTableModel modelP = (DefaultTableModel)dataModels.get(keyP);
jTable3.setModel(modelP); // change the table to the new table model
);The words "I am here" only appear when I click on rows and not when I click on columns of that same row. Anyone know why?
Also, each time I click on a row, "I am here" appears 2 times. I know I read that someone else had that problem. I will try to find the solution to that one in the forum.
Thanks.
AllysonI found out how to get the column, but I can't seem to get them together. Here is the listener for the column:
ListSelectionModel colSM1 = jTable1.getColumnModel().getSelectionModel();
colSM1.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if (lsm.isSelectionEmpty()) {
//no columns are selected
else {
SelectedC = lsm.getMinSelectionIndex();
});These are 2 different listeners and I really want to find out what row,column has changed. Is there any way to combine these somehow? Thanks.
Allyson
Maybe you are looking for
-
I just bought a new Retina Display macbook pro, and I plugged in my iPod touch (4th gen) into the new computer, but it will not show up, even after I typed in the passcode. How do I get my iTouch to sync with my new computer without restoring my itou
-
Install Logic Studio in Macbook pro 17"
Hi, I have a mac pro ( I installed in mac pro without problems) and I have Macbook pro with problems. When install the jampack 3 Stop the install and the message say put the next disk ( logic install) but the jamplack 3 is in the computer. And I push
-
Remoting Connection Issue: Channel.Connect.Failed
Solution: Turns out my client had installed a new firewall/web management system without telling me. My app was being blocked. :( Hi there, I have a Flex app using remoting and ColdFusion. My client has suddenly experienced the following error: Chann
-
New to Firefox...about bookmark management
-
IOS software was froze when the electricity went off and it was disconnected from the wifi