Using result set to add dynamic JCheckBox - java

I saw this Need to add JCheckBox In JTable Dynamically but it didn't help at all seeing my situation is similar but I am not sure how to add the JCheckBox after I have take the raw data from my database.
public void fillAnyTable(ResultSet resultSet, JTable table)throws SQLException{
//Create new table model
DefaultTableModel tableModel = new DefaultTableModel();
//Retrieve meta data from ResultSet
ResultSetMetaData metaData = resultSet.getMetaData();
//Get number of columns from metadata
int columnCount = metaData.getColumnCount();
//Get all column names from metadata and add columns to table
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
tableModel.addColumn(metaData.getColumnLabel(columnIndex));
}
//this is when I assume I can create a new column but now how to add the checkbox
tableModel.addColumn("Check");
//Create Array of Objects with size of Column count from metadata
Object[] row = new Object[columnCount];
//Scroll through Result Set
while (resultSet.next()){
//Get object from column with specific index of result set to array of objects
for (int i = 0; i < columnCount; i++){
row[i] = resultSet.getObject(i+1);
}
System.out.println(Arrays.toString(row));
//Now add row to table model with that array of objects as an argument
tableModel.addRow(row);
}
//Now we add the table model to the table
table.setModel(tableModel);
}
}
This is what the view looks like

I am not sure how to add the JCheckBox after I have take the raw data from my database.
You don't add a JCheckBox. The TableModel holds data, not components. So you need to:
override the getColumnClass(...) method of the TableModel to return Boolean.class for the column where you want the check box. Then the table will use the proper renderer/editor for a check box.
add Boolean.FALSE to the TableModel when you add the data from the ResultSet.
So you just add the Boolean value when you are finished adding each column value to your row array:
//Now add row to table model with that array of objects as an argument
row[columnCount].add( Boolean.FALSE );
tableModel.addRow(row);
Of course you will also need to make your "row" array larger to hold this value.

Related

Get rows from a jtable sorted with RowSorter

Actually i am able to export as excel but it export the entire JTable not the sorted data with Rowsorter, i tried something like but nothing changed :
DefaultTableModel tableModel;
try {
RowSorter<? extends TableModel> rowSorter = model.getjTable1().getRowSorter();
TableModel tableModel = rowSorter.getModel();
} catch (NullPointerException ne) {
tableModel = (DefaultTableModel) model.getjTable1().getModel();
}
A second important thing about my jtable, actually i can select only 1 row and i wont be able to change that.
My question, is, how can i only get the sorted rows from RowSorter ?
Do i need to sort programmatically ? Can i get the visible rows from my jtable ?
but it export the entire JTable not the sorted data
The data in the TableModel does NOT change.
Only the data displayed in the JTable (the view) changes.
If you only want the data in the table then you only use methods of the JTable to access the data.
Something like:
for (int row = 0; row < table.getRowCount(); row++)
for (int column = 0; column < tagle.getColumnCount(); column++)
System.out.println( table.getValueAt(row, column);

How to populate multiple JTables using a method where there are variable columns

I would like to populate more than one JTable using the code below. The amount of columns in the 2D array can be variable. So I would like to use a method that accepts an integer to indicate the number of columns to add in the following line:
tableModel.addRow(new Object[]{arr[i][0], arr[i][1]});
I'm trying to figure a way to add (for each new JTable) a specified number of arr[i][0], arri, to a table determined by a method argument.
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
for (int i = 0; i < arr.length; i++) {
tableModel.addRow(new Object[]{arr[i][0], arr[i][1]});
}
Is this possible?
This is linked in a way to my previous question: How to populate a JComboBox using a method
In order for data to be displayed in a JTable, you must have a column defined in the TableColumnModel of the table.
So you need to define your DefaultTableModel with the maximum number of columns that is possible.
Then you just use the addRow(...) method. The DefaultTableModel will automatically pad the row with null values up to the maximum number of columns.

How to check if table is made in Jtable and JFrame

Hi I want to check if table is made to add rows.If is not I want to show message :create table first. My problem : I do not know what I should type to if statement to check if is although one row made(which can suggest me that table was created).
I create table via NetBeans JFrame options this way:
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
/*
space is empty here because on start I do not create any rows.
user has to click button create or add rows.
*/
},
new String [] {
"Name", "Surname"
}
));
My if statment:
if(//do not know what type here because new Object [][] will not work){
JOptionPane.showMessageDialog(null, "Create table!");
}else //add row to table because exist {
Object[][] temp = new Object[data.length + 1][2];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 2; j++) {
temp[i][j] = data[i][j];
}
}
data = temp;
jTable1.setModel(new DefaultTableModel(data, columns));
}
Looks like you're using NetBeans GUI builder. If you go to the properties pane (the tab to the very right in Netbeans design view) with the jTable highlighted, you will see a property model
Click on the ... button to the right of the property, and a Dialog will pop up
Set the number of rows to 0, and the number of columns to how many columns you want, and set the column title and type and if you want it editable
Then in your actionPerformed, however you get the data for rows, add an array of that data to the model with model.addRow()
public void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// get row data, and put it into an array
Object[] row = {data1, data2, data3 ...};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(row);
}
So whenever the button is pressed, a row will be added dynamically to your table. That's the easiest way to do it with GUI Builder
EDIT
If you want to check the number of rows then you check the rowCount
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if (model.getRowCount() < 1) {
do something.
}

