How to delete all rows of a JTable in Loop? - java

I am trying to delete all rows of my JTable when an action is performed.
I wrote code below:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int rowCount = model.getRowCount();
for (int i = 0; i < rowCount ; i++){
model.removeRow(i);
}
But it didn't work as I expected.

Each time you remove a row, the row count will change. Better to continue looping until there are no rows left
while (model.getRowCount() > 0) {
model.removeRow(0);
}
Now, if I'm not wrong, you could also just do model.setRowCount(0) and it will remove all the rows for you ;)

I searched the net and find out that we should delete the rows of the table from the end of the table instead of the beginning. I wanted to share this information with others.
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount; i > 0 ; i--){
model.removeRow(i-1);
}
It worked properly for me. Good Luck.

Related

Why ArrayIndexOutOfBoundsException error on Jtable having one element

I want to add jTable elements to a list. It works fine when jTable have more then one element, but it gives me the the following error when jTable have one element. Why so? How to resolve it. Thank You.
Here is the error.
Error: Exception in thread "AWT-EventQueue-0"
java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
Here is the code:
DefaultTableModel table_tags = (DefaultTableModel)this.jTable_selectedTags.getModel();
int rowCount=table_tags.getRowCount();
Vector data = table_tags.getDataVector();
Vector row = (Vector) data.elementAt(1);
int mColIndex = 0;
List tags_data = new ArrayList(rowCount);
for (int i = 0; i < table_tags.getRowCount(); i++) {
row = (Vector) data.elementAt(i);
tags_data.add(row.get(mColIndex));
}
System.out.println(tags_data);
The issues was in accessing of index. So, after changing
Vector row = (Vector) data.elementAt(1);
to
Vector row = (Vector) data.elementAt(0);
It worked fine.
Your for loop is wrong. You iterate the table using this condition:
for (int i = 0; i < table_tags.getRowCount(); i++)
Problem is that you use the row count to perform the iteration. Given only one element in the Vector your row count would indeed by 1 but using this to iterate over the table would cause it to fail, since the only element at the table would at index 0. Change your above condition to:
for (int i = 0; i < table_tags.getRowCount() - 1; i++)
And I suppose you'll be fine.

Error while removing row from Libgdx's table

