I expect once combobox has been selected, the JTable will change.
Here is my part of code:
……
chooseAccoutingItemComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeTable();
jScrollpane.revalidate();
jScrollpane. repaint();
}
private void changeTable() {
JTable accountTable2 = new JTable(accountBook.getRowData(startYear, startMonth, endYear, endMonth, (AccountingItem) chooseAccoutingItemComboBox.getSelectedItem()), accountBook.getColumnNames());
accountTable = accountTable2;
}
});
accountTable = new JTable(accountBook.getRowData(startYear, startMonth, endYear, endMonth, accountintItem), accountBook.getColumnNames());
jScrollpane = new JScrollPane(accountTable);
add(jScrollpane, BorderLayout.CENTER);
……
And now when I selected item in combobox, the JTable didn't change. WHY?
答案 0 :(得分:4)
Yours is a basic core Java mistake, one which has nothing to do with Swing, revalidate or repaint, and all to do with the core distinction of what is the difference between a Java reference variable and a reference (or object):
Changing the object referenced by a variable will have no effect on the original object. For example, your original displayed JTable object, the one initially referenced by the accountTable variable is completely unchanged by your changing the reference that the accountTable variable holds, and for this reason your GUI will not change. Again understand that it's not the variable that's displayed, but rather the object
To achieve your goal you will instead want to change the state of the displayed JTable. Do this by changing its model.
i.e., by doing something like:
private void changeTable() {
// create a new table model
MyTableModel newModel = new MyTableModel(pertinentParameters);
// use the new model to set the model of the displayed JTable
accountTable.setModel(newModel);
}
Use the parameters that you're currently passing into your new JTable:
accountBook.getRowData(startYear, startMonth, endYear, endMonth,
(AccountingItem) chooseAccoutingItemComboBox.getSelectedItem()),
accountBook.getColumnNames()
to create the new TableModel instead.
In fact you might even be able to create a DefaultTableModel directly with this data, something like:
DefaultTableModel model = new DefaultTableModel(accountBook.getRowData(
startYear, startMonth, endYear, endMonth,
(AccountingItem) chooseAccoutingItemComboBox.getSelectedItem()),
accountBook.getColumnNames());
accountTable.setModel(model);