Reputation: 11
I'm trying to make a program in which a displayed JTabel changes according to the user's choice of files. They input this by clicking a button that calls on some method(), that returns a new JTable. But I cannot get the table in the GUI to update.
public class program extends JFrame{
public JPanel panel;
public JTable table;
public program{
this.panel = new JPanel();
panel.setLayout(new FlowLayout());
JTable table = new JTable();
panel.add(table);
JButton button = new JButton();
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser();
if(browser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
table = method(); //some method that changes the values of the table
panel.revalidate();
panel.repaint();
}
};
});
panel.add(button);
setContentPane(panel);
setVisible(true);
}
private static JTable method(){ ... }
public static void main(String[] args){
program something = new program();
}
}
I'm not entirely sure on the differences between validate()
, revalidate()
, and repaint()
despite reading a lot about them. I've also tried table.revalidate()
ect. instead, but that's no good either.
EDIT: Thanks for the help, it's all sorted now :) I rewrote my ActionListener as "instructed" by resueman:
JButton button = new JButton();
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser();
if(browser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
panel.remove(table);
table = method();
panel.add(table);
panel.revalidate();
panel.repaint();
}
};
});
I've hesitated to do this since FlowLayout would place it somewhere I didn't want it. But with additional JPanels inside the primary one, it can be controlled.
Thanks for the comments, you all just saved my day!
Upvotes: 1
Views: 1374
Reputation: 13858
If you could redesign to change the tables contents you wouldn't need to worry about manually repainting.
Try to modify your code to
table.setModel (method());
And model ()
returning a TableModel
instead of a JTable
.
You don't see any changes because the old JTable
is still added to your panel. You'd have to remove old / add new if you insist of keeping your method the way it is.
Good Luck.
Upvotes: 2