Boa noite, colegas.
Eu estou desenvolvendo um programa em Java simulando um mercado. A ideia principal é o usuário entrar com um usuário e uma senha. Caso a pessoa entre com a senha “admin” e o usuário “administrador” esta pessoa terá acesso ilimitado ao programa. Caso ela use a senha “1234” e o usuário “convidado” ela também terá acesso ao programa, porém será um acesso restrito.
O programa está bom, mas acabei encontrando alguns erros: O programa aceita qualquer nome de usuário, mesmo que o mesmo não exista e quando uma das opções restritas a convidados é selecionada aparece o seguinte erro:
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at projeto.MenuPrincipal$3.actionPerformed(MenuPrincipal.java:92)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
at projeto.MenuPrincipal$3.actionPerformed(MenuPrincipal.java:92)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Os únicos problemas são esses. Eu ficaria muito grato se alguém pudesse me ajudar, pois estou trabalhando neste programa a dias, e não quero perde-lo por um errinho bobo como este. A sintaxe das classes ficam abaixo:
Classe login:
package projeto;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.tools.Tool;
public class Login extends JFrame
{
public JTextField tfLogin;
private JLabel lbSenha;
private JLabel lbLogin;
private JButton btLogar;
private JLabel btCadastrar;
private JButton btCancelar;
public String password, user;
public JPasswordField pfSenha;
private static Login frame;
public Login()
{
inicializarComponentes();
definarEventos();
}
Cadastro cadastro = new Cadastro();
private void inicializarComponentes()
{
setTitle("Login no Sistema");
setBounds(0,0,300,350);
setLayout(null);
tfLogin= new JTextField(10);
pfSenha = new JPasswordField();
lbSenha = new JLabel("Senha");
lbLogin = new JLabel("Login");
btLogar = new JButton("Logar");
btCancelar = new JButton("Cancelar");
btCadastrar = new JLabel("<html><br>Senha de administrador: admin;<br> Usuário de administrador: administrador;"
+ "<br><br>Senha de convidado: 1234;<br> Usuário de convidado: convidado</html>");
tfLogin.setBounds(100, 30, 120, 25);
lbLogin.setBounds(30, 30, 80, 25);
lbSenha.setBounds(30, 75, 80, 25);
pfSenha.setBounds(100, 75, 120, 25);
btLogar.setBounds(20, 120, 100, 25);
btCancelar.setBounds(125, 120, 100, 25);
btCadastrar.setBounds(20, 150, 205, 120);
add(tfLogin);
add(lbSenha);
add(lbLogin);
add(btLogar);
add(btCancelar);
add(pfSenha);
add(btCadastrar);
}
private void definarEventos()
{
btLogar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String user2 = String.valueOf(tfLogin.getText());
String senha = String.valueOf(pfSenha.getPassword());
if(user2.equals("1") || user2.equals("administrador") && senha.equals("1")||senha.equals("admin")){
frame.setVisible(false);
MenuPrincipal.abrir();
user2 = user;
senha = password;
}
else
{
JOptionPane.showMessageDialog(null, "Login ou Senha incorretas!");
}
}
}
);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
frame = new Login();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((tela.width - frame.getSize().width) / 2,
(tela.height - frame.getSize().height) / 2);
frame.setVisible(true);
}
}
);
}
}
Classe MenuPrincipal:
package projeto;
import java.awt.;
import java.awt.event.;
import javax.swing.*;
public class MenuPrincipal extends JFrame
{
private Container contentPane;
private JMenuBar mnBarra;
private JMenu mnArquivo, mnExemplos;
private JMenuItem miSair, miCalculadora, miMercado;
private JLabel texto;
public MenuPrincipal()
{
inicializarComponentes();
definirEventos();
}
private void inicializarComponentes()
{
//Barra e características do menu:
setTitle("Menu Principal");
setBounds(0, 0, 600, 400);
contentPane = getContentPane();
mnBarra = new JMenuBar();
mnArquivo = new JMenu("Arquivo");
mnArquivo.setMnemonic('A');
mnExemplos = new JMenu("Exemplos");
mnExemplos.setMnemonic('E');
miSair = new JMenuItem("Sair", new ImageIcon("sair.jpg"));
miSair.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, ActionEvent.ALT_MASK));
miCalculadora = new JMenuItem("Calculadora");
mnArquivo.add(miSair);
mnExemplos.add(miCalculadora);
mnBarra.add(mnArquivo);
mnBarra.add(mnExemplos);
setJMenuBar(mnBarra);
miMercado = new JMenuItem("Processamento de compras");
mnExemplos.add(miMercado);
//Texto:
setLayout(new GridLayout(1,10,10,10));
contentPane.setBackground(new Color(250, 250, 250));
texto = new JLabel("<html><h1>Bem vindo ao Twin Pines Mall! O mercado do futuro!</h1><br>Utilizando este programa você poderá<br> "
+ "desfrutar das ferramentas essenciais para qualquer mercado. Mas antes de utilizar, vamos ver um pouco"
+ "sobre a história de nosso mercado.<br>"
+ "<br><h2>História do Twin Pines Mall</h2><br>O Twin Pines Mall foi inaugurado em 1985, por um empresário. O mercado recebeu este"
+ " nome por conta do antigo dono<br> do terreno, o senhor Otis Peabody, ter como hobby a plantação de pinheiros(pines). Para a nomeação<br> "
+ "do local foram escolhidos 2 pinheiros em especial, que eram praticamente gêmeos (twin). O local foi palco de muitas coisas<br> "
+ "empolgantes, como a primeira viajem temporal feita pelo Doutor Emmett L. Brown e pelo seu fiel ajudante, Marty McFly<br>"
+ "<br><h2>Utilização do programa</h2><br>Para utilizar o programa, selecione uma função na barra de opções. Atualmente temos apenas as opções<br>"
+ "Cadastro de funcionários e calculadora", SwingConstants.LEADING);
texto.setFont(new Font("Arial Narrow", Font.LAYOUT_LEFT_TO_RIGHT, 20));
texto.setForeground(Color.black);
add(texto);
texto.setBounds(10, 10, 10, 100);
}
private void definirEventos()
{
miSair.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
miCalculadora.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Calculadora calculadora = new Calculadora();
contentPane.removeAll();
contentPane.add(calculadora);
contentPane.validate();
}
});
miMercado.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Login dados = new Login();
if(dados.user.equals("administrador") || dados.password.equals("admin")){
Pedidos compras = new Pedidos();
contentPane.removeAll();
contentPane.add(compras);
contentPane.validate();
}
else{
JOptionPane.showMessageDialog(null, "Esta função não está disponível para convidados. Tente com a conta de administrador.");
}
}
});
}
public static void abrir()
{
MenuPrincipal frame = new MenuPrincipal();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((tela.width - frame.getSize().width) / 2,
(tela.height - frame.getSize().height / 2));
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
Classe pedidos:
package projeto;
import javax.swing.;
import javax.swing.table.;
import javax.swing.border.TitledBorder;
import java.awt.;
import java.awt.event.;
import java.text.DecimalFormat;
public class Pedidos extends JPanel {
private JPanel pnPrincipal, pnTable;
private JButton btRemover, btAdicionar;
private JScrollPane scrollTable;
private JTable table;
private JLabel lbNumero, lbTotal, lbProduto, lbPrecoUnitario, lbQuantidade;
private JTextField tfNumero, tfTotal, tfProduto, tfPrecoUnitario, tfQuantidade;
DecimalFormat df = new DecimalFormat("#,###.00");
public Pedidos() {
inicializarComponentes();
definirEventos();
}
private void inicializarComponentes() {
setLayout(null);
lbProduto = new JLabel("Produto");
lbQuantidade = new JLabel("Quantidade");
lbPrecoUnitario = new JLabel("PrecoUnitario");
lbNumero = new JLabel("Numero do Pedido:");
lbTotal = new JLabel("Total do Pedido:");
tfProduto = new JTextField();
tfPrecoUnitario = new JTextField();
tfQuantidade = new JTextField();
tfNumero = new JTextField();
tfTotal = new JTextField();
tfTotal.setEnabled(false);
tfTotal.setHorizontalAlignment(JTextField.RIGHT);
btAdicionar = new JButton("Adicionar");
btAdicionar.setToolTipText("Adiciona um item ao pedido");
btRemover = new JButton("Remover");
btRemover.setToolTipText("Remove os itens selecionados");
lbProduto.setBounds(15, 40, 100, 25);
lbQuantidade.setBounds(225, 40, 100, 25);
lbPrecoUnitario.setBounds(310, 40, 100, 25);
lbNumero.setBounds(15, 10, 120, 25);
lbTotal.setBounds(278, 360, 100, 25);
tfProduto.setBounds(15, 65, 200, 25);
tfQuantidade.setBounds(225, 65, 50, 25);
tfPrecoUnitario.setBounds(310, 65, 80, 25);
tfNumero.setBounds(130, 10, 50, 25);
tfTotal.setBounds(375, 360, 100, 25);
btAdicionar.setBounds(15, 100, 100, 22);
btRemover.setBounds(125, 100, 100, 22);
pnPrincipal = new JPanel();
pnPrincipal.setLayout(null);
pnPrincipal.setBounds(0, 0, 500, 400);
pnPrincipal.add(lbNumero);
pnPrincipal.add(lbTotal);
pnPrincipal.add(tfNumero);
pnPrincipal.add(tfTotal);
pnPrincipal.add(lbProduto);
pnPrincipal.add(tfProduto);
pnPrincipal.add(lbQuantidade);
pnPrincipal.add(tfQuantidade);
pnPrincipal.add(lbPrecoUnitario);
pnPrincipal.add(tfPrecoUnitario);
pnTable = new JPanel(new BorderLayout());
pnTable.setBorder(new TitledBorder("Itens do Pedido"));
scrollTable = new JScrollPane();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
pnPrincipal.add(btAdicionar);
pnPrincipal.add(btRemover);
DefaultTableModel tableModel = new DefaultTableModel(
new String[]{"Produto", "Qtde", "Preco Un.", "Total"},0) {
public boolean isCellEditable(int row, int col) {
if (col == 3) {
return false;
}
return true;
}
};
table = new JTable(tableModel);
DefaultTableCellRenderer alinhaDireita = new DefaultTableCellRenderer();
alinhaDireita.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumnModel().getColumn(0).setPreferredWidth(150);
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(1).setPreferredWidth(50);
table.getColumnModel().getColumn(1).setResizable(false);
table.getColumnModel().getColumn(1).setCellRenderer(alinhaDireita);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setResizable(false);
table.getColumnModel().getColumn(2).setCellRenderer(alinhaDireita);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setResizable(false);
table.getColumnModel().getColumn(3).setCellRenderer(alinhaDireita);
table.getTableHeader().setReorderingAllowed(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
scrollTable.setViewportView(table);
pnTable.add(scrollTable);
pnTable.setBounds(10, 130, 470, 230);
pnPrincipal.add(pnTable);
add(pnPrincipal);
}
private void definirEventos() {
btAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tfProduto.getText().equals("") || tfQuantidade.getText().equals("") ||
tfPrecoUnitario.getText().equals("")){
JOptionPane.showMessageDialog(pnTable, "Preencha todos os campos!");
return;
}
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
dtm.addRow(new Object[]{tfProduto.getText(), tfQuantidade.getText(),
tfPrecoUnitario.getText(), "" + df.format(Integer.parseInt(
tfQuantidade.getText()) * Double.parseDouble(tfPrecoUnitario.getText()))});
limparCampos();
calcularTotal();
}
});
btRemover.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[] linhas = table.getSelectedRows();
DefaultTableModel dtm = (DefaultTableModel) table.getModel();
for (int i = (linhas.length - 1); i >= 0; --i) {
dtm.removeRow(linhas[i]);
}
calcularTotal();
}
});
}
private void calcularTotal() {
double total = 0;
for (int linha = 0; linha < table.getRowCount(); linha++) {
String valor = "" + table.getValueAt(linha, 3);
valor = valor.replace(".", "");
valor = valor.replace(",", ".");
total += Double.parseDouble(valor);
}
tfTotal.setText("" + df.format(total));
}
private void limparCampos() {
tfProduto.setText("");
tfQuantidade.setText("1");
tfPrecoUnitario.setText("");
tfProduto.requestFocus();
}
}
Agradeço a atenção de todos.