I want to write a board game using LibGDX and during a game I want make it possible to add or remove rows / columns on that board. First, I made some tests to prepare myself to that. Here is the code :
public class Test extends Game {
Skin skin;
Stage stage;
Texture texture1;
static int columns = 7;
static int rows = 12;
Window window2;
Table table2;
ArrayList<ArrayList<TextButton>> buttons;
#Override
public void create () {
skin = new Skin(Gdx.files.internal("data/uiskin.json"));
buttons = new ArrayList<ArrayList<TextButton>>();
for(int i = 0 ; i< rows; ++i)
{
buttons.add(new ArrayList<TextButton>());
for( int k = 0; k < columns; ++k)
{
buttons.get(i).add(new TextButton(("ASD" + i + k), skin));
}
}
texture1 = new Texture(Gdx.files.internal("data/badlogicsmall.jpg"));
TextureRegion image = new TextureRegion(texture1);
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
ImageButtonStyle style = new ImageButtonStyle(skin.get(ButtonStyle.class));
style.imageUp = new TextureRegionDrawable(image);
ImageButton iconButton = new ImageButton(style);
window2 = new Window("Dialog2", skin);
window2.getTitleTable().add(new TextButton("X", skin)).height(window2.getPadTop());
window2.setSize(300, 400);
table2 = new Table();
for(int i = 0 ; i< rows; ++i)
{
for( int k = 0; k < columns; ++k)
{
table2.add(buttons.get(i).get(k));
}
table2.row();
}
ScrollPane pane= new ScrollPane(table2,skin);
pane.setScrollbarsOnTop(false);
pane.setFadeScrollBars(false);
window2.add(iconButton).row();
window2.add(pane);
stage.addActor(window2);
iconButton.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
new Dialog("Some Dialog", skin, "dialog") {
protected void result (Object object) {
System.out.println("Chosen: " + object);
if((Boolean) object )
{
for(int i = 0 ; i <columns; ++i){
table2.getCells().removeIndex(0).getActor().remove();}
}
}
}.text("Are you enjoying this demo?").button("Yes", true).button("No", false).key(Keys.ENTER, true)
.key(Keys.ESCAPE, false).show(stage);
}
});
}
#Override
public void render () {
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
}
As you can see here, I'm creating a standalone button and a table and fill it with buttons. Then after button clicked I want to remove first row of that table and also move rest of rows up. It works but only once (for first row), then (with second click) I got this exception :
Exception in thread "LWJGL Application" java.lang.IndexOutOfBoundsException: index can't be >= size: 70 >= 70
Don't know what to do and how to fix it. Hope you can help me with this.
UPDATE
Thanks for reply; my code looks like this now :
// initialization
for(int i = 0 ; i< rows; ++i)
{
for( int k = 0; k < columns; ++k)
{
table2.add(new TextButton(("ASD" + i + k), skin));
}
table2.row();
}
// sample operation - remove left column
for(int i = 0 ; i <rows; ++i){
table2.removeActor( table2.getChildren().get(i*columns-i) );
}
columns--;
Also, I got similar Array in logical model and want to change state of UI table based on that array. So is this approach correct or should I change something?
The issue is about row() you are using - before the first row there is no row cell (marked with row() method) and that's why it does not cause error but when removing the second one it does.
Compare with table2 without any rows to test it:
for(int i = 0 ; i< rows; ++i)
{
for( int k = 0; k < columns; ++k)
{
table2.add(buttons.get(i).get(k));
}
//table2.row(); - we don't want any rows!
}
Ok we know where problem lays but it is not the solution (ok maybe some solution it is:) ). Instead of hard removing indexes of Table cells you should operate on Actors of table using following code:
for(int i = 0 ; i <columns; ++i){
table2.removeActor( table2.getChildren().first() );
}
Working with a table in such a way is a bit cumbersome, at least I don't know better. A quick fix for your code would be:
// Global field
int removedRows = 0;
// In your listener
System.out.println("Chosen: " + object);
if ((Boolean) object)
{
for (int i = 0; i < columns; ++i)
{
table2.getCells().get(i + columns * removedRows).clearActor();
}
removedRows++;
}
But if you want to remove complete rows, I would use a VerticalGroup and add each row there, so you can directly access a row and remove it from the VerticalGroup. If you use a fixed size for the buttons then it will align properly, too.
table2.getCells()
Returns an Array, this means we now operate on that Array and NOT the table2 anymore!
This means if you execute this:
table2.getCells().removeIndex(0);
It will just remove that cell from the array. This does NOT update the table2 as a complete object, just the cells array of that table (since no copy of that array is returned)
In other words you are doing this:
Array<Cell> table2Cells = table2.getCells();
Cell tableCell = table2Cells.removeIndex(0);
tableCell.clearActor();
So you delete the cell from the table2 cell array, and then you clear the cells contents (actor in this case). But you are not updating the table to reflect the changes of the removed cell, table2 still "thinks" that the cell is there, but you deleted it.
Thus you get the index error, because the stage draws the table, and the table wants to draw a cell that no longer exists.
So if you want to create some kind of board for a game the best way would be to code your own class that provides the functionality you desire.
A workaround would be that you reset the table and fill it again:
int table2Rows = table2.getRows();
table2.reset();
// Omit the first row
for (int i = rows - table2Rows + 1; i < rows; ++i)
{
for (int k = 0; k < columns; ++k)
{
table2.add(buttons.get(i).get(k));
}
table2.row();
}
table2.layout();
Thus the first cell will contain the first button and so on, since the table internal values are properly updated.

Change the width of JTable column

