How to clear contents of a jTable ? - java

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();

Related

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.

How to delete all rows of a JTable in Loop?

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.

How can I return a variable from within a "for" loop inside a mouseEntered method?

I've made a stadiumPanel class that contains a two-dimensional array of JButtons, each with their own MouseListener. Each button corresponds to a "Seat" object, which contains a set of data (inside a separate data class), and when I hover over the button with the mouse, I want to grab the data that corresponds to that button and display it in my parent class (a JWindow).
To do this, I'm trying to use two nested "for" loops inside the MouseEntered() method, which then uses MouseEvent.getSource() to search for the hovered-over JButton (and consequently the index corresponding to the correct Seat). A Seat object at the given index is then returned using my "stad.getSeat" method. Then, from the for loop, I want to store that seat in my "seatHovered" variable so I can access the data corresponding to that Seat from another class. However, I can't manage to change the hoveredSeat variable from within the "for" loop.
How can I do this?
public class StadiumPanel extends JPanel implements MouseListener
{
Seat hoveredSeat;
Stadium stad;
JButton[][] buttons = new JButton[Stadium.ROWS+1][Stadium.COLUMNS+1];
public StadiumPanel(Stadium s){
stad = s;
for (int row = 0; row < Stadium.ROWS; row++){
for (int col = 0; col < Stadium.COLUMNS; col++){
buttons[row][col] = new JButton();
add(buttons[row][col]);
buttons[row][col].addMouseListener(this);
}
}
}
public void mouseEntered(MouseEvent e)
{
for (int row = 0; row < Stadium.ROWS; row++){
for (int col = 0; col < Stadium.COLUMNS; col++){
if (e.getSource() == buttons[row][col] && buttons[row][col] != null){
hoveredSeat = stad.getSeat(row,col);
}
}
}
}
}
My apologies if this question is ridiculously confusing. Any input is much appreciated.

refreshing JTable doesn't show correctly data

this function should refresh my JTable:
list = null;
list = (ArrayList<String[]>) interface_engine.getData();
info = new String[list.size()][header.length];
Iterator it = list.iterator();
for (int i = 0; i < list.size(); i++) {
String[] current = (String[]) it.next();
for (int j = 0; j < header.length; j++) {
info[i][j] = current[j];
}
}
DefaultTableModel model = (DefaultTableModel) data_table.getModel();
model.addRow(info);
when i call it for add a new row (getData is a remote method for retrieve data from db), the added row it's not display as a string, but a a variable reference (such as String#128dda...). Where's the problem?
the added row it's not display as a string, but a a variable reference (such as String#128dda...).
Read the DefaultTableModel API. You can't add a 2-Dimensional array using the addRow() method. You can only add one row at a time.
The addRow() method should be inside your loop. Build one row of data, then invoke the addRow() method.

Categories

Resources