Onca
Onca

Reputation: 1135

Java swing jTable not being updated

I built a jTable using NetBeans GUI, and I want to update it inside the constructor of the class. I'm planning to add a search option on the frame so the whole update idea is quite critical for me.

My code:

    public availableTrumps(TrumpistClient TC){
    initComponents();
    availableTrumpsTrumpistClient=TC;
    String result=null;

    String query="SELECT * FROM APP.TRUMPS";

        result=this.availableTrumpsTrumpistClient.WritingReading("sql_select", query);

        if (result.contains("empty")){
            JOptionPane.showMessageDialog(this, "There are now trumps to show.");
        }
        else if (result.contains("error")){
            JOptionPane.showMessageDialog(this, "Error in the connection. Please try again.");
        }
        else{
            int i;
            String []data = result.split("\r\n");
            String [][] data2 = new String [data.length][];
            for (i = 0; i < data.length; i++)
            {
                data2[i] = data[i].split("&");
            }
            String[] columnNames = {"From", "To", "Departure Time", "Remaining Places", "Proposer", "ClosingTime", "Cost Per Seat" };
            this.jTable1 = new JTable(data2,columnNames);
            this.jTable1.setPreferredScrollableViewportSize(new Dimension(500,100));
            this.jTable1.setFillsViewportHeight(true);
            JScrollPane jps = new JScrollPane(jTable1);
            add(jps);
            jTable1.revalidate();

    }

    }

The input two-dimentional array data2 is fine and validated. I added the last 5 rows of the code to see if they help with something. I don't know if they are mandatory and in any case I do not want to change the graphical properties of the jTable I built with the GUI (just the data in it). When I run the program, I see that the jTable remains empty. Why?

Upvotes: 1

Views: 388

Answers (2)

wchargin
wchargin

Reputation: 16047

As others have said, you don't want to create multiple JTable instances. Create one like this:

DefaultTableModel model = new DefaultTableModel(new Object[0][0], 
    new String[]{"From", "To", "etc."});

JTable table = new JTable(model);

Then, when you need to add rows, use

model.addRow(dataForThisRow); // Object

If you want to change a cell:

model.setValueAt(newValue, row, col); // Object, int, int

Or, to remove row i:

model.removeRow(i); // int

For more information, see the DefaultTableModel documentation.


If, for some reason, it is imperative that you recreate the table each time, I believe the problem is that you are calling revalidate without calling repaint.

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

I suggest you use a table model, whenever the data changes you change the model. Build the JTable instance only once, not whenever you need to change the data.

Upvotes: 4

Related Questions