How to get the stored object from JTable - java

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.

Related

Adding items into tableview without using an instance of any class

I'm designing a project about cataloging something. In this project user must be able to create his own table as he wish. Therefore I do not have any static class and instance of it.
I'm creating a diaglog pane and I can create textfields for user inputs according to column names of database table dynamically but how can i add those user's inputs into the tableView ?
As I can add any String input into the ListView can I add user String inputs into tableView columns?
ListView<String> listView = new ListView();
public ObservableList<String> listCatalogNames = FXCollections.observableArrayList();
listCatalogNames.add("Books");
More details with an example;
There is listview that contains all catalog names and according to lisview selection tableview will be created dynamically center of borderpane.
User have books(name, author, page) and movies(name, year, director, genree) catalogs.
Lets say user selected movies and tableView appeared with 4 columns and clicked add button. Diaglog pane created with 4 textfield. I built everything until that point but I cannot add user's input into the tableView because i dont have any static class for Movies or Books etc.
Is there any way to create dynamic class ?
Please give me an idea and help me about that situation.
here is the github link of our project
Just use String[] storing the Strings for every column of a row (or a similar data structure) as item type for the TableView. It should be simple enough to create a String[] from the inputs and add it to this TableView:
static TableView<String[]> createTable(String... columnNames) {
TableView<String[]> table = new TableView<>();
for (int i = 0; i < columnNames.length; i++) {
final int index = i;
TableColumn<String[], String> column = new TableColumn<>(columnNames[i]);
column.setCellValueFactory(cd -> new SimpleStringProperty(cd.getValue()[index]));
table.getColumns().add(column);
}
return table;
}
Adding a String[] userInputs to a TableView<String[]> table would be done like this:
table.getItems().add(userInputs);
A similar issue (creating a TableView based on the metadata of a ResultSet) can be found here: How to fill up a TableView with database data
Easiest solution that comes to my mind is to make use of polymorphism. You can create a super class of both Book and Movie, let's call it Item. Then you can declare your table to contain Item and cast to one of the concrete classes when you need to.

Show selected row information in another table

Hello everybody I just created two JTable components and two array lists.
The first ArrayList contains questions' data (question ID, question Description, Key answer) and another array list contains options' data (option Id, option description).
First table gets questions data from first array list and shows it.
And each question in this table has multi options.
enter image description here
I want when I select row in questions' table, the options of this question will appear. How can I do that?
Below I post two functions that are used to show data:
private void showQuestions(){
int rowCount= question_table.getRowCount();
Object question[]=null;
DefaultTableModel t = (DefaultTableModel) question_table.getModel();
for(int i=0;i<examQuestions.size();i++){
question =new Object[]{examQuestions.get(i).question_id,examQuestions.get(i).questionDescription,examQuestions.get(i).keyAnswer};
t.addRow(question);
}
question_table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
}
});
}
private void showOption(){
int rowCount = option_table.getRowCount();
Object option[]=null;
DefaultTableModel t = (DefaultTableModel) option_table.getModel();
for(int i = 0;i <=examQuestions.size()-1;i++){
for(int j = 0; j <=examQuestions.get(i).answerOptions.size()-1;j++){
option = new Object[]{ j+1, examQuestions.get(i).answerOptions.get(j)};
t.addRow(option);
}
}
}

Remove highlighted columns and data from jtable

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.

How to add a row to JTable after populating data using DbUtils.resultSetToTableModel?

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.

Manipulating fields in the jTable Java

I have populated my jTable with the following Code. It has two columns, the first has variable name and the second is a list of its dependencies. The user can change the dependencies by selecting them from the list in the jTable.
When the user changes a value, I want to row to be added to another jTable (which would be no user editable. How would I do that?
The code to populate the table is
Vector<Vector> data = new Vector<Vector>();
for (String v : acn.getVariableNames()) {
Vector tmp = new Vector();
tmp.add(v);
ArrayList<String> temp = new ArrayList<String>();
for (String u : acn.getVariableDomain(v)) {
temp.add(u);
}
tmp.add(temp);
data.add(tmp);
}
Vector names = new Vector();
names.add("Variable");
names.add("Domain Value");
DefaultTableModel dt = new DefaultTableModel();
dt.setDataVector(data, names);
jTable2.setModel(dt);
jTable2.getColumnModel().getColumn(1).setCellEditor(new ChangeImpactEditor());
jTable2.getColumnModel().getColumn(1).setCellRenderer(new TableListRenderer());
The way i would do it is to override
public void setValueAt(Object aValue, int rowIndex, int columnIndex);
from your TableModel.
The setValue method get called by the JTable after the user has editted a value
In your overriden method you then can set the value in the other tablemodel

Categories

Resources