I am having problems with fixing something in my program. Basically I know how to use action Listeners but there is no option to add one to a JTable
. How is this done?
Basically I want to add an action Listener to my table so that every time a value is changed it will update that field in my data base.
IE
JTable.addActionListener (new ActionListener) {
// text is changed
updateDataBase();
};
You should add a listener to the TableModel
:
yourtableObject.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// your code goes here, whatever you want to do when something changes in the table
}
});
TableModelEvent
contains row and column number and type of modification.
TableModelEvent
is used to notify listeners that a table model has changed.
Start by taking a look at How to Use Tables
What you will want to do is register a TableModelListener
with the JTable
's model and monitor for changes there
You may also find How to Write a Table Model Listener of some use
The kind of thing you are look for is
TableModel#getType
equals TableModelEvent.UPDATE
TableModel#getFirstRow
and TableModel#getLastRow
are typically equals (singularly that a single row was update), this may or may not be relevant, that's up to you to decide TableModel#getColumn
is not equal to TableModelEvent.ALL_COLUMNS
, this signifies that a single cell was updated. Again, this may or may not be important, but if the cell was edited by the user, this will be set Take a look at javax.swing.event.TableModelEvent
for more details
If you want to have an event when there is a change in selection you can use:
table.getSelectionModel()addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent l) {
//action
}
});
Source: http://www.java2s.com/Tutorial/Java/0240__Swing/TableSelectionEventsandListeners.htm
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.