Hi all
I am programming a database-related application in Java. I have to facilitate several different types of queries, but I'd like to use the same JTable to display the results of each query (one at a time, of course).
The problem is that when I'm using one JTable, I can't change the contents of it. I'm stuck with the data that I used to initialize the JTable.
I could not find any methods to update the contents of the JTable. I tried creating a new JTable object and adding that to the panel, then tried repainting/updating the panel & container, but nothing worked.
So I created this very stripped down version of the problem. Currently I am initializing the JTable with column names columnNames1 and rows data1.
When the button is clicked, I want to change the JTable to have column names columnNames2 and rows data2;
public class TestClass extends JFrame{ JPanel panel; JTable table; JScrollPane scrollPane; Container C; JButton testButton; ActionListener changeListener; String[] columnNames1 = {"First Name","Last Name","Age"}; String[] columnNames2 = {"First Name","Last Name","Height"}; Object[][] data1 = { {"Mary", "Campione", "Snowboarding", "5"}, {"Alison", "Huml", "Rowing", "3"}, {"Kathy", "Walrath", "Knitting", "2"}, {"Sharon", "Zakhour", "Speed reading", "20"}, {"Philip", "Milne", "Pool", "10"}}; Object[][] data2 = { {"James", "Keenan", "Hiking", "65"}, {"Josh", "Huml", "Running", "37"}, {"Billy", "Walrath", "Swimming", "21"}, {"Robert", "Zakhour", "Golfing", "88"}, {"Mike", "Milne", "Soccer", "1"}}; public TestClass(){ testButton = new JButton("Change Data"); changeListener = new ChangeListener(); testButton.addActionListener(changeListener); panel = new JPanel(); Container C = getContentPane(); C = getContentPane(); C.add(panel); table = new JTable(data1, columnNames1); scrollPane = new JScrollPane(table); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); panel.add(scrollPane); panel.add(testButton); } class ChangeListener implements ActionListener{ public void actionPerformed(ActionEvent evt){ System.out.println("Change Button pressed"); //change contents of JTable } } public static void main(String[] args){ Frame f = new TestClass(); f.setSize(600,600); f.setVisible(true); f.setTitle("University Database Application"); } }
Any help would be much appreciated. :idea: