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.