Is there a way I can delete the highlighted selected columns in this jtable using the remove button? I know there's a way for rows but I'm not sure how to do this for selected columns.
private void RemoveColBActionPerformed(java.awt.event.ActionEvent evt) {
// Removes the highlighted column
}
private void AddBActionPerformed(java.awt.event.ActionEvent evt) {
//Add Data
lMessage.setText("");
DefaultTableModel model = (DefaultTableModel) JtableData.getModel();
if (!ProdNameTF.getText().trim().equals("")) {
model.addRow(new Object[] {
ProdNameTF.getText(), CategoryCB.getSelectedItem().toString(), PriceTF.getText()
});
} else {
lMessage.setText("Message Left Blank");
}
}
You can remove columns from the JTable view. The data will still be contained in the TableModel, it just won't be displayed in the JTable.
So the basic code would be:
TableColumnModel tcm = table.getColumnModel();
tcm.removeColumn( tcm.getColumn(...) );
For a more complex solution that allows the user to hide/show columns as they wish check out the Table Column Manager.
Related
I have two JTables which share a TableModel.
This is so that I can set them up in a scroll pane such that one of them has a few columns showing on the left and does not scroll sideways, visually 'freezing' those columns, and the other contains the rest of the columns.
They are always sorted the same so that the rows match up. This is done using a RowSorter listener, shown below. (frozenTable and tableView are the names of my JTables).
RowSorterListener rowSorterListener = new RowSorterListener() {
#Override
public void sorterChanged(RowSorterEvent e) {
if (RowSorterEvent.Type.SORT_ORDER_CHANGED == e.getType()) {
RowSorter source = e.getSource();
if (source == tableView.getRowSorter()) {
frozenTable.getRowSorter().removeRowSorterListener(this);
frozenTable.getRowSorter().setSortKeys(source.getSortKeys());
frozenTable.getRowSorter().addRowSorterListener(this);
} else {
tableView.getRowSorter().removeRowSorterListener(this);
tableView.getRowSorter().setSortKeys(source.getSortKeys());
tableView.getRowSorter().addRowSorterListener(this);
}
}
}
};
At another point in my code, I want to be able to get the TableColumn objects that are currently being sorted on. Before I added the frozentable, I was able to do this with the following code:
List<? extends SortKey> sortKeys = tableView.getRowSorter().getSortKeys();
for(SortKey key : sortKeys){
TableColumn column = tableView.getColumnModel().getColumn(key.getColumn());
// other stuff in the loop
}
It seems as though a SortKey only has two things in it, a column index and a SortOrder. This raises two questions:
How is my RowSorterListener even managing to sort the tables based on columns from one or the other table? If all I'm passing when I say 'setSortKeys' is 'sort by column 3' and column 3 is different for each JTable, then how is this working in the first place? Because it does work. If I have a Name column in the frozenTable and an Age column in the tableView and I sort by Age, it does sort both JTables by the Age column.
How do I get the TableColumn object associated with a SortKey?
Check out the Fixed Column Table which is a reusable class that allows you to share a model between two tables
The code to create the fixed column table is:
JTable table = new JTable(...);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane= new JScrollPane( table );
FixedColumnTable fct = new FixedColumnTable(2, scrollPane);
JTable fixed = fct.getFixedTable();
I don't think you need the sorter listener.
You should just be able to share the RowSorter using code something like:
table.setAutoCreateRowSorter(true);
fixed.setRowSorter(table.getRowSorter());
table.setUpdateSelectionOnSort(true);
fixed.setUpdateSelectionOnSort(false);
I have a JTable in which I can add users with several attributes like age, name, etc. This works and the users are added to my arraylist and JTable.
Now what I want is when I choose the JTable row, to be able to get the object stored in the user's arrayList so that I can modify or delete them.
Here is the example of my code when I add users to the JTable:
private void jButtonAddAUserActionPerformed(java.awt.event.ActionEvent evt) {
User obj=new User();
obj.setName(jTextFieldName.getText());
obj.setAdress(jTextFieldAdress.getText());
obj.setNumCC(Integer.parseInt(jTextFieldNumCC.getText()));
obj.setTele(Integer.parseInt(jTextFieldTele.getText()));
obj.setUserName(jTextFieldUserName.getText());
obj.setPassword(jTextFieldPassword.getText());
DefaultTableModel model=(DefaultTableModel) jTableUsers.getModel();
model.addRow(new Object[]{
jTextFieldName.getText(),
jTextFieldAdress.getText(),
jTextFieldTele.getText(),
jTextFieldNumCC.getText(),
obj.isAdmin
});
usersList.add(obj);
JOptionPane.showMessageDialog(null,"Data inserted correctly.");
jTextFieldName.setText("");
jTextFieldAdress.setText("");
jTextFieldNumCC.setText("");
jTextFieldTele.setText("");
jTextFieldPassword.setText("");
jTextFieldUserName.setText("");
}
Edit:
Here is the code for removing users already working:
private void jButtonRemoverActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTableInvestidores.getModel();
User u = userList.get(jTableUsers.getSelectedRow());
userList.remove(u);
model.removeRow(jTableUsers.getSelectedRow());
JOptionPane.showMessageDialog(null,"Data removed.");
}
And here is the code for updating user that is still not working, im trying to update it from the jTextFields:
private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTableUsers.getModel();
userList.get(jTableUsers.getSelectedRow());
model.setValueAt(jTextFieldName.getText(), jTableUsers.getSelectedRow(),0);
model.setValueAt(jTextFieldAdress.getText(), jTableUsers.getSelectedRow(),1);
model.setValueAt(jTextFieldPhone.getText(), jTableUsers.getSelectedRow(),2);
model.setValueAt(jTextFieldNumCC.getText(), jTableUsers.getSelectedRow(),3);
User u =userList.get(jTableUsers.getSelectedRow());
JOptionPane.showMessageDialog(null,"Data updated.");
}
Can anyone please give me some help on this? Thanks!
you could use something similar to this. sadly you didn't specify how you want to edit the user.
User u=userList.get(table.getSelectedRow()); //get user for editing
int location=table.getSelectedRow(); //get location in list to maintain order
userList.remove(u); //remove selected user to edit variables
//modify user u
userList.add(location,u); //insert user at previous location in list
model.setRowCount(0); //reset table model
for (int i = 0; i < userList.size(); i++) { //refill table model
User u = userList.get(i); /7get user
Vector<Object> vhelp = new Vector<>(); //create vector to store the values of the variables from user
vhelp.add(/*your data*/); // 1 add per variable that should be displayed in table
model.addRow(vhelp); //add the data to the table model (fills the table with data)
}
your method should look like this:
DefaultTableModel model = (DefaultTableModel) jTableUsers.getModel();
User u = userList.get(jTableUsers.getSelectedRow());
int location=jTableUsers.getSelectedRow();
userList.remove(u);
u.setName(jTextFieldName.getText());
u.setAdress(jTextFieldAdress.getText());
u.setNumCC(Integer.parseInt(jTextFieldNumCC.getText()));
u.setTele(Integer.parseInt(jTextFieldTele.getText()));
//u.isAdmin can't tell what this has to be
userlist.add(location,u);
model.setRowCount(0);
for (int i = 0; i < userList.size(); i++) {
User u = userList.get(i);
Vector<Object> vhelp = new Vector<>();
vhelp.add(u.getName());
vhelp.add(u.getAddress());
vhelp.add(u.getTele());
vhelp.add(u.getNumCC());
vhelp.add(u.isAdmin);
model.addRow(vhelp);
}
JOptionPane.showMessageDialog(null, "Data updated.");
the users are added to my arraylist and JTable.
Don't store the data in two separate places. The data should only be stored in the TableModel of the JTable.
So you can create a custom "User" object to contain the data about each user. Then you can create a custom TableModel to hold "User" object which can be displayed and access by the JTable.
Now what I want is when I choose the JTable row, to be able to get the object stored in the user's arrayList so that I can modify or delete them.
Check out Table Row Model for a step by step approach on create the custom TableModel. It contains all the methods you need to dynamically add, access and delete objects from the TableModel.
I have a JTable defined in this way:
public JTable table_1;
model_3 = new DefaultTableModel();
table_1 = new JTable(model_3);
scrollPane_5.setViewportView(table_1);
Add row:
model_3.addRow(new Object[]{table.getValueAt(row,0) , table.getValueAt(row,1) ,table.getValueAt(row,2) , commentFood });
Remove Row:
model_3.removeRow(row); //row is an integer
Until here, it used to work properly. As you can see this table is defined as public because sometimes I need to fill it up from another JFrame in this way:
takeOrder to = new takeOrder();
//Get data from DB to resultSet
to.table_1.setModel(DbUtils.resultSetToTableModel(resultSet));
If I fill up the table in this way and try to add or remove my model_3, it will not work! Any suggestion that how I can add or remove to the table after using DbUtils.resultSetToTableModel(resultSet) will be appreciated.
As I couldn't find any information on the internet and I saw couple of people asked same question with no answer. I came up with this solution:
if (formOut) {
for (int i = 0; i < table_1.getRowCount(); i++) {
model_3.addRow(new Object[]{table_1.getValueAt(i,0),
table_1.getValueAt(i, 1), table_1.getValueAt(i, 2)});
}
}
formOut = false;
table_1.setModel(model_3);
fromOut is a boolean to check if I have used another model for my table. If so I add data from table to previous model, and then I reference that model to my table. Now I can add to that model as well.
I am trying to implement Summation function of MS EXCEL but not getting a way to get the values from the JTable cells. Can you suggest me some way to get the values from the cells and use it for my function?
For example, how can you get the value -
String data[][] = {{"Value1", "Value2", "Value3"},{"Value4", "Value5", "Value6"},
{"Value7", "Value8", "Value9"},{"Value10", "Value11", "Value12"}};
String col[] = {"Column1", "Column2", "Column3"};
DefaultTableModel model = new DefaultTableModel(data, col);
JTable table = new JTable(model);
...
System.out.println(table.getModel().getValueAt(2, 2)); // row index and column index
...
it gives -
Value9
To get the values from the table, you can implement the interface MouseListener in the anonymous inner class, for example -
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTable target = (JTable) e.getSource();
int rowIndex = target.getSelectedRow();
int columnIndex = target.getSelectedColumn();
System.out.println(target.getModel().getValueAt(rowIndex, columnIndex));
}
});
See also:
How to Write a Mouse Listener
How to Write a List Selection Listener
I use a HashMap to fill a JTable, which is more or less continuously updated:
public Map< Long, MyObject > tableData = new HashMap< Long, MyObject >();
Every time a new element is added to the map the table model is notified:
tableData.put(id, anObject);
AbstractTableModel atm = (AbstractTableModel)model;
atm.fireTableDataChanged();
In Addition I have a TableRowSorter which sorts the rows according to a specific criteria:
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
.
.
.
table.setRowSorter(sorter);
My goal is that the (vertical) scrollbar always jumps to the last added row, which can be somwhere in the mid
of the table because of the sorter probably using this:
table.scrollRectToVisible(table.getCellRect(row,0, true));
The problem is I do not know the index of the row :) Where can I hook in to get this index?
Scrolling to a newly inserted row in a potentially sorted table involves
listening to changes in the table model
converting the rowIndex of the event (it is in model coordiates) to view coordinates
scrolling to the view position
In code:
final JTable table = new JTable();
TableModelListener l = new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
if (TableUtilities.isInsert(e)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int viewRow = table.convertRowIndexToView(e.getFirstRow());
table.scrollRectToVisible(table.getCellRect(viewRow, 0, true));
}
});
}
}
};
table.getModel().addTableModelListener(l);
Two important aspects:
your model implemenation must fire the correct event, that is a insert, not a dataChanged
invoking both index conversion and scrolling guarantees that the table (which is listening to the model as well) has updated all internal state according to the model change.