Deleting multiple rows freeze JTable - java

I am trying to delete multiple rows (per example, five of fifty) in a Jtable, but I can only delete one at time (I am using multiple interval selection before you ask!), and I feel the Jtable freeze a bit. My delete button:
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e){
SwingUtilities.invokeLater(new Runnable() {
public void run(){
int[] selectedRow = jTable.getSelectedRows();
for(int j=0; j<selectedRow.length; j++){
Boolean state= (Boolean)jTable.getValueAt(selectedRow[j],10);
if(state==true){//deleta the row
User u=model.getUsers(selectedRow[j]);
new UserDao().delete(u);
model.remove(selectedRow[j]);
numberField.setText(String.valueOf(model.getRowCount()));
}
}
}
});
}
});
My remove:
public void remove(int row) {
this.userlist.remove(row);
this.fireTableDataChanged();
}
What I am doing wrong?

Let's take a closer look at the code...
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e){
// Don't know why you need to use invokeLater
// The event should be trigged within the EDT if the user
// clicked the button. This may introduce a small "pause"
// depending on what else is in the EDT...
SwingUtilities.invokeLater(new Runnable() {
public void run(){
// Get the indices of the selected rows...okay
int[] selectedRow = jTable.getSelectedRows();
// Loop through the selected rows...good...
for(int j=0; j<selectedRow.length; j++){
// Get the "state" of the row...okay
Boolean state= (Boolean)jTable.getValueAt(selectedRow[j],10);
// Long winded if, but okay...
if(state==true){//deleta the row
// Don't know what's going on here,
// But I assume you are trying to delete
// something from some kind of database
// THIS is likely to chew up some time...
User u=model.getUsers(selectedRow[j]);
new UserDao().delete(u);
// Uh oh...
// If you remove a row from the model, the list of indices you
// have is now invalid, as they no longer point
// to the correct rows in the model
model.remove(selectedRow[j]);
numberField.setText(String.valueOf(model.getRowCount()));
}
}
}
});
}
});
So. Two problems.
You seem to be calling some kind of management functionality within the context of the EDT, functionality that "looks" like it's going to cause the EDT to be slowed/paused for even a small amount of time...
You are relying on out of date information...
A better solution would be to use some kind of background process to perform the deleting of the User and provide a means within the model to look up the User object itself and remove it from the model. This removes the possibility of the indices being changed under you.
A SwingWorker provides a means by which we can perform operations in the background, off the Event Dispatching Thread, while provide means to re-sync required actions (like modifying the table model) back onto the EDT when required...
For example...
public class DeleteUsersWorker extends SwingWorker<List<User>, User> {
private UserTableModel model;
private List<User> users;
public DeleteUsersWorker(UserTableModel model, List<User> users) {
this.model = model;
this.users = users;
}
protected List<User> doInBackground() {
UserDao dao = new UserDao();
for (User user : users) {
dao.delete(user);
publish(user);
}
return users;
}
protected void process(List<User> users) {
for (User user : users) {
model.remove(user);
}
}
}
And the contents of the actionPerformed method...
int[] selectedRow = jTable.getSelectedRows();
List<User> usersToBeRemoved = new ArrayList<>(selectedRow.length);
for(int row : selectedRow){
// Is state part of the User object??
Boolean state = (Boolean)jTable.getValueAt(row,10);
if(state){
usersToBeRemoved.add(model.getUsers(row));
}
}
DeleteUsersWorker worker = new DeleteUsersWorker(model, users);
worker.execute();
This will probably require to add some additional functionality to the table model to support removing the User object from the model, but I don't have your model, so it's difficult to make suggestions...
Take a look at Concurrency in Swing for more details...
A better solution might be to have a listener on your dao API that could provide notifications about updates, this way the model could update itself, but again, not enough context to make a determination ;)
Updated with comments form TrashGod
You should also beware that the view indices don't always map directly to the model indices. This happens when the table is sorted or filtered. While you might argue that your table isn't (sorted or filtered) it is good practice never to make such assumptions...
When taking a row index from the table, you should call JTable#convertRowIndexToModel(int) which will return you the index point in the model
Take a look at Sorting and Filtering for more details...
Update with runnable example
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class TableDeleteRowsTest {
public static void main(String[] args) {
new TableDeleteRowsTest();
}
public TableDeleteRowsTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final UserTableModel model = new UserTableModel(
new User("Kermit"),
new User("Fozzie"),
new User("Animal"),
new User("Miss Piggy"),
new User("Gonzo"),
new User("Beaker"),
new User("Crazy Harry"),
new User("Floyd Pepper"),
new User("Sweetums"));
final JTable table = new JTable(model);
JButton delete = new JButton("Delete");
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int[] selectedRows = table.getSelectedRows();
if (selectedRows.length > 0) {
List<User> users = new ArrayList<>(selectedRows.length);
for (int row : selectedRows) {
int modelRow = table.convertRowIndexToModel(row);
Boolean selected = (Boolean) model.getValueAt(modelRow, 1);
if (selected) {
users.add(model.getUser(modelRow));
}
}
if (users.size() > 0) {
new DeleteUserWorker(users, model).execute();
}
}
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.add(delete, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DeleteUserWorker extends SwingWorker<List<User>, User> {
private List<User> users;
private UserTableModel model;
public DeleteUserWorker(List<User> users, UserTableModel model) {
this.users = users;
this.model = model;
}
#Override
protected void process(List<User> chunks) {
for (User user : users) {
model.remove(user);
}
}
#Override
protected List<User> doInBackground() throws Exception {
for (User user : users) {
// Simulated delay
Thread.sleep(250);
publish(user);
}
return users;
}
}
public class UserTableModel extends AbstractTableModel {
private List<User> users;
private List<Boolean> selected;
public UserTableModel(User... users) {
this.users = new ArrayList<>(Arrays.asList(users));
selected = new ArrayList<>(this.users.size());
for (User user : this.users) {
selected.add(new Boolean(false));
}
}
public User getUser(int row) {
return users.get(row);
}
#Override
public int getRowCount() {
return users.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public String getColumnName(int column) {
String name = "?";
switch (column) {
case 0:
name = "User";
break;
case 1:
name = "";
break;
}
return name;
}
#Override
public Class getColumnClass(int column) {
Class type = String.class;
switch (column) {
case 0:
type = String.class;
break;
case 1:
type = Boolean.class;
break;
}
return type;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
switch (columnIndex) {
case 0:
value = users.get(rowIndex).getName();
break;
case 1:
value = selected.get(rowIndex);
break;
}
return value;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
switch (columnIndex) {
case 1:
if (aValue instanceof Boolean) {
selected.set(rowIndex, (Boolean) aValue);
fireTableCellUpdated(rowIndex, columnIndex);
}
break;
}
}
public void remove(User user) {
int index = users.indexOf(user);
if (index >= 0) {
selected.remove(index);
users.remove(user);
fireTableRowsDeleted(index, index);
}
}
}
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
Updated with additional example
The above example will only delete the rows that are marked AND selected. To delete all the marked rows, you will need something more like...
JButton delete = new JButton("Delete");
delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
List<User> users = new ArrayList<>(selectedRows.length);
for (int row = 0; row < table.getRowCount(); row++) {
int modelRow = table.convertRowIndexToModel(row);
Boolean selected = (Boolean) model.getValueAt(modelRow, 1);
if (selected) {
users.add(model.getUser(modelRow));
}
}
if (users.size() > 0) {
new DeleteUserWorker(users, model).execute();
}
}
});

