Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

how to update Jtable after inserting data into it.

This is my Table class
Code
package view;

import java.awt.*;
import java.sql.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;

import java.awt.Dimension;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import Database.Database;

public class Table extends JPanel {
    Database db;
    JScrollPane scrollPane;

    public Table(Database db) {
        this.db = db;
        JTable table = maakTabel("Crocodile");

        scrollPane = new JScrollPane(table);
        this.add(scrollPane);

        JPanel buttonPanel = new JPanel();
        this.add(buttonPanel, BorderLayout.SOUTH);
    }

    public void veranderTabel(String animalType) {
        // hoe verwijder je een tabel
        // hoe voeg je een nieuwe tabel toe
        JTable table = maakTabel(animalType);

        this.remove(scrollPane);
        scrollPane = new JScrollPane(table);
        this.add(scrollPane);
    }

    public JTable maakTabel(String animalType) {
        ArrayList columnNames = new ArrayList();
        ArrayList data = new ArrayList();

        try {
            ResultSet rs = db.getAllAnimals();
            //ResultSet rs = db.getAnimalType(animalType);
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            // Get column names
            for (int i = 1; i <= columns; i++) {
                columnNames.add(md.getColumnName(i));
            }
            // Get row data
            while (rs.next()) {
                ArrayList row = new ArrayList(columns);

                for (int i = 1; i <= columns; i++) {
                    row.add(rs.getObject(i));
                }
                data.add(row);
            }
        } catch (SQLException e) {
        }

        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();

        for (int i = 0; i < data.size(); i++) {
            ArrayList subArray = (ArrayList) data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++) {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }

        for (int i = 0; i < columnNames.size(); i++)
            columnNamesVector.add(columnNames.get(i));

        // Create table with database data
        JTable table = new JTable(dataVector, columnNamesVector) {
            public Class getColumnClass(int column) {
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);

                    if (o != null) {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        return table;
    }
}

This is my DetailsPanel class where I add an animal to the database with the addBtn

Code
package view;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import mammels.Elephant;
import mammels.Human;
import reptiles.Crocodile;
import Database.Database;
import animals.Animal;

@SuppressWarnings("serial")
public class DetailsPanel extends JPanel {

    JLabel firstnameLabel = new JLabel("Firstname: ");
    JLabel weightLabel = new JLabel("Weight: ");
    JLabel lastnameLabel = new JLabel("Lastname: ");
    JLabel genderLabel = new JLabel("Female: ");

    String[] petStrings = { "Type", "Elephant", "Human", "Crocodile" };

    JComboBox<?> selector = new JComboBox<Object>(petStrings);
    JTextField firstnameField = new JTextField(10);
    JTextField weightField = new JTextField(10);
    JTextField lastnameField = new JTextField(10);

    JTextField bodycoveringField = new JTextField(10);
    // JTextField genderField = new JTextField(10);
    JTextField errorField = new JTextField(20);
    JRadioButton maleButton = new JRadioButton("Male");
    JRadioButton femaleButton = new JRadioButton("Female");

    ButtonGroup group = new ButtonGroup();
    {
        group.add(maleButton);
        group.add(femaleButton);
    }

    JButton addBtn = new JButton("Add");

    public DetailsPanel(Database db) {

        add(selector);
        lastnameField.setEditable(false);

        selector.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                @SuppressWarnings("unchecked")
                JComboBox<String> combo = (JComboBox<String>) e.getSource();

                String geselecteerdeType = (String) combo.getSelectedItem();
                if (geselecteerdeType.equals("Human")) {
                    // aanzetten lastname field
                    lastnameField.setEditable(true);
                } else {
                    // uitzetten lastname field
                    lastnameField.setEditable(false);
                    lastnameField.setText("");
                }
            }
        });

        addBtn.setMaximumSize(new Dimension(120, 30));
        addBtn.setPreferredSize(new Dimension(120, 30));

        addBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {

                String firstName = firstnameField.getText();
                if (firstName.equals("")) {
                    errorField.setText("Vul een naam in");
                    return;
                }

                double weight;
                try {
                    weight = Double.parseDouble(weightField.getText());
                } catch (Exception e) {
                    errorField.setText("Vul een getal in bij gewicht");
                    return;
                }

                boolean female;
                if (maleButton.isSelected()) {
                    female = false;
                } else if (femaleButton.isSelected()) {
                    female = true;
                } else {
                    errorField.setText("Kies een geslacht");
                    return;
                }

                Animal animal = null;
                String animalType = (String) selector.getSelectedItem();

                switch (animalType) {
                    case "Human":        boolean married = false;
                        String lastName = lastnameField.getText();
                        if (lastName.equals("")) {
                        errorField.setText("Vul de achternaam in");
                        return;
                        }
                        animal = new Human(firstName, lastName, married, weight, female);
                        break;
                    case "Crocodile":    animal = new Crocodile(firstName, weight, female);
                        break;
                    case "Elephant":    animal = new Elephant(firstName, weight, female);
                        break;
                    default:            errorField.setText("Kies een type");
                        System.out.println(animalType);
                        return;                        
                }

                db.addAnimal(animal);

            }
        });

        setGrid();
    }

    public void setGrid() {
        setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();

        // textfields

        gc.gridx = 2;
        gc.gridy = 0;
        add(firstnameField, gc);

        gc.gridx = 2;
        gc.gridy = 1;
        add(lastnameField, gc);

        gc.gridx = 2;
        gc.gridy = 2;
        add(weightField, gc);

        gc.gridx = 5;
        gc.gridy = 0;
        // gc.gridheight = 3;
        // gc.fill = GridBagConstraints.VERTICAL;
        add(addBtn, gc);

        gc.gridx = (int) 3.5;
        gc.gridy = 1;
        add(maleButton, gc);

        gc.gridx = 4;
        gc.gridy = 1;
        add(femaleButton, gc);

        // textlabels

        gc.gridx = 0;
        gc.gridy = 0;
        add(selector, gc);

        gc.gridx = 1;
        gc.gridy = 0;
        add(firstnameLabel, gc);

        gc.gridx = 1;
        gc.gridy = 1;
        add(lastnameLabel, gc);

        gc.gridx = 1;
        gc.gridy = 2;
        add(weightLabel, gc);

errorField.setEditable(false);
        gc.gridx = 3;
        gc.gridy = 2;
        gc.gridwidth =3;
        add(errorField, gc);
    }
}
Now when I press addBtn it checks if all the info is correct and then it does db.addAnimal(animal);

After that I want my jtable that contains all info about the animals to refresh.

How do I do this?
[Image: MXEbkQu.gif]

tableModel.fireTableDataChanged() ?
Use a DefaultTableModel and add data to the model and it should update automatically.
Your code looks nice but maybe it's better to not use dutch in the future?
Spoiler (Click to View)
(Sep 6, 2015 07:48 AM)eSp0rt Wrote:  tableModel.fireTableDataChanged() ?

how would I use that? 🤨
I'm a pretty big noob sorry
[Image: MXEbkQu.gif]

(Sep 7, 2015 05:39 AM)Heulen Wrote:  how would I use that? 🤨
I'm a pretty big noob sorry

When you put your element add this.
(Sep 7, 2015 06:15 AM)eSp0rt Wrote:  When you put your element add this.

so, where in the code? at the addBtn actionlistener?
[Image: MXEbkQu.gif]

(Sep 7, 2015 06:22 AM)Heulen Wrote:  so, where in the code? at the addBtn actionlistener?

At the end of your addAnimal method maybe? (im on phone is hard to see the code)


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by mattApr 1, 2017 08:29 PM 2 177 Apr 1, 2017 08:29 PM
Last Post: matt
[C#] by Elite Hacker 69Dec 4, 2016 08:46 PM 11 175 Dec 4, 2016 08:46 PM
Last Post: Elite Hacker 69
[Python] by datguy.devSep 16, 2016 11:34 AM 2 75 Sep 16, 2016 11:34 AM
Last Post: datguy.dev