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.
Related
I'm trying to loop through all of the rows in a column in a jTable at the moment I can get it to loop through a column but it only gives me the first 5 values and it also gives me a strange output.
here is the code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// Button to Start
Object[] columnData = new Object[jTable1.getColumnCount()];
Object[] rowData = new Object [jTable1.getRowCount()];
for (int i = 0; i < jTable1.getColumnCount(); i++) {
columnData[i] = jTable1.getValueAt(i, 4);
System.out.println(Arrays.toString(columnData));
}
here is the output:
I think you are using your column iteration as the row number in your code. jTable1.getValue(i, 4) has parameters row, column in that order. If you only have five columns, you will only get five values.
Try changing the loop to count through the rows and select the 5th column.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// Button to Start
Object[] columnData = new Object[jTable1.getRowCount()]; // One entry for each row
Object[] rowData = new Object [jTable1.getRowCount()];
for (int i = 0; i < jTable1.getRowCount(); i++) { // Loop through the rows
// Record the 5th column value (index 4)
columnData[i] = jTable1.getValueAt(i, 4);
}
System.out.println(Arrays.toString(columnData));
I'm using GridPane for my JavaFX layout, and I always use width percentages for ColumnConstraints, but in one specific case it seems it does not work: when I set the width percentage of a ColumnConstraints inside an array.
My code:
ColumnConstraints[] myColumns = Factory.createColumns(3);
myColumns[0].setPercentWidth(35);
myColumns[1].setPercentWidth(12);
myColumns[2].setPercentWidth(53);
devicePane.getColumnConstraints().setAll(myColumns);
The array comes from my utility method for column creation using equally divided sizes:
public static final ColumnConstraints[] createColumns(int count) {
ColumnConstraints[] columns = new ColumnConstraints[count];
ColumnConstraints column = new ColumnConstraints(1, 10, Double.MAX_VALUE);
column.setPercentWidth(100/count);
column.setFillWidth(true);
column.setHgrow(Priority.ALWAYS);
column.setHalignment(HPos.CENTER);
for(int i = 0; i < count; i++) {
columns[i] = column;
}
return columns;
}
Result:
Columns with old width percentage
But the expected is:
Columns with right width percentage
You're just creating a single ColumnConstraints object. This makes it impossible to assign different values to the percentWidth property. You need to create seperate objects for this purpose:
public static final ColumnConstraints[] createColumns(int count) {
ColumnConstraints[] columns = new ColumnConstraints[count];
for(int i = 0; i < count; i++) {
ColumnConstraints column = new ColumnConstraints(1, 10, Double.MAX_VALUE);
column.setPercentWidth(100/count); // do we still need this?
column.setFillWidth(true);
column.setHgrow(Priority.ALWAYS);
column.setHalignment(HPos.CENTER);
columns[i] = column;
}
return columns;
}
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.
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.
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();