Related

How do you disallow Drag and Drop between two JTables?

I have two JTables, and they are set up so that you can drag and drop the rows within each JTable. The problem is that it lets me drag a row from one JTable to the other JTable, and I am trying to figure out how to stop that. I only want the user to be able to drag and drop a row within that same JTable.
In other words, when I drag a row outside the current table and hover the mouse over the empty panel space, the mouse cursor displays a circle with a diagonal line through it, which is what I want. However, when I drag the mouse over the other table, it displays the small rectangular "drop" icon, which is what I am trying to block. When the user tries to drag this row on top of other table, I would like the small circle with diagonal line to appear.
This is a working example that demonstrates the problem:
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DragSource;
import java.util.ArrayList;
import java.util.List;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataHandler;
import javax.swing.DropMode;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.table.AbstractTableModel;
public class JTableDnD extends JFrame
{
private JTable tableA;
private JTable tableB;
public JTableDnD()
{
// *** Create First Table ***
List<Object[]> dataA = new ArrayList<Object[]>();
dataA.add(new Object[] {"A1", "A1"});
dataA.add(new Object[] {"A2", "A2"});
dataA.add(new Object[] {"A3", "A3"});
List<String> columnsA = new ArrayList<String>();
columnsA.add("Column 1");
columnsA.add("Column 2");
tableA = new JTable(new TableModel(columnsA, dataA));
tableA.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableA.setDragEnabled(true);
tableA.setDropMode(DropMode.INSERT_ROWS);
tableA.setFillsViewportHeight(true);
tableA.setTransferHandler(new TableTransferHandler(tableA));
JScrollPane scrollPaneA = new JScrollPane(tableA);
// *** Create Second Table ***
List<Object[]> dataB = new ArrayList<Object[]>();
dataB.add(new Object[] {"B1", "B1"});
dataB.add(new Object[] {"B2", "B2"});
dataB.add(new Object[] {"B3", "B3"});
List<String> columnsB = new ArrayList<String>();
columnsB.add("Column 1");
columnsB.add("Column 2");
tableB = new JTable(new TableModel(columnsB, dataB));
tableB.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableB.setDragEnabled(true);
tableB.setDropMode(DropMode.INSERT_ROWS);
tableB.setFillsViewportHeight(true);
tableB.setTransferHandler(new TableTransferHandler(tableB));
JScrollPane scrollPaneB = new JScrollPane(tableB);
// *** Add ScrollPanes to Panel ***
this.getContentPane().setLayout(new FlowLayout());
add(scrollPaneA);
JPanel emptyPanel = new JPanel();
emptyPanel.setPreferredSize(new Dimension(100, 200));
add(emptyPanel);
add(scrollPaneB);
} // end JTableDnD constructor
private static void createAndShowGUI()
{
JFrame frame = new JTableDnD();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
interface Reorderable
{
public void reorder(int from, int to);
}
class TableModel extends AbstractTableModel implements Reorderable
{
private List<String> columnNames;
private List<Object[]> data;
public TableModel(List<String> columnNames, List<Object[]> data)
{
super();
this.columnNames = columnNames;
this.data = data;
}
#Override
public void reorder(int from, int to)
{
if (from < to)
{
to--;
}
Object[] row = data.remove(from);
data.add(to, row);
fireTableDataChanged();
}
#Override
public int getRowCount()
{
return data.size();
}
#Override
public int getColumnCount()
{
return columnNames.size();
}
#Override
public String getColumnName(int column)
{
return columnNames.get(column);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
return data.get(rowIndex)[columnIndex];
}
} // end TableModel
class TableTransferHandler extends TransferHandler
{
private final DataFlavor localObjectFlavor = new ActivationDataFlavor(Integer.class, DataFlavor.javaJVMLocalObjectMimeType, "Integer Row Index");
private JTable table = null;
public TableTransferHandler(JTable table)
{
this.table = table;
}
#Override
protected Transferable createTransferable(JComponent component)
{
return new DataHandler(new Integer(table.getSelectedRow()), localObjectFlavor.getMimeType());
}
#Override
public boolean canImport(TransferHandler.TransferSupport support)
{
boolean b = support.getComponent() == table &&
support.isDrop() &&
support.isDataFlavorSupported(localObjectFlavor);
table.setCursor(b ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
return b;
}
#Override
public int getSourceActions(JComponent component)
{
return TransferHandler.COPY_OR_MOVE;
}
#Override
public boolean importData(TransferHandler.TransferSupport support)
{
JTable target = (JTable) support.getComponent();
JTable.DropLocation dropLocation = (JTable.DropLocation) support.getDropLocation();
int index = dropLocation.getRow();
int max = table.getModel().getRowCount();
if (index < 0 || index > max)
{
index = max;
}
target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
try
{
Integer rowFrom = (Integer) support.getTransferable().getTransferData(localObjectFlavor);
if (rowFrom != -1 && rowFrom != index)
{
((Reorderable) table.getModel()).reorder(rowFrom, index);
if (index > rowFrom)
{
index--;
}
target.getSelectionModel().addSelectionInterval(index, index);
return true;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
#Override
protected void exportDone(JComponent component, Transferable transferable, int action)
{
if (action == TransferHandler.MOVE)
{
table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
} // end TableTransferHandler
I believe I need to add some extra logic to the canImport() method to make sure that the row that is being dropped is from that same table, but I can't seem to figure it out. I've tried inspecting the data inside the TransferSupport object that gets passed into canImport(), but it does not seem to have any function that returns the exact JTable object source.
In the simplified Swing DnD, there is no support for getting at the source of the transferable. The component returned by TransferSupport` is the target of the drop, that is the component that somehow should handle the associated transferable. So if you have a per-component TransferHandler configured with a particular table, the support's component will always be that same table instance and your check will be true trivially.
If you want to enable/disable dropping based on the sender, you'll have to provide it on a per-drag basis: a drag starts in exportAsDrag and ends in exportDone, so you can set/null the sender in those.
#Override
protected void exportDone(JComponent component,
Transferable transferable, int action) {
table = null;
}
#Override
public void exportAsDrag(JComponent comp, InputEvent e, int action) {
table = (JTable) comp;
super.exportAsDrag(comp, e, action);
}
Now you can re-use the same instance of the handler across several instances of table:
TableTransferHandler handler = new TableTransferHandler();
tableA.setTransferHandler(handler);
tableB.setTransferHandler(handler);
As an aside: I wouldn't fiddle with the cursors, they are supporsed to be under complete control of the dnd subsystem.

How to refresh data in JTable I am using TableModel

Hi,
I have created my TableModel and want to refresh JTable once I added a new row. What should be added to the listener to "refresh" JTable?
public class MyTableModel implements TableModel {
private Set<TableModelListener> listeners = new HashSet<TableModelListener>();
//List<Staff> staffs = Factory.getInstance().getStaffDAO().getAllStaff();
private List<Staff> staffs;
public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}
#Override
public int getRowCount() {
return staffs.size();
}
#Override
public int getColumnCount() {
return 5;
}
#Override
public String getColumnName(int columnIndex) {
switch (columnIndex){
case 0:
return "First Name";
case 1:
return "Second Name";
case 2:
return "Date";
case 3:
return "Position";
case 4:
return "Salary";
}
return "";
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return Object.class;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
}
Here is my listener of my Add row Button:
#Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
!!!Here should be some code that will be firing my table after adding new row!!!
}
I've tried to use method firetabledatachanged() of AbstractTableModel in my actionPerformed() but with unluck, it is appeared ClassCastException.
UPDATE 1
WorkPlaceGui.java
public class WorkPlaceGui extends JFrame implements ActionListener {
AbstractTableModel model;
JTable jTable;
JScrollPane jScrollPane;
public WorkPlaceGui()throws SQLException{
List<Staff> staffs = Factory.getInstance().getStaffDAO().getAllStaff();
for(int i = 0; i < 0; i++) {
staffs.add(new Staff("First Name " + staffs.get(i).getName(), "Second Name " + staffs.get(i).getSurname(), "Date " + staffs.get(i).getDate(), "Position " + staffs.get(i).getPosition(), "Salary " + staffs.get(i).getSalary()));
}
model = new MyTableModel(staffs);
jTable = new JTable(model);
JButton jBtnAdd = new JButton("Добавить");
JButton jBtnDel = new JButton("Удалить");
JButton jBtnUpd = new JButton("Обновить");
JButton jBtnAdmin = new JButton("Админка");
JPanel panelNorth = new JPanel();
JPanel panelCenter = new JPanel();
JPanel panelSouth = new JPanel();
jTable.setPreferredScrollableViewportSize(new Dimension(350, 150));
jScrollPane = new JScrollPane(jTable);
panelNorth.setLayout(new FlowLayout());
panelNorth.add(jBtnAdd);
panelNorth.add(jBtnDel);
panelNorth.add(jBtnUpd);
panelNorth.add(jBtnAdmin);
panelCenter.add(jScrollPane);
setLayout(new BorderLayout());
add(panelNorth, BorderLayout.NORTH);
add(panelCenter, BorderLayout.CENTER);
jBtnAdd.addActionListener(this);
setPreferredSize(new Dimension(550, 300));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Staff data base");
pack();
setVisible(true);
setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
model.fireTableDataChanged();
}
}
MyTableModel.java
public class MyTableModel extends AbstractTableModel {
private List<Staff> staffs;
public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}
#Override
public int getRowCount() {
return staffs.size();
}
#Override
public int getColumnCount() {
return 5;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
}
You've done it the hard way.
First of all, you've implemented directly from TableModel and secondly you've failed to implement the listener requirements...
Instead, try extending from the AbstractTableModel instead, which already includes the implementations of the listener registration and notification.
You will need to provide a method that will allow you to add a row to the table model. In this method you need to use the fireTableRowsInserted method which will notify any tables using the model, that a new row has been added...
Update with example
This is VERY, VERY basic example. It's only intention is to demonstrate the use of fireTableRowsInserted. It uses a Swing Timer to add a new row every 125 milliseconds until you kill it ;)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class DynamicTable {
public static void main(String[] args) {
new DynamicTable();
}
public DynamicTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final MyTableModel model = new MyTableModel();
JTable table = new JTable(model);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(125, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow();
}
});
timer.start();
}
});
}
public class MyTableModel extends AbstractTableModel {
private List<String[]> rows;
public MyTableModel() {
rows = new ArrayList<>(25);
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
String[] row = rows.get(rowIndex);
return row[columnIndex];
}
public void addRow() {
int rowCount = getRowCount();
String[] row = new String[getColumnCount()];
for (int index = 0; index < getColumnCount(); index++) {
row[index] = rowCount + "x" + index;
}
rows.add(row);
fireTableRowsInserted(rowCount, rowCount);
}
}
}
Updated with another example
Because your table model is backed by its own List, it has no connection to your factory. It doesn't know when you add or remove objects from it. This means you become responsible for updating the model:
public class MyTableModel extends AbstractTableModel {
private List<Staff> staffs;
public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}
#Override
public int getRowCount() {
return staffs.size();
}
#Override
public int getColumnCount() {
return 5;
}
public void add(Staff staff) {
int size = getSize();
staffs.add(staff);
fireTableRowsInserted(size, size);
}
public void remove(Staff staff) {
if (staffs.contains(staff) {
int index = stafff.indexOf(staff);
staffs.remove(staff);
fireTableRowsDeleted(index, index);
}
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
}
And your actionPerformed:
#Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
((MyTableModel)model).add(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
Your class MyTableModel implements TableModel, but it has no event handling mechanism to connect the model to the view. Instead extend AbstractTableModel, as shown here and here. AbstractTableModel provides the fireTable* methods needed for this.
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
Well, first of all, find more about Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern).
I suggest that you create a ObservableModel class that will have a list of PropertyChangeListeners. Your StaffDAO should extend this ObservableModel. When the new staff is added (i.e. addStaff is called) you should call ObservableModel's firePorpertyChange or something like that. firePropertyChange notifyies all propertyChangeListeners. One of those listeners should be registered in your Table, and its propertyChanged method should be implemented with refreshing of the table (hd1) had a good answer.
myTableModel.fireTableDataChanged(); should be just enough to force a refresh of your table. As usual, if you have further problems, do feel free to leave a comment.
For a more general solution you can use the Row Table Model and just implement the getValueAt() and setValueAt() methods.
Here should be some code that will be firing my table after adding new row!
The model is responsible for invoking the proper fireXXX method.
Use this type of casting.
((AbstractTableModel)student.getModel()).fireTableCellUpdated();

Swing GUI: JList with jtextFields on the rows

My problem is:
I have a button that will add components to a JList when it is clicked. Each row of the list is composed by two jtextFields. The first is the ID of the row. Every time I press the "Add button", a new row appears, the ID is incremented, and the person who is using the application will write whatever he want on the second jTextField (forward the ID field).
Then it will have a scroll pane for when there are more than 4 rows.
And I want a Remove Button too. To be possible to remove some rows.
Can you help me with this? I don't know how to create a list like this...
Thanks!
Simply use JTable with two columns. This will allow you to establish two columns, one for the ID and one for the value. This will allow you make the second column editable.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class TestTable04 {
public static void main(String[] args) {
new TestTable04();
}
private int id = 0;
public TestTable04() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final RecordTableModel model = new RecordTableModel();
JTable table = new JTable(model);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.add(new Record(++id));
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(add, BorderLayout.SOUTH);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Record {
private int id;
private String value;
public Record(int id) {
this.id = id;
}
public int getID() {
return id;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class RecordTableModel extends AbstractTableModel {
private List<Record> lstRecords;
public RecordTableModel() {
lstRecords = new ArrayList<>(24);
}
public void add(Record record) {
lstRecords.add(record);
fireTableRowsInserted(lstRecords.size() - 1, lstRecords.size() - 1);
}
public void remove(Record record) {
if (lstRecords.contains(record)) {
int index = lstRecords.indexOf(record);
remove(index);
}
}
public void remove(int index) {
lstRecords.remove(index);
fireTableRowsDeleted(index, index);
}
#Override
public int getRowCount() {
return lstRecords.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = Integer.class;
break;
}
return clazz;
}
#Override
public String getColumnName(int column) {
String name = null;
switch (column) {
case 0:
name = "ID";
break;
case 1:
name = "Value";
break;
}
return name;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Record record = lstRecords.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = record.getID();
break;
case 1:
value = record.getValue();
break;
}
return value;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Record record = lstRecords.get(rowIndex);
switch (columnIndex) {
case 1:
record.setValue(aValue == null ? null : aValue.toString());
fireTableCellUpdated(rowIndex, columnIndex);
break;
}
}
}
}
Check out How to use tables for more details
You can try creating a custom ListCellRenderer and use JList's setRenderer method to assign it. Override the getListCellRenderer() method of ListCellRenderer to return a JPanel containing two components, a JLabel for the id, and a JTextfield for the user input. You may need to keep a reference to the JTextField elsewhere so that you can retrieve the user input.
To implement the add and remove methods, I would recommend backing the JList with a ListModel. Add and remove to the ListModel will also update the JList UI.

java: Get row data from popupmenu actionListener event

I'm having a little scenario here that maybe a duplicate. I have JTable where i show some data, i have a mouselistener that listens for right clicks on the table and displays a popup menu with one menuitem. My goal is that when the user clicks the menuitem, i get the values from the table and feed them into a custom dialog which has some fill in fields, so that the user doesn't have to feed the whole dialog by hand since i will feed the dialog with the values selected on the table. but my problem is that the menuitem actionevent doesn't have a way of getting the point so that i can use table.getRowAt(). i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable that can then be accessed by the actionlistener for the menuitem.
i want it to look like this
theScrollPane.getViewport().add(myJTable, null);
JMenuItem menuItem = new JMenuItem(clickMe);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuItemActionPerformed(e);
}
});
MouseListener popupListener = new PopupListener();
popupMenu.add(menuItem);
myJTable.addMouseListener(popupListener);
protected void menuItemActionPerformed (ActionEvent e) {
// what to do here to get the table row data
// and send it to my custom dialog via it's constructor ???
}
// a simple nested class for the popup
class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
int row = myJTable.rowAtPoint(e.getPoint());
int selectedRow = myJTable.getSelectedRow();
// just to make sure the popup appears only where the row is
// selected
if (row == selectedRow) {
showPopup(e);
}
}
public void mouseReleased(MouseEvent e) {
int row = myJTable.rowAtPoint(e.getPoint());
int selectedRow = myJTable.getSelectedRow();
if (row == selectedRow) {
showPopup(e);
}
}
private void showPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
so my question is, is saving the row number the only way that i can do this or is there a better way?
i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable
You read the wrong comment.
If you read the answer above that link (ie. the one with 7 votes) you will see the solution is to select the row you clicked on BEFORE showing the popup menu. Then in your menu item Action you can reference
table.getSelectedRow();
I have tried your case referring to this case and I am able to get the row and show it in a JDialog. I just modified my old code to do this. I haven't thoroughly tested.
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class AllTableExample {
private JTabbedPane tabbedPane;
private JTable allTable;
private AllTableModel allTableModel;
public AllTableExample() {
List<TableData> data = new ArrayList<TableData>();
data.add(new TableData("John1", "A", "Maths", "Hellen1"));
data.add(new TableData("John2", "A", "Maths", "Hellen2"));
data.add(new TableData("John3", "A", "Maths", "Hellen3"));
data.add(new TableData("John4", "A", "Maths", "Hellen4"));
data.add(new TableData("John5", "A", "Maths", "Hellen5"));
allTableModel = new AllTableModel(data);
}
public void createUI() {
JFrame frame = new JFrame();
tabbedPane = new JTabbedPane();
tabbedPane.add("All", getAllTablePanel());
frame.add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Table Model Example.");
frame.pack();
frame.setVisible(true);
}
private JPanel getAllTablePanel() {
JPanel panel = new JPanel();
allTable = new JTable(allTableModel);
JScrollPane scroll = new JScrollPane(allTable);
panel.add(scroll);
allTable.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
int r = allTable.rowAtPoint(e.getPoint());
if (r >= 0 && r < allTable.getRowCount()) {
allTable.setRowSelectionInterval(r, r);
} else {
allTable.clearSelection();
}
int rowindex = allTable.getSelectedRow();
if (rowindex < 0)
return;
if (e.getComponent() instanceof JTable) {
JDialog dialog = new JDialog();
int selectedRow = allTable.getSelectedRow();
dialog.setTitle("Edit Row: " + selectedRow);
TableData data = ((AllTableModel) allTable.getModel()).getTableData().get(selectedRow);
List<TableData> tempData = new ArrayList<TableData>();
tempData.add(data);
AllTableModel tempModel = new AllTableModel(tempData);
JTable table = new JTable(tempModel);
dialog.add(new JScrollPane(table));
dialog.setVisible(true);
}
}
});
return panel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new AllTableExample().createUI();
}
};
EventQueue.invokeLater(r);
}
}
class AllTableModel extends AbstractTableModel {
List<TableData> tableData = new ArrayList<TableData>();
Object[] columnNames = {"Name", "Grade", "Subject", "Staff"};
public AllTableModel(List<TableData> data) {
tableData = data;
}
public List<TableData> getTableData() {
return tableData;
}
#Override
public String getColumnName(int column) {
return columnNames[column].toString();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return tableData.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
TableData data = tableData.get(rowIndex);
switch (columnIndex) {
case 0:
return data.getName();
case 1:
return data.getGrade();
case 2:
return data.getSubject();
case 3:
return data.getStaff();
default:
return null;
}
}
}
class TableData {
private String name;
private String grade;
private String subject;
private String staff;
public TableData(String name, String grade, String subject, String staff) {
super();
this.name = name;
this.grade = grade;
this.subject = subject;
this.staff = staff;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getStaff() {
return staff;
}
public void setStaff(String staff) {
this.staff = staff;
}
}
Note: Store the row number of the table on which the pop-up opened such that after the changes in the popup dialog we have to update the original row.

Radio button in JTable not working properly

I have a problem with the following code. My task is, I have to have radio buttons in the first column and when a user selects that radio button that row is selected and sent for processing. But my problem is, I am able to select the radio button which are in the first column, but afterwards when user clicks in any part of the table then my clicked radio button is being unchecked. I am not able to figure, why it is happeneing. I am really stuck with this problem. Help required. The following code shows my problem.
import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class DisplayTable extends JDialog {
public void initialize() {
SourceTableModel stm = new SourceTableModel();
JTable sourceTable = new JTable(stm);
sourceTable.getColumnModel().getColumn(0).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(0).setCellEditor(new RadioButtonEditor(new JCheckBox ()));
JPanel panel = new JPanel();
panel.add(new JScrollPane(sourceTable));
add(panel);
setModal(true);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisplayTable().initialize();
}
});
}
}
class SourceTableModel extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private List<SourceModel> sourceList = new ArrayList<SourceModel>();
private String[] columnNamesList = {"Select", "Group", "Work"};
public SourceTableModel() {
this.sourceList = getSourceDOList();
}
public String getColumnName(int column) {
return columnNamesList[column];
}
public int getRowCount() {
return sourceList.size();
}
public int getColumnCount() {
return columnNamesList.length;
}
public Class<?> getColumnClass(int columnIndex) {
return (columnIndex == 0 ? Boolean.class : String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return (columnIndex == 0 ? true : false);
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
SourceModel model = (SourceModel) sourceList.get(rowIndex);
switch (columnIndex) {
case 0:
model.setSelect((Boolean)aValue);
break;
case 1:
model.setFactory((String) aValue);
break;
case 2:
model.setSupplier((String) aValue);
break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
SourceModel source = sourceList.get(rowIndex);
switch(columnIndex){
case 0:
return source.isSelect();
case 1:
return source.getFactory();
case 2:
return source.getSupplier();
default:
return null;
}
}
private List<SourceModel> getSourceDOList() {
List<SourceModel> tempSourceList=new ArrayList<SourceModel>();
for (int index = 0; index < 5; index++) {
SourceModel source = new SourceModel();
source.setSelect(false);
source.setFactory("group");
source.setSupplier("Work");
tempSourceList.add(source);
}
return tempSourceList;
}
}
class SourceModel {
private boolean select;
private String factory;
private String supplier;
public SourceModel() {
// No Code;
}
public SourceModel(boolean select, String factory, String supplier) {
super();
this.select = select;
this.factory = factory;
this.supplier = supplier;
}
public boolean isSelect() {
return select;
}
public void setSelect(boolean select) {
this.select = select;
}
public String getFactory() {
return factory;
}
public void setFactory(String factory) {
this.factory = factory;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
}
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
public JRadioButton btn = new JRadioButton();
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
}
public Component getTableCellEditorComponent(JTable table, Object
value, boolean isSelected, int row, int column) {
if (value==null)
return null;
btn.addItemListener(this);
if (( (Boolean) value).booleanValue())
btn.setSelected(true);
else
btn.setSelected(false);
return btn;
}
public Object getCellEditorValue() {
if(btn.isSelected() == true)
return new Boolean(true);
else
return new Boolean(false);
}
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}
class RadioButtonRenderer implements TableCellRenderer {
public JRadioButton btn = new JRadioButton();
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value==null) return null;
if(((Boolean)value).booleanValue())
btn.setSelected(true);
else
btn.setSelected(false);
if (isSelected) {
btn.setForeground(table.getSelectionForeground());
btn.setBackground(table.getSelectionBackground());
} else {
btn.setForeground(table.getForeground());
btn.setBackground(table.getBackground());
}
return btn;
}
}
EDIT:
I have updated my code and I have used Boolean class for the first column. The problem which I am facing is, if I remove super.fireEditingStopped(); from RadioButtonEditor class then I am able to check and then if I click at any part of the table then checked one I being unchecked. If I keep the super.fireEditingStopped(); then I am not even able to check the Radio button.
I know that super.fireEditingStopped(); will stop editing. But my question is how to check it?
P.S: Sorry I have posted my entire code. I thought it will be easy for some one to look at the problem.
This is the screen shot of the program.
From your illustration, it appears that you want to enforce mutual exclusion among the rows of a JTable, where each row has a single JRadioButton. As a ButtonGroup is unsuitable, this example due to #Guillaume Polet uses a custom manager.
I have a problem with the following code. My task is, I have to have
radio buttons in the first column and when a user selects that radio
button that row is selected and sent for processing. But my problem
is, I am able to select the radio button which are in the first
column, but afterwards when user clicks in any part of the table then
my clicked radio button is being unchecked. I am not able to figure,
why it is happeneing. I am really stuck with this problem. Help
required. The following code shows my problem.
don't to use JRadioButton, use built_in support for Boolean value in JTable == JCheckBox,
then you can sorting and filtering based on Boolean value
otherwise you have to override to String ("true" / "false")
there are a few good JRadioButtons as Renderer and Editor in JTable, including usage of JComboBox as Editor for RadioButtonGroup
If you need to dynamically change the Look and Feel, your CellEditor is recommended to extend Component.
//#see javax/swing/SwingUtilities.java
static void updateRendererOrEditorUI(Object rendererOrEditor) {
if (rendererOrEditor == null) {
return;
}
Component component = null;
if (rendererOrEditor instanceof Component) {
component = (Component)rendererOrEditor;
}
if (rendererOrEditor instanceof DefaultCellEditor) {
//Ahh, AbstractCellEditor ...
component = ((DefaultCellEditor)rendererOrEditor).getComponent();
}
if (component != null) {
SwingUtilities.updateComponentTreeUI(component);
}
}
Here is a "CellEditor extends JRadioButton ..." example:
import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class DisplayTable2 extends JDialog {
public void initialize() {
Object[][] data = {
{ true, "Group1", "Work1" }, { false, "Group2", "Work2" },
{ false, "Group3", "Work3" }, { false, "Group4", "Work4" }
};
JTable sourceTable = new JTable(new SourceTableModel(data));
sourceTable.getColumnModel().getColumn(0).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(0).setCellEditor(new RadioButtonEditor());
JPanel panel = new JPanel();
panel.add(new JScrollPane(sourceTable));
add(panel);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setModal(true);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new DisplayTable2().initialize();
}
});
}
}
class SourceTableModel extends DefaultTableModel {
private static final String[] columnNamesList = {"Select", "Group", "Work"};
public SourceTableModel(Object[][] data) {
super(data, columnNamesList);
}
#Override public Class<?> getColumnClass(int columnIndex) {
return (columnIndex == 0 ? Boolean.class : String.class);
}
#Override public boolean isCellEditable(int rowIndex, int columnIndex) {
return (columnIndex == 0 ? true : false);
}
#Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if(columnIndex==0 && aValue instanceof Boolean) {
//lazy development
for(int i=0; i<getRowCount(); i++) {
super.setValueAt(i==rowIndex, i, columnIndex);
}
} else {
super.setValueAt(aValue, rowIndex, columnIndex);
}
}
}
class RadioButtonRenderer extends JRadioButton implements TableCellRenderer {
#Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value instanceof Boolean) {
setSelected((Boolean)value);
}
return this;
}
}
class RadioButtonEditor extends JRadioButton implements TableCellEditor {
public RadioButtonEditor() {
super();
addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
#Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(value instanceof Boolean) {
setSelected((Boolean)value);
}
return this;
}
#Override public Object getCellEditorValue() {
return isSelected();
}
//Copid from AbstractCellEditor
//protected EventListenerList listenerList = new EventListenerList();
//transient protected ChangeEvent changeEvent = null;
#Override public boolean isCellEditable(EventObject e) {
return true;
}
#Override public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
#Override public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
#Override public void cancelCellEditing() {
fireEditingCanceled();
}
#Override public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
}
#Override public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
}
public CellEditorListener[] getCellEditorListeners() {
return listenerList.getListeners(CellEditorListener.class);
}
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for(int i = listeners.length-2; i>=0; i-=2) {
if(listeners[i]==CellEditorListener.class) {
// Lazily create the event:
if(changeEvent == null) changeEvent = new ChangeEvent(this);
((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
}
}
}
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for(int i = listeners.length-2; i>=0; i-=2) {
if(listeners[i]==CellEditorListener.class) {
// Lazily create the event:
if(changeEvent == null) changeEvent = new ChangeEvent(this);
((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
}
}
}
}

Categories