Need a little help hiding / disabling the jbutton

I am working on a student / admin portal application and I need a little help hiding / enabling the jbuttons.

  • If the user is logged in as an administrator, the jbutton must be enabled / displayed.
  • If the user is registered as a student the jbutton should be disabled / disappeared.

For example, I have button 1 in Jframe1 and will hide the button in JFrame2. Please find the code below - the one in the double asterisk is my code for setting the visibility of the jbutton in frame2 to hide. I also set the jbutton variable modifier to be public.

FORM 1 - login

package testlogin;
import java.sql.*;
import javax.swing.JOptionPane;

////////////////////////////////
public class login extends javax.swing.JFrame {
public welc welc;
public Statement st;
public int xtry =1,ytry=4,trig;
Connection conn=null;
PreparedStatement pst =null;
ResultSet rs =null;


 ///
    public login() {

        initComponents();
         conn=mysqlconnect.Connectdb();    //class connection       
    }

//////////

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        user1 = new javax.swing.JTextField();
        submitbtn = new javax.swing.JButton();
        pass1 = new javax.swing.JPasswordField();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMaximumSize(new java.awt.Dimension(350, 300));
        setMinimumSize(new java.awt.Dimension(350, 100));
        setName("Login"); // NOI18N
        setPreferredSize(new java.awt.Dimension(350, 230));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("LOGIN");

        jLabel2.setText("STUDENT NUMBER:");

        jLabel3.setText("PASSWORD:");

        submitbtn.setText("SUBMIT");
        submitbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitbtnActionPerformed(evt);
            }
        });

        pass1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                pass1MouseClicked(evt);
            }
        });
        pass1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pass1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(84, 84, 84)
                                .addComponent(jLabel1))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addGap(36, 36, 36)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(user1)
                                    .addComponent(pass1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(88, 88, 88)
                        .addComponent(submitbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(185, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(41, 41, 41)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(user1, 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(jLabel3)
                    .addComponent(pass1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41)
                .addComponent(submitbtn)
                .addContainerGap())
        );

        jButton1.setText("LOGIN AS ADMIN");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("LOGIN AS STUDENT");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setText("LOGIN");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(138, 138, 138)
                        .addComponent(jLabel4)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(84, 84, 84))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 70, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void submitbtnActionPerformed(java.awt.event.ActionEvent evt) {                                          

            String sql = "select *from tablelogin where username = ? and password = ?";      //check Password and Username
         try{
             pst = conn.prepareStatement(sql);
             pst.setString(1,user1.getText());      //gets user text from textbox
             pst.setString(2,pass1.getText());       //gets pass text from textbox
             rs = pst.executeQuery();               //send to query

        if (rs.next()){                            //query will test if username & password == user1 & user2
            if (trig==1){                  //triggers the condition if user or admin
            JOptionPane.showMessageDialog(null, "YOU ARE LOGGED IN AS AN ADMIN!");
            welc spark = new welc();
        spark.btn_create.setVisible(false);

            }
            else{
            JOptionPane.showMessageDialog(null, "YOU ARE LOGGED IN AS A STUDENT!");

            }
            JOptionPane.showMessageDialog(null, "Connection Established!"); 

             this.dispose();
             new welc().setVisible(true);    
                }
        else               
                if (xtry<=4){                       //condition for number of tries
                    JOptionPane.showMessageDialog(null, "INVALID USERNAME OR PASSWORD!\n(Only "+ytry+" tries left)");
                    xtry++;                     //increment & decrement for tries
                    ytry--;
                }
                else {                          //dialog exit
                    JOptionPane.showMessageDialog(null, "Maximum number of tries exceeded. Program will exit..");
                    System.exit(0);
                }                                                                      
                    }
       catch(Exception e){                     

        }




    }                                         

    private void pass1ActionPerformed(java.awt.event.ActionEvent evt) {                                      

    }                                     

    private void pass1MouseClicked(java.awt.event.MouseEvent evt) {                                   
        pass1.setText("");
    }                                  

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
       jPanel1.hide();                                      
    }                                 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       jPanel1.show();                                      //show panel1
       jPanel2.hide();                                      // hide panel2
       jLabel2.setText("USERNAME:");                        //set text to username
       trig=1;

    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         jPanel1.show();
       jPanel2.hide();




    }                                        


    public static void main(String args[]) {


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPasswordField pass1;
    public javax.swing.JButton submitbtn;
    private javax.swing.JTextField user1;
    // End of variables declaration                   
}

      

Frame 2 - welc

package testlogin;

import java.awt.Color;                  //import for colors
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutionException;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;       //import for dbutils/table


public class welc extends javax.swing.JFrame {
public String username2;
Connection conn=null;
PreparedStatement pst =null;
ResultSet rs =null;




////////////

