File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Updating data in a JTable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Updating data in a JTable" Watch "Updating data in a JTable" New topic

Updating data in a JTable

Talhah Mafawalla

Joined: Nov 05, 2006
Posts: 24
Hi all,

I seem to have an anoying problem. The problem is that when i try to insert data in to a JTable using a JButton the JTable wont update until i resize the frame manually, sometimes this does not work. Though the same code works perfectly on some computers, dont know if it is the JDK version or not. Anyways heres the code:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;

public class TableDemo2 extends JFrame{

Vector columnNames, data;
JButton bt1;

public TableDemo2() {

columnNames = new Vector();

data = new Vector();

JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);

JLabel lb1 = new JLabel("Results of Java Programming", JLabel.CENTER);
lb1.setFont(new Font("Courier", Font.ITALIC + Font.BOLD, 16));

bt1 = new JButton("Show Data");
bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int x = 1; x <= 15; x++){
Vector v1 = new Vector();
v1.addElement("FirstName" + x);
v1.addElement("LastName" + x);
v1.addElement(new Integer(60 + 2 * x));
v1.addElement(new Boolean(true));

JTable table = new JTable(data, columnNames);

add(lb1, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(bt1, BorderLayout.SOUTH);

public static void main(String[] args) {
new TableDemo2();


Sorry if the post is too long, but i need help on this.
Thanks in advance.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
in your actionListener you create a new JTable, but don't do anything with it.

the fact it works on some computers indicates that in your real code you
probably remove the old table from the scrollpane, then add the new one.
in this case it should be
repaint();//sometimes required, sometimes not, safest to have it

you don't really need to create a new JTable, then remove/add, just change
the tableModel

(table will need to be made final, or moved so it is a class field - not local)

//JTable table = new JTable(data, columnNames);
table.setModel(new javax.swing.table.DefaultTableModel(data, columnNames));
Talhah Mafawalla

Joined: Nov 05, 2006
Posts: 24
Thanks alot Michael that has helped alot, i think im on the right path using table models rather than adding data direct to the jtable.

Thanks alot again

I agree. Here's the link:
subject: Updating data in a JTable
It's not a secret anymore!