Removing all the rows of DefaultTableModel
Why complicating simple things, but removes must be iterative,
if (myTableModel.getRowCount() > 0) {
for (int i = myTableModel.getRowCount() - 1; i > -1; i--) {
myTableModel.removeRow(i);
}
}
Code example
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;
public class RemoveAddRows extends JFrame {
private static final long serialVersionUID = 1L;
private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
private Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50)},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
{"Sell", "Apple", new Integer(3000), new Double(7.35)},
{"Buy", "Nortel", new Integer(4000), new Double(20.00)}
};
private JTable table;
private DefaultTableModel model;
public RemoveAddRows() {
model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model) {
private static final long serialVersionUID = 1L;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
int firstRow = 0;
int lastRow = table.getRowCount() - 1;
int width = 0;
if (row == lastRow) {
((JComponent) c).setBackground(Color.red);
} else if (row == firstRow) {
((JComponent) c).setBackground(Color.blue);
} else {
((JComponent) c).setBackground(table.getBackground());
}
/*if (!isRowSelected(row)) {
String type = (String) getModel().getValueAt(row, 0);
c.setBackground("Buy".equals(type) ? Color.GREEN : Color.YELLOW);
}
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}*/
return c;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
JButton button1 = new JButton("Remove all rows");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (model.getRowCount() > 0) {
for (int i = model.getRowCount() - 1; i > -1; i--) {
model.removeRow(i);
}
}
System.out.println("model.getRowCount() --->" + model.getRowCount());
}
});
JButton button2 = new JButton("Add new rows");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Object[] data0 = {"Buy", "IBM", new Integer(1000), new Double(80.50)};
model.addRow(data0);
Object[] data1 = {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)};
model.addRow(data1);
Object[] data2 = {"Sell", "Apple", new Integer(3000), new Double(7.35)};
model.addRow(data2);
Object[] data3 = {"Buy", "Nortel", new Integer(4000), new Double(20.00)};
model.addRow(data3);
System.out.println("model.getRowCount() --->" + model.getRowCount());
}
});
JPanel southPanel = new JPanel();
southPanel.add(button1);
southPanel.add(button2);
add(southPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
RemoveAddRows frame = new RemoveAddRows();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Deleting all the rows in a JTable
The following code worked for me:
DefaultTableModel dm = (DefaultTableModel) getModel();
int rowCount = dm.getRowCount();
//Remove rows one by one from the end of the table
for (int i = rowCount - 1; i >= 0; i--) {
dm.removeRow(i);
}
Removing Row from DefaultTableModel Object
The "very" basic idea is, when TableModel#setValue
is called, you want to check the column
that was modified. If the column
is (in this case) 5
, you'll want to check what the value is...
For example...
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 5) {
if ("Delete".equals(aValue)) {
removeRow(rowIndex);
}
}
}
Remember, the above example overrides the default behaviour of setValueAt
, so if you're relying on the values to updated in the model, you need to call super.setValueAt(...)
Take a look at How to use tables
how to remove all rows in jtable?
for example
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;
public class RemoveAddRows extends JFrame {
private static final long serialVersionUID = 1L;
private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
private Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50)},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
{"Sell", "Apple", new Integer(3000), new Double(7.35)},
{"Buy", "Nortel", new Integer(4000), new Double(20.00)}
};
private JTable table;
private DefaultTableModel model;
public RemoveAddRows() {
model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model) {
private static final long serialVersionUID = 1L;
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
int firstRow = 0;
int lastRow = table.getRowCount() - 1;
int width = 0;
if (row == lastRow) {
((JComponent) c).setBackground(Color.red);
} else if (row == firstRow) {
((JComponent) c).setBackground(Color.blue);
} else {
((JComponent) c).setBackground(table.getBackground());
}
/*if (!isRowSelected(row)) {
String type = (String) getModel().getValueAt(row, 0);
c.setBackground("Buy".equals(type) ? Color.GREEN : Color.YELLOW);
}
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}*/
return c;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
JButton button1 = new JButton("Remove all rows");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (model.getRowCount() > 0) {
for (int i = model.getRowCount() - 1; i > -1; i--) {
model.removeRow(i);
}
}
System.out.println("model.getRowCount() --->" + model.getRowCount());
}
});
JButton button2 = new JButton("Add new rows");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Object[] data0 = {"Buy", "IBM", new Integer(1000), new Double(80.50)};
model.addRow(data0);
Object[] data1 = {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)};
model.addRow(data1);
Object[] data2 = {"Sell", "Apple", new Integer(3000), new Double(7.35)};
model.addRow(data2);
Object[] data3 = {"Buy", "Nortel", new Integer(4000), new Double(20.00)};
model.addRow(data3);
System.out.println("model.getRowCount() --->" + model.getRowCount());
}
});
JPanel southPanel = new JPanel();
southPanel.add(button1);
southPanel.add(button2);
add(southPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
RemoveAddRows frame = new RemoveAddRows();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Recreate Jtable or remove all rows and add new rows?
What's the best choice to do that, renew Jtable or remove all rows and addrows?
If you recreate the JTable, all the renderers and editors will be recreated for the table.
If you change the TableModel, then the table will need to recreate the TableColumnModel, and all the TableColumns based on the new TableModel.
There will be many more objects that need to be created to support the JTable/TableModel relationship.
Removing rows and adding rows, will just cause the table to repaint the new data using all the current renderers. I would say this is more efficient. And instead of adding rows one at a time, you should add all the rows at once
Swing JTable, exception while removing rows from DefaultTableModel
there are 2 problems in your code .
1)try to get values from none existing row/column - in modellistner
.
2)continuously remove rows without stopping even when there are no more rows-in removeTableRows
method
let me explain 2nd error first.
2)
inside the while loop you are not update row count.you are getting row count but this while loop condition never become false.for example you have 3 rows and count is 3 now inside while loop you are checking (rows > 0)
no matter how much time it loops it's always true so when loop runs 4th time you get a error because there is no more rows to remove. you have to recount the row count
change method to
DefaultTableModel defaultModel= (DefaultTableModel) tableToClear.getModel();
int rows = defaultModel.getRowCount();
while (rows > 0) {
defaultModel.removeRow(0);
rows = defaultModel.getRowCount(); // this is very important
}
String[] test = {"a", "b", "c"};
defaultModel.addRow(test);
note:
you can use method defaultModel.RowCount(0);
method to remove all rows .you don't need to do it using a loop
1)
make sure row and col is 0 or more than it .because those can be -1 when they doesn't exist.then you will get lot of errors
so this line is important
(row >= 0 && col >= 0){}
and also here
boolean ishotKeyColEmpty = tableModel.getValueAt(row, 0).toString().isEmpty();
you have to safely check getValueAt(row, 0)
is not null before call
toString().isEmpty()
method.
in your
complete code
addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
TableModel tableModel = (TableModel) e.getSource();
Object data = null;
try {
if (row >= 0 && col >= 0) {
data = tableModel.getValueAt(row, col);
boolean ishotKeyColEmpty = false;
boolean ishTypeColEmpty = false;
if (tableModel.getValueAt(row, 0) != null) {
ishotKeyColEmpty = tableModel.getValueAt(row, 0).toString().isEmpty();
}
if (tableModel.getValueAt(row, 2) != null) {
ishTypeColEmpty = tableModel.getValueAt(row, 2).toString().isEmpty();
}
if (data != null && data.toString().equals("") && !ishotKeyColEmpty && !ishTypeColEmpty) {
tableModel.setValueAt("", row, 0);
tableModel.setValueAt("", row, 2);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Related Topics
Any Character Including Newline - Java Regex
Using PDFbox to Write Utf-8 Encoded Strings to a PDF
Spring Boot Actuator Without Spring Boot
Java:Read Last N Lines of a Huge File
How to Cause a Child Process to Exit When the Parent Does
How Are Constructors Called During Serialization and Deserialization
Javac Error: Class Names Are Only Accepted If Annotation Processing Is Explicitly Requested
Java: Local Variable Mi Defined in an Enclosing Scope Must Be Final or Effectively Final
Loss of Precision - Int -> Float or Double
Making Spring-Data-Mongodb Multi-Tenant
Often Big Numbers Become Negative
How to Use Regular Expressions in Web.Xml Url Patterns
File Upload Using Selenium Webdriver and Java Robot Class