Update Jtable using Defaulttablemodel

Asked

Viewed 1,217 times

0

I understand that the use of Defaulttablemodel is almost abhorrent, however, I used this model and now I have no time to change to a Tablemodel (which I haven’t learned to use yet), is there any way to update a table of a class in the View, after a create method in Dao? The system is in Java, using Javax.Swing MVC.

Creation of 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 Login button action.

Method to load data to 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:Home

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

Save New Item 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 to do this without having to implement a Tablemodel? I am aware of how much better it is to use a Tablemodel, but I do not have much time on this project. I am a beginner in the area, if you can simplify the explanation thank you.

  • Do as you said, after saving the data call the method carregarDadosProdutosJTable()

  • @Diegoaugusto "Exception in thread "AWT-Eventqueue-0" java.lang.Nullpointerexception" in the line "Defaulttablemodel model = (Defaulttablemodel) table.getModel();" of the Load Method()

  • You’re calling this method in the view right?

  • @Diegoaugusto in the creation of Jtable I call in the view, after Login, the update I tried to call in Dao, but it did not work.

  • Do you have a button that saves you right? This button has an action, call it after saving it within the button action

  • @Diegoaugusto The same mistake.

  • Before calling the method carregarDadosProdutosJTable() your table has something loaded or this method is the one to load?

  • @diegofm After validating Login I call initComponents() to create the screen, and then load DadosProductJTabel() to load the table. Is working, the problem is updating her.

  • I do not understand your problem, the question does not make clear where the origin of the error is. In fact, it says yes, but you’re telling us something else. At what point the nullpointer happens?

  • @diegofm I have a table, and I need to update it. Researching I found some forms, but all are with Tablemodel, which I’m not using, even though I know it’s better. I was wondering if there is a way to update this table using Defaulttablemodel.

  • 2

    No tablemodel, impossible. If I understand correctly, the problematic method loads the table, but if called a second time, does it accuse error? It is difficult to help you, especially without a [mcve] to be able to simulate the problem or analyze the operation of your program better.

  • @diegofm is exactly that, initially it works, but if you try to call again you have the problem. It has how to mark a comment as a response?

  • No, you’ve solved the problem?

  • @diegofm It was a question, I wanted to know if there was any way, if not, I already got my answer.

  • Gabriel, is your table so complex? Creating a tablemodel is simpler than it looks, in this question I explain step-by-step how to create one, it’s very simple. Perhaps it is better to spend a little time creating one, than to have a headache and lose a lot of time later giving maintenance. And any questions, you can ask here on the site also. :)

  • 1

    @diegofm haha, is the hard head that does not leave even, but by the numerous limitations of the Defaulttablemodel I will need the same Tablemodel. Thank you for the guidelines.

Show 11 more comments

2 answers

1

First, I recommend declaring the Jtable model in the class, so whenever you need it, just do it table.getModel(model) The error is due to not having declared Jtable in the constructor (public (classe utilizada)) In class you must do DefaultTableModel model = new DefaultTableModel(String[](Seus campos) and in the builder do (nomedatabela) = new JTable(model) This should solve the problem. If not solve, I beg no excuse but I am also beginner

`

-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, puts your method that lists the items

  • I don’t think that has anything to do with the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.