I need to change the column width size of my JTable. Please look at the following code which will use to display values. But I don't know how to maximize the width of the table column.
please let me know how to configure my code.
public void displayTable(JTable table){
Vector columns = new Vector(getIndividual(0).chromosomeColumnCount()+1);
columns.add("Staff Names");
for(int i=0; i<getIndividual(0).chromosomeColumnCount(); i++){
columns.add(RosterManager.getDay(i));
}
Vector data = new Vector();
Vector row;
for(int row1=0; row1<getIndividual(0).ChromosomeRowSize(); row1++){
row = new Vector(getIndividual(0).chromosomeColumnCount());
row.add(RosterManager.getNurse(row1).getEmpName());
for(int col=0; col<getIndividual(0).chromosomeColumnCount(); col++){
row.add(getIndividual(0).getShift(row1, col).getShiftName());
}
data.add(row);
}
DefaultTableModel tableModel = new DefaultTableModel(data, columns);
table.setModel(tableModel);
}
setPreferredWidth(27) can be used. Inside the method you have to add a dimension.
Something like this:
//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < cols.length; i++) {
column = table.getColumnModel().getColumn(i);
if(i == 0 ) column.setPreferredWidth(10);
}
Im using this method to change the width of columns of JTables. Just add this to your displayTable() method.
your_table_name.getColumnModel().getColumn(0).setPreferredWidth(50);
your_table_name.getColumnModel().getColumn(1).setPreferredWidth(100);
JTableName.getColumn(Object identifier).setWidth(WIDTH);
JTableName.getColumn(Object identifier) will return the column and set Width will change its width.

Row Index out of range exception while selecting a row where i removed

int[] selRows = getNstInclude().getTable().getSelectedRows();
if (selRows.length == 0)
{
return;
}
int selIndices = getNstInclude().getTable().getSelectedRow();
for (int i = selRows.length - 1; i >= 0; i--)
{
getNstInclude().getTableModel().removeRow(selRows[i]);
}
getNstInclude().getTable().setRowSelectionInterval(selIndices, selIndices);
where getNstInclude() is my jtable.
in the above code,intaially iam removing a row from my jtable and then iam selecting a row by using a same index where i removed the row,But it showing row index out of range exception.
can someone help me that what i done a mistake here?
thanks in advance

How to clear contents of a jTable ?

I have a jTable and it's got a table model defined like this:
javax.swing.table.TableModel dataModel =
new javax.swing.table.DefaultTableModel(data, columns);
tblCompounds.setModel(dataModel);
Does anyone know how I can clear its contents ? Just so it returns to an empty table ?
Easiest way:
//private TableModel dataModel;
private DefaultTableModel dataModel;
void setModel() {
Vector data = makeData();
Vector columns = makeColumns();
dataModel = new DefaultTableModel(data, columns);
table.setModel(dataModel);
}
void reset() {
dataModel.setRowCount(0);
}
i.e. your reset method tell the model to have 0 rows of data The model will fire the appropriate data change events to the table which will rebuild itself.
If you mean to remove the content but its cells remain intact, then:
public static void clearTable(final JTable table) {
for (int i = 0; i < table.getRowCount(); i++) {
for(int j = 0; j < table.getColumnCount(); j++) {
table.setValueAt("", i, j);
}
}
}
OK, if you mean to remove all the cells but maintain its headers:
public static void deleteAllRows(final DefaultTableModel model) {
for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
model.removeRow(i);
}
}
//To clear the Contents of Java JTable
DefaultTableModel dm = (DefaultTableModel) JTable1.getModel();
for (int i = 0; i < dm.getRowCount(); i++) {
for (int j = 0; j < dm.getColumnCount(); j++) {
dm.setValueAt("", i, j);
}
}
You have a couple of options:
Create a new DefaultTableModel(), but remember to re-attach any listeners.
Iterate over the model.removeRow(index) to remove.
Define your own model that wraps a List/Set and expose the clear method.
I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable.
For an example, if your table contains 40 raws, you can do following.
DefaultTableModel model = (DefaultTableModel)this.jTable.getModel();
model.setRowCount(0);
model.setRowCount(40);
One of the trivial methods is to use the following option.
dataModel.setRowCount(0);
dataModel is the model which you would like clear the content on
However, it is not optiomal solution.
Another easy answer:
defaultTableModel.getDataVector().removeAllElements();

Categories

Resources