Update JTable using DefaultTableModel

0
I understand that the use of DefaultTableModel is almost abominable, but I used this template and now I have no time to change to a TableModel (which I have not learned yet), is there any way to update a table of a class in View , after a method of create no Dao? The system is in Java, using Javax.Swing MVC.

Creating the main screen and JTable data

@Override
public void actionPerformed(ActionEvent ae) {
    if (ae.getSource().equals(btnentrar)) {

        if (txtsenha.getPassword().length == 0 || txtuser.getPassword().length == 0) {
            JOptionPane.showMessageDialog(frame, "Preencha os campos");
        } else {

            UserDao userDao = new UserDao();
            Usuario usuario = new Usuario();
            usuario = userDao.Login(new String(txtuser.getPassword()), new String(txtsenha.getPassword()));

            if (usuario != null) {
                JOptionPane.showMessageDialog(frame, "Conectado");
                Principal principal = new Principal();
                principal.initComponents(usuario);
                principal.carregarDadosProdutosJTable();
                frame.dispose();
            } else {
                JOptionPane.showMessageDialog(frame, "Não foi possível efetuar login.");
            }

        }

    }
}

Package: View Class: Login

A simple login screen, this is the Enter button action.

Method for loading data into JTable

public void carregarDadosProdutosJTable() {
    ItemDao itemDao = new ItemDao();
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    model.setRowCount(0);
    ArrayList<Item> itens = (ArrayList<Item>) itemDao.listarProdutos();
    for (Item c : itens) {
        model.addRow(new Object[]{c.getCodigo(), c.getDescricao(), c.getCategoria(), c.getEstoque()});
    }
}

Package: View Class: Main

If I try to call this method again, NetBeans displays a Null error in the third line of this code (DefaulTableModel model = ...)

New Save Method

public void salvarItem(Item item) {
    try {
        // cria um preparedStatement
        pstm = con.prepareStatement("insert into produto (prodescricao,procategoria,proestoque) values (?,?,?)");

        pstm.setString(1, item.getDescricao());
        pstm.setString(2, item.getCategoria());
        pstm.setInt(3, item.getEstoque());
        pstm.execute();
        pstm.close();
        con.close();
        JOptionPane.showMessageDialog(null, "Item registrado com sucesso.");
    } catch (SQLException erro) {
        JOptionPane.showMessageDialog(null, "Erro de sql " + erro.getMessage());
    }
}

Package: Dao Class: ItemDao

Ideally, I think it would be to update after saving a new item, since it would change the list of products, or items, and the old table would no longer be correct. Is there any way I can do this without having to implement a TableModel? I'm aware of how much better it is to use a TableModel, though, I'm not having too much time on this project for that. I am a beginner in the area, if you can simplify the explanation, thank you.

    
asked by anonymous 14.06.2016 / 18:34

2 answers

1

First, I recommend declaring the JTable template in the class, so whenever you need it, just do table.getModel(model) The error is due to not having declared the JTable in the constructor ( public (classe utilizada) ) In the class must DefaultTableModel model = new DefaultTableModel(String[](Seus campos) and in the constructor make (nomedatabela) = new JTable(model) This should solve the problem. If it does not resolve, I apologize but I'm also a beginner

'

    
23.06.2017 / 12:51
-2
public void carregarDadosProdutosJTable() {
    ItemDao itemDao = new ItemDao();

    table.getColumnModel().getColumn(0).setPreferredWidth(4);
    table.getColumnModel().getColumn(1).setPreferredWidth(220);
    table.getColumnModel().getColumn(2).setPreferredWidth(40);
    table.getColumnModel().getColumn(3).setPreferredWidth(40);            
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    model.setRowCount(0);
    ArrayList<Item> itens = (ArrayList<Item>) itemDao.listarProdutos();

    try{
        for (Item c : itens) {
        model.addRow(new Object[]{c.getCodigo(), c.getDescricao(), c.getCategoria(), c.getEstoque()});
    }
    }catch(Exception erro){
        erro.printStackTrace();
         JOptionPane.showMessageDialog(null, "A tabela não pôde ser carregada");
     }
}

See which error will appear, or thing, put your method that lists the items

    
03.01.2018 / 00:48