    public welc() {
        Color color = new Color(0,153,51);  //bgcolor 
        getContentPane().setBackground(color); 
        conn=mysqlconnect.Connectdb();    //class connection   
        initComponents();

    }



    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        btn_create = new javax.swing.JButton();
        btn_create1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        btn_reglist = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(0, 153, 51));
        setMaximumSize(new java.awt.Dimension(1000, 600));
        setMinimumSize(new java.awt.Dimension(500, 500));
        setPreferredSize(new java.awt.Dimension(1000, 600));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jPanel1.setMinimumSize(new java.awt.Dimension(875, 400));
        jPanel1.setPreferredSize(new java.awt.Dimension(875, 400));

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel8.setText("PERSONAL INFORMATION");

        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()
                .addComponent(jLabel8)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addContainerGap(374, Short.MAX_VALUE))
        );

        jComboBox1.setEditable(true);
        jComboBox1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "HOME", "ACCOUNT", "SCHEDULE", "LOGOUT" }));
        jComboBox1.setFocusable(false);
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        btn_create.setText("CREATE AN ACCOUNT");
        btn_create.setEnabled(false);
        btn_create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_createActionPerformed(evt);
            }
        });

        btn_create1.setText("REMOVE AN ACCOUNT");
        btn_create1.setEnabled(false);

        btn_reglist.setText("CHECK RECORDS");
        btn_reglist.setEnabled(false);
        btn_reglist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_reglistActionPerformed(evt);
            }
        });

        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(75, 75, 75)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 840, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(426, 426, 426)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(41, 41, 41)
                                .addComponent(btn_reglist)
                                .addGap(37, 37, 37)
                                .addComponent(btn_create)
                                .addGap(18, 18, 18)
                                .addComponent(btn_create1)))))
                .addContainerGap(110, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_create)
                    .addComponent(btn_create1)
                    .addComponent(jLabel1)
                    .addComponent(btn_reglist))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 409, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(100, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  


    }                                 

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void btn_createActionPerformed(java.awt.event.ActionEvent evt) {                                           
        new create().show();
        this.hide();
    }                                          

    private void btn_reglistActionPerformed(java.awt.event.ActionEvent evt) {                                            
            new checkreg().show();
            this.hide();
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {



        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new welc().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    public javax.swing.JButton btn_create;
    public static javax.swing.JButton btn_create1;
    public javax.swing.JButton btn_reglist;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   

    private void setOpaque(boolean b) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

      

+3


source to share


1 answer


After changing the visibility of a component, or after adding or removing a component, you will need to call revalidate()

and repaint()

in the component container (which I believe is the contentPane in your example, at least for the second window) to re-lay out its components and then redraw to get rid of the dirty areas in your window.

btn_create.setVisible(false);
getContentPane().revalidate();
getContentPane().repaint();

      

Having said that, your code could be vastly improved by not flipping windows on the user side and instead using just one JFrame and replacing JPanel views via CardLayout.


Edit
Here's your error:

welc spark = new welc();
spark.btn_create.setVisible(false);

      

You create a completely new welc object called sparks, which is never displayed, and then sets the properties of one of its components, which works for that welc object , but this will not affect the welc displayable, since they are two completely different objects. The solution is to give the welc (which should be renamed Welc) a public method that allows you to change the state of its button, and then call that method on the Welc displayable, rather than a new and different welc object you instantiate in place.

eg.



// capitalize class name
public class Login extends javax.swing.JFrame {
   // create one instance only of Welc:
   public Welc welc = new Welc();  //!! added

   // ....


   private void submitbtnActionPerformed(java.awt.event.ActionEvent evt) {

      // .... code deleted for simplicfication

            if (trig == 1) {
               JOptionPane.showMessageDialog(null,
                     "YOU ARE LOGGED IN AS AN ADMIN!");
               // !! Welc spark = new Welc(); // removed 
               // spark.btn_create.setVisible(false);
               welc.btnCreateSetVisible(false); //!! add this
            } else {
               JOptionPane.showMessageDialog(null,
                     "YOU ARE LOGGED IN AS A STUDENT!");
            }
            JOptionPane.showMessageDialog(null, "Connection Established!");
            this.dispose();
            //!! new Welc().setVisible(true);
            welc.setVisible(true);
         } 
      } catch (Exception e) {
         //!! never have empty catch blocks
      }
   }


   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      //!! never use deprecated methods
      jPanel1.show();
      jPanel2.hide();
      jLabel2.setText("USERNAME:");
      trig = 1;
   }

// ....

      


Edit 2

Further suggestions:

  • As I go further, I can see how you want to log in through a dialog, but I would do just that using a modal dialog like JDialog or JOptionPane. You can use your main JFrame as the "calling" window, even if it is not already visible.
  • I recommend that you do not have a login window directly modifying the main GUI window, as this unnecessarily increases class concatenation.
  • Instead, consider creating an enumeration for your login type, say something called LoginType, and include all the required elements, say STUDENT and ADMINISTRATOR.
  • Then you can give your main GUI a method public void setLoginType(LoginType loginType)

    and in that method the main GUI will do whatever it needs to do for itself based on the login type.
  • Separate your database code from your GUI.
  • Make sure to create your database code on your thread that is disconnected from the Swing event thread.

