Hack Forums
[Java] how to update Jtable after inserting data into it. - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Java] how to update Jtable after inserting data into it. (/showthread.php?tid=4977541)



how to update Jtable after inserting data into it. - Heulen - Sep 6, 2015

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?


* - eSp0rt - Sep 6, 2015

tableModel.fireTableDataChanged() ?


* - WildeThing - Sep 6, 2015

Use a DefaultTableModel and add data to the model and it should update automatically.


* - c0ffee - Sep 6, 2015

Your code looks nice but maybe it's better to not use dutch in the future?
Spoiler (Click to View)


* - Heulen - Sep 7, 2015

(Sep 6, 2015 07:48 AM)eSp0rt Wrote:  tableModel.fireTableDataChanged() ?

how would I use that? ๐Ÿคจ
I'm a pretty big noob sorry


* - eSp0rt - Sep 7, 2015

(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.


* - Heulen - Sep 7, 2015

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

so, where in the code? at the addBtn actionlistener?


* - eSp0rt - Sep 7, 2015

(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)