java – Add row in JTable on button click


I'm starting with interface creation in Java, an example I'm trying to do is to have a form with textField nome and email , and when I click the Enviar data from these textField goes to my JTable , but I'm not able to manipulate my table , follows the code of the last attempt:

import java.awt.GridLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/** * @author Rosicléia Frasson */
public class teste01 extends JFrame {

    JPanel painelFundo;
    JTable tabela; // minha tabela
    private JTextField nome;
    private JLabel txtnome;
    private JLabel txtemail;
    private JTextField email;
    private JButton enviar;
    private JButton cancelar;

    DefaultTableModel modelo = (DefaultTableModel) tabela.getModel(); //pega modelo da tabela

    private int dado = 0;

    public teste01() {

        enviar.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if(!nome.getText().equals("") && !email.getText().equals(""))
                    nome.setText("stack"); // apenas para ver se entrou na condição

                    modelo.addColumn("Nome"); // era para adicionar as colunas

                   /* dados[dado][0] = nome.getText();
                    dados[dado][1] = email.getText();
                    dado += 1;
                    tabela = new JTable(dados, colunas);
        cancelar.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
        painelFundo.addComponentListener(new ComponentAdapter() {

    // cria minha interface
    public static void main(String[] args) {
        JFrame frame = new JFrame("teste01");
        frame.setContentPane(new teste01().painelFundo);


As you are using DefaulTableModel , just call the addRow() method, passing a Strings vector with the value of the two fields:

String[] novaLinha = {nome.getText(), email.getText()};

The DefaultTableModel itself will take care of notifying the listeners and redrawing your table with the new row.

Scroll to Top