How to check if table is made in Jtable and JFrame - java

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.
}

Related

Using result set to add dynamic JCheckBox

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.

How can i add a mouse click listener to a jCombobox in a jTable cell?

I created a TableColumn like this:
TableColumn ColonneArticle = jTableBonCommande.getColumnModel().getColumn(1);
I filled it from DB table named "Article"
List<Article> l = new ArrayList<Article>();
l= em.createNamedQuery("Article.findAll").getResultList();
TableColumn ColonneArticle = jTableBonCommande.getColumnModel().getColumn(1);
JComboBox comboBox = new JComboBox();
for (int i = 0; i < l.size(); i++) {
comboBox.addItem(l.get(i).getDesignationarticle());
}
ColonneArticle.setCellEditor(new DefaultCellEditor(comboBox));
Now i want to fill my jTable with selected "Article" credentials, so can i add a mouse click listener to a jCombobox in a jTable cell ?
Please Help !
When a cell is updated, the TableModel#setValueAt method is called. When this occurs for the first column, you should then load the values for the row based on the value passed to the this method

Modify Entire Column(s) in JTable

I have a JTable which is formed by importing data from a text file. It is a huge table with about 522 columns and thousands of rows. Many cells in this table are empty as well.
Now, I want to be able to apply some mathematical operations to the data available in certain columns. So right now, I can select multiple columns, but I dont know how to go about getting these values. I know I'll need an array of arrays where I can store the value from the table columns and then modify each value based on my algorithm.
Right now, to start it off simply, I just want to be able to print out the values in the select column (just one to keep it simple) but I cant do that, I get the value of a particular cell printed 2-4 times. My testing code is as follows:
For Selection entire columns, I am using this code:
public static void selectWholeColumn(final JTable table)
{
final JTableHeader header = table.getTableHeader();
header.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int col = header.columnAtPoint(e.getPoint());
if(header.getCursor().getType() == Cursor.E_RESIZE_CURSOR)
{
e.consume();
}
else
{
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
table.clearSelection();
table.setColumnSelectionInterval(col,col);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
}
});
}
In my GUI I have a button which when clicked fires a backend class and this method which takes in a JTable as a parameter is executed to print out the values of all rows in the selected Column:
public void filterData(final JTable table)
{
TableModel model = table.getModel();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(false);
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedColumns.length; i++)
{
for (int j = 0; j < selectedRow.length; j++)
{
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
Any suggestions as to how I could print or basically get the values of all rows in a selected Column or columns, so that I can modify the data in them at once?
Thank you!
Looping though the TableModel and using getValueAt() in a ListSelectionListener is a reasonable approach, although your listener will be invoked for each change. It's not clear where you're having trouble; you can
Concatenate the selected values using StringBuilder.
Accumulate the selected values in a List<String>.
Maintain the selection in your TableModel, as shown here using Set<Integer>.
Operate on the selection in the ItemHandler of a TableCellRenderer, as shown here.

How to put data in JTable from Vector with java

I have a table which has only field names and no data, I want to enter data from inputs
by Vector
i try this cod but is't work
Object[][] ss= new frand[1][];
for(int i = 0 ; i<feeds.size();i++){
ss[1][i]=feeds.get(i);
}
JTable table = new JTable(
// new Object[][] {
// new frand[] { feeds.get(0) },
// new frand[] { feeds.get(1) }
// },
ss,
new String[] { "connect client " }
);
frandtabmodule module = new frandtabmodule(feeds);
table.setModel(module);
how do I do that?
to load the table from an array A, if the table just create it, you can simply use:
  
  table.setModel (new javax.swing.table.DefaultTableModel (
                 new String [] [] {
{"2014-02-22", A.get(0)}
}   ,         
                 new String [] {
             "Date", "Total"
         }));
if not, you can use the DefaultTableModel class and its methods and AddColumn addRow
It seems that you first create a table by passing data and columns, then create a model and set the model. When you pass column and row data in JTable constructor, then the table creates and uses DefaultTableModel that is initialized with that data. If you have a specialized model frandtabmodule that wraps around the original vector feeds there is no need to build an array and pass it to the table. Just use JTable default constructor and then call setModel, or use a constructor that takes a model as an argument.
See How to use Tables for more details and examples.
EDIT:
Not sure is that is the intention, but the posted code indicates that you want to use the vector elements as columns. If that is not the intention, then it seems you have a mix up of indexes while building an array. The first set of square brackets is for the rows and the second is for columns. For example:
private static Object[][] vector2DArray(Vector<Object> sourceVector) {
Object[][] rows = new Object[sourceVector.size()][1];
for (int i = 0; i < sourceVector.size(); i++) {
rows[i][0] = sourceVector.get(i);
}
return rows;
}

Invert the Selection in JTable

On clicking a button, I want the selected rows to be inverted (non-selected rows should be selected and selected rows should be non-selected).
Is there a build-in method in JTable to do it?
JTable doesn't seems to have a built-in way of doing this. So I implemented it with the following code. (Hope this is helpful for someone who is facing a similar issue.)
int[] selectedIndexs = jtable.getSelectedRows();
jtable.selectAll();
for (int i = 0; i < jtable.getRowCount(); i++) {
for (int selectedIndex : selectedIndexs) {
if (selectedIndex == i) {
jtable.removeRowSelectionInterval(i, i);
break;
}
}
}
To simplify Sudar's solution:
int[] selectedIndices = table.getSelectedRows();
table.selectAll();
for (int prevSel : selectedIndices) {
table.removeRowSelectionInterval(prevSel, prevSel);
}
JTable does not have that feature
No, You will have to implement a cutsom ListSelectionListener
A refinement to above is to update selection using the selection model object, not the table object. When you update the selection via the table, each update fires a selection change event and it takes few seconds to update a table with just a few hundred rows.
The fastest way for tables with more than few hundred rows is this
/**
* Invert selection in a JTable.
*
* #param table
*/
public static void invertSelection(JTable table) {
ListSelectionModel mdl = table.getSelectionModel();
int[] selected = table.getSelectedRows();
mdl.setValueIsAdjusting(true);
mdl.setSelectionInterval(0, table.getRowCount() - 1);
for (int i : selected) {
mdl.removeSelectionInterval(i, i);
}
mdl.setValueIsAdjusting(false);
}

Categories