JTable in Netbeans

I want to add db(MySql) data to a single specific column in jTable when there is three columns. From this below coding the data automatically add to the 1st column, but I want to add it to the 2nd column in Jtable. Please help me ..i'm new to netbeans !!!
Connection con = Driver.connect();
ResultSet rst = Handler.getData(con, "select lec_name from lecturer");
DefaultTableModel dtm = (DefaultTableModel)jTable1.getModel();
while (rst.next()) {
Object ob []= {rst.getString(1)};
dtm.addRow(ob);
}
Each element in the Object array is a column. This means, you simply means you just need to fill the row array with the correct values
Object ob []= {rst.getString(1), rst.getString(2), rst.getString(3)}};
dtm.addRow(ob);
This of course assumes you've added the appropriate columns to the model in the first place

How can I delete the column and its underlying data without hiding it in jtable

I am having difficulties with deleting the actual data under a particular column which I am trying to delete.
I actually want to delete the column and its underlying data. I am able to insert new columns but when I delete
and insert again, the old columns which I previously deleted pop up again.
Any sort help is appreciated.
Thank you in advancce.
The data is stored in the TableModel.
Deleting the column from the ColumnModel will only prevent the view (the JTable) from showing it.
In order to remove it, you need to tell the TableModel to remove the column data as well.
Depending on you implementation, you could use JTable.setValueAt(value, row, column) or TableModel.setValueAt(value, row, column), which ever is more convenient.
This of course assumes you've implemented the setValueAt method
public void removeColumnAndData(JTable table, int vColIndex) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn col =table.getColumnModel().getColumn(vColIndex);
int columnModelIndex = col.getModelIndex();
Vector data = model.getDataVector();
Vector colIds = model.getColumnIdentifiers();
// Remove the column from the table
table.removeColumn(col);
// Remove the column header from the table model
colIds.removeElementAt(columnModelIndex);
// Remove the column data
for (int r=0; r<data.size(); r++) {
Vector row = (Vector)data.get(r);
row.removeElementAt(columnModelIndex);
}
model.setDataVector(data, colIds);
// Correct the model indices in the TableColumn objects
// by decrementing those indices that follow the deleted column
Enumeration<TableColumn> enum1 = table.getColumnModel().getColumns();
for (; enum1.hasMoreElements(); ) {
TableColumn c = (TableColumn)enum1.nextElement();
if (c.getModelIndex() >= columnModelIndex) {
c.setModelIndex(c.getModelIndex()-1);
}
}
model.fireTableStructureChanged();
}
/*MyDefaultTableModel class**/
class MyTableModel extends DefaultTableModel
{
String columns[];
int size;
public MyTableModel(String col[],int size)
{
super(col,size);
columns = col;
this.size=size;
}
public Vector getColumnIdentifiers()
{
return columnIdentifiers;
}
}

Categories