Skip to main content
2 de 8
removeu 1 caractere do conteúdo; tags editadas
Math
  • 31,3mil
  • 15
  • 95
  • 132

colocar permissão no login com restrição de acesso

Estou usando um código que já era feito por alguém, fiz algumas modificações a respeito do que eu queria. Esse código tem 2 tipos de acesso "Administrador e Funcionario" gostaria que quando a pessoa entrasse com o login do tipo Funcionário ela não conseguisse ver os seguintes itens (jMenu2,jMenuItem12,jMenuItem13) que se encontra na jframe "Menu" que abre logo após efetuar o login. Alguém poderia me dar um força? obrigado!!

Segue o código

package Telas;

import Classes.SQLConnection;
import com.sun.glass.events.KeyEvent;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author rafae
 */
public class Login extends javax.swing.JFrame {

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    /**
     * Creates new form Login
     */
    public Login() {
        initComponents();
        setIcon();
SwingUtilities.invokeLater(new Runnable() { public void run() { LoginUsuario.requestFocus(); } });  
        conn = SQLConnection.java_db();
        Toolkit toolkit = getToolkit();
        Dimension size = toolkit.getScreenSize();
        setLocation(size.width / 2 - getWidth() / 2,
                size.height / 2 - getHeight() / 2);
        currentDate();
    }

    public void currentDate() {
        Calendar cal = new GregorianCalendar();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        lbl_data.setText(day + "/" + (month + 1) + "/" + year);

        //HORA
        int second = cal.get(Calendar.SECOND);
        int minute = cal.get(Calendar.MINUTE);
        int hour = cal.get(Calendar.HOUR);

        lbl_hora.setText(hour + ":" + (minute) + ":" + second);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        LoginUsuario = new javax.swing.JTextField();
        LoginSenha = new javax.swing.JPasswordField();
        txt_divisao = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        LoginSalvar = new javax.swing.JButton();
        LoginEntrar = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        lbl_data = new javax.swing.JMenu();
        lbl_hora = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/chave.png"))); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Login", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 18))); // NOI18N
        jPanel1.setFocusable(false);

        LoginUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginUsuarioActionPerformed(evt);
            }
        });

        LoginSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginSenhaActionPerformed(evt);
            }
        });
        LoginSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                LoginSenhaKeyPressed(evt);
            }
        });

        txt_divisao.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Funcionario", "Administrador" }));
        txt_divisao.setToolTipText("");

        jLabel1.setText("Usuário :");
        jLabel1.setFocusable(false);

        jLabel2.setText("Senha : ");
        jLabel2.setFocusable(false);

        jLabel4.setText("Divisão :");
        jLabel4.setFocusable(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(LoginUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                            .addComponent(LoginSenha)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(txt_divisao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(LoginUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(LoginSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txt_divisao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        LoginSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/power_exit_23.6px_1122609_easyicon.net.png"))); // NOI18N
        LoginSalvar.setText("Sair");
        LoginSalvar.setFocusable(false);
        LoginSalvar.setMaximumSize(new java.awt.Dimension(95, 33));
        LoginSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginSalvarActionPerformed(evt);
            }
        });

        LoginEntrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/enter_24px_1170222_easyicon.net.png"))); // NOI18N
        LoginEntrar.setText("Entrar");
        LoginEntrar.setFocusable(false);
        LoginEntrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginEntrarActionPerformed(evt);
            }
        });

        jMenuBar1.setFocusable(false);

        lbl_data.setText("Data");
        lbl_data.setFocusable(false);
        jMenuBar1.add(lbl_data);

        lbl_hora.setText("Hora");
        lbl_hora.setFocusable(false);
        jMenuBar1.add(lbl_hora);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(LoginEntrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(LoginSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(LoginSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(LoginEntrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(524, 332));
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void LoginEntrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if (LoginUsuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O Campo Usuário está vazio");
        } else if (LoginSenha.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O Campo Senha está vazio");
        } else {

            String sql = "select id,username,password,division from Users Where (username =? and password =? and division =?)";

            try {
                int count = 0;

                pst = conn.prepareStatement(sql);

                pst.setString(1, LoginUsuario.getText());
                pst.setString(2, LoginSenha.getText());
                pst.setString(3, txt_divisao.getSelectedItem().toString());

                rs = pst.executeQuery();

                {
                }
                while (rs.next()) {
                    int id = rs.getInt(1);
                    Emp.empId = id;
                    count = count + 1;
                }
                String access = (txt_divisao.getSelectedItem().toString());

                if (access.equals("Administrador")) {
                    


                    if (count == 1) {
                        JOptionPane.showMessageDialog(null, "Bem Vindo!");
                        Menu j = new Menu();
                        j.setVisible(true);
                        this.dispose();
                        

                        java.util.Date currentDate = GregorianCalendar.getInstance().getTime();
                        DateFormat df = DateFormat.getDateInstance();
                        String dateString = df.format(currentDate);

                        java.util.Date d = new java.util.Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                        String timeString = sdf.format(d);

                        String value0 = timeString;
                        String values = dateString;

                        int value = Emp.empId;
                        String reg = "insert into Informacao (EMP_ID,DATA,STATUS) values ('" + value + "','" + value0 + " / " + values + "','Logged in')";
                        pst = conn.prepareStatement(reg);
                        pst.execute();
                        this.dispose();

                    } else if (count > 1) {
                        JOptionPane.showMessageDialog(null, "Duplicado, nome de usuário ou acesso à senha negado");
                    } else {
                        JOptionPane.showMessageDialog(null, "O nome de usuário e a senha não estão corretos");
                    }
                } else if (access.equals("Funcionario")) {

                    if (count == 1) {
                        JOptionPane.showMessageDialog(null, "Bem Vindo!");
                        Menu j = new Menu();
                        j.setVisible(true);

                        java.util.Date currentDate = GregorianCalendar.getInstance().getTime();
                        DateFormat df = DateFormat.getDateInstance();
                        String dateString = df.format(currentDate);

                        java.util.Date d = new java.util.Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                        String timeString = sdf.format(d);

                        String value0 = timeString;
                        String values = dateString;

                        int value = Emp.empId;
                        String reg = "insert into Informacao (EMP_ID,DATA,STATUS) values ('" + value + "','" + value0 + " / " + values + "','Logged in')";
                        pst = conn.prepareStatement(reg);
                        pst.execute();
                        this.dispose();
                    } else {
                        JOptionPane.showMessageDialog(null, "O nome de usuário e a senha não estão corretos");
                    }
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);

            } finally {

                try {
                    rs.close();
                    pst.close();

                } catch (Exception e) {

                }
            }

        }
user82329