Add line in JTable when clicking the button

3

I'm starting to create an interface in Java, an example I'm trying to do is to have a form with textField nome and email , and clicking the Enviar button will% for my textField , but I am not able to manipulate my table, it 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() {
            @Override
            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
                    modelo.addColumn("Email");

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

    // cria minha interface
    public static void main(String[] args) {
        JFrame frame = new JFrame("teste01");
        frame.setContentPane(new teste01().painelFundo);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}
    
asked by anonymous 30.03.2016 / 20:37

2 answers

0

Since you're using DefaulTableModel , just call the addRow() , passing a vector of Strings to the value of the two fields:

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

The DefaultTableModel itself will notify listeners and redraw their table with the new line.

    
30.03.2016 / 22:50
0

I've been trying the same thing and in the action of the button to add I put the following code.

DefaultTableModel nada = (DefaultTableModel) jTable1.getModel();

 nada.addRow(new Object[]{null,null});
    
31.05.2017 / 01:25