Edit 3
For example:

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.*;
public class MyLogin {
   private static void createAndShowGUI() {
      MainGui mainGui = new MainGui();

      JFrame mainFrame = new JFrame("Main GUI");
      mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      mainFrame.add(mainGui);
      mainFrame.pack();
      mainFrame.setLocationRelativeTo(null);

      LoginDialogPanel dialogPanel = new LoginDialogPanel();

      LoginType loginType = null;

      while (loginType == null) {
         int result = JOptionPane.showConfirmDialog(mainFrame, dialogPanel, "Login",
                     JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

         if (result != JOptionPane.OK_OPTION) {
            // JOptionPane to make sure they want to exit
            // exit
            return;
         }

         loginType = dialogPanel.getLoginType();

      }

      System.out.println(loginType.getName());

      // TODO: check login credentials via database in background thread
      // I'd use a SwingWorker and add a PropertyChangeListener to it.
      // In the prop chng listener, if the worker state is SwingWorker.StateValue.DONE  
      // I'd show the mainFrame GUI if the credentials are OK

      System.out.println("User name: " + dialogPanel.getUserName());
      System.out.print("Never do this, never change a password to String: ");

      // TODO: delete the line of code below
      System.out.println("Password: " + new String(dialogPanel.getPassword())); // ***** !!

      mainGui.setLoginType(loginType);
      mainGui.setUser(dialogPanel.getUserName());

      mainFrame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}

// parts of my main GUI

@SuppressWarnings("serial")
class MainGui extends JPanel {

   private LoginType loginType;
   private JButton showForAllTypesButton = new JButton("Show for all");
   private JButton showForAdminButton = new JButton("Show for admin");
   private JTextField userField = new JTextField(10);

   public MainGui() {
      userField.setEditable(false);
      userField.setFocusable(false);

      add(new JLabel("User:"));
      add(userField);
      add(Box.createHorizontalStrut(15));
      add(showForAllTypesButton);
      add(showForAdminButton);
   }

   public void setLoginType(LoginType loginType) {
      this.loginType = loginType;
      showForAdminButton.setVisible(loginType == LoginType.ADMINISTRATOR);
      revalidate();
      repaint();
   }

   public void setUser(String user) {
      userField.setText(user);
   }

   public LoginType getLoginType() {
      return loginType;
   }

}

// parts of my login dialog jpanel

class LoginDialogPanel extends JPanel {
   private static final String TITLE = "Login Type";
   private boolean loginSuccessful = false;

   private ButtonGroup loginTypeBtnGroup = new ButtonGroup();
   private JTextField userNameField = new JTextField(10);
   private JPasswordField passwordField = new JPasswordField(10);

   public LoginDialogPanel() {
      setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
      JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
      titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 32));
      JPanel titlePanel = new JPanel();
      titlePanel.add(titleLabel);
      add(titlePanel);

      JPanel radioWrapperPanel = getLoginTypePanel();
      add(radioWrapperPanel);
      add(getNamePasswordPanel());
   }

   private JPanel getLoginTypePanel() {
      JPanel radioBtnPanel = new JPanel(new GridLayout(0, 1));
      for (LoginType loginType : LoginType.values()) {
         JRadioButton radioBtn = new JRadioButton(loginType.getName());
         radioBtn.setActionCommand(loginType.toString());
         loginTypeBtnGroup.add(radioBtn);
         radioBtnPanel.add(radioBtn);
      }
      JPanel radioWrapperPanel = new JPanel();
      radioWrapperPanel.add(radioBtnPanel);
      radioWrapperPanel.setBorder(BorderFactory.createTitledBorder("Login Type"));
      return radioWrapperPanel;
   }

   private JPanel getNamePasswordPanel() {
      JPanel namePasswordPanel = new JPanel(new GridBagLayout());
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.insets = new Insets(5, 5, 5, 5);
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.anchor = GridBagConstraints.EAST;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      namePasswordPanel.add(new JLabel("User Name:", SwingConstants.TRAILING), gbc);

      gbc.gridy = 1;
      namePasswordPanel.add(new JLabel("Password:", SwingConstants.TRAILING), gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      namePasswordPanel.add(userNameField, gbc);

      gbc.gridy = 1;
      namePasswordPanel.add(passwordField, gbc);

      JPanel namePasswordWrapperPanel = new JPanel();
      namePasswordWrapperPanel.add(namePasswordPanel);
      namePasswordPanel.setBorder(BorderFactory.createTitledBorder("Login Credentials"));
      return namePasswordPanel;
   }

   public boolean isLoginSuccessful() {
      return loginSuccessful;
   }

   public LoginType getLoginType() {
      ButtonModel model = loginTypeBtnGroup.getSelection();
      if (model == null) {
         return null; // nothing selected
      }

      return LoginType.valueOf(LoginType.class, model.getActionCommand());
   }

   public String getUserName() {
      return userNameField.getText();
   }

   public char[] getPassword() {
      return passwordField.getPassword();
   }

}

enum LoginType {
   STUDENT("Student"), ADMINISTRATOR("Administrator");
   private String name;

   private LoginType(String name) {
      this.name = name;
   }

   public String getName() {
      return name;
   }

}

      

+3


source







All Articles