简体   繁体   中英

Java GUI- Set the Login Page to appear before the main Frame

I'm working on this code currently which implements a login page right before the main one. The code is as follows:

public class TestFrame extends JFrame implements ActionListener{

    private JFrame frame; //main frame
    private JFrame lframe; //login frame
    private Container container;
    private JLabel userLabel;
    private JLabel passwordLabel;
    private JTextField userTextField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton resetButton;
    private JCheckBox showPassword;

    /**
     * Launch the application.
     */

    /**
     * Create the application. Rest of the program here.
     */
    public TestFrame() {
        container = getContentPane();
        userLabel = new JLabel("USERNAME");
        passwordLabel = new JLabel("PASSWORD");
        userTextField = new JTextField();
        passwordField = new JPasswordField();
        loginButton = new JButton("LOGIN");
        resetButton = new JButton("RESET");
        showPassword = new JCheckBox("Show Password");
        JFrame lframe=new JFrame();
        lframe.setTitle("Login BHMS");

        JFrame frame = new JFrame();
        frame.setTitle("Test System");

        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JLabel(new ImageIcon("test.png")));
        frame.setResizable(false);
        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        /**
         *
         * @Main Page, IGNORE----------------------------------------------------------------------
         */

        frame.setVisible(true); //the main frame
        lframe.setVisible(true); //if the login is successful then the main frame is visible
    }

    public void login() {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
        lframe.setVisible(true);
    }

    public void setLayoutManager() {
        container.setLayout(null);
    }
 
    public void setLocationAndSize() {
        lframe.setBounds(500,500,500,500);
        userLabel.setBounds(50, 150, 100, 30);
        passwordLabel.setBounds(50, 220, 100, 30);
        userTextField.setBounds(150, 150, 150, 30);
        passwordField.setBounds(150, 220, 150, 30);
        showPassword.setBounds(150, 250, 150, 30);
        loginButton.setBounds(50, 300, 100, 30);
        resetButton.setBounds(200, 300, 100, 30);
    }

    public void addComponentsToContainer() {
        container.add(userLabel);
        container.add(passwordLabel);
        container.add(userTextField);
        container.add(passwordField);
        container.add(showPassword);
        container.add(loginButton);
        container.add(resetButton);

        JLabel lblNewLabel = new JLabel("");
        lblNewLabel.setIcon(new ImageIcon(login.class.getResource("/development/test1.png")));
        lblNewLabel.setBounds(106, 10, 204, 113);
        getContentPane().add(lblNewLabel);
    }

    public void addActionEvent() {
        loginButton.addActionListener(this);
        resetButton.addActionListener(this);
        showPassword.addActionListener(this);
    }

    public void loginActionPerformed(ActionEvent e) {
        //Coding Part of LOGIN button
        if (e.getSource() == loginButton) {
            String userText;
            String pwdText;
            userText = userTextField.getText();
            pwdText = passwordField.getText();
            if (userText.equalsIgnoreCase("Admin") && pwdText.equalsIgnoreCase("Admin")) {
                JOptionPane.showMessageDialog(this, "Login Successful."+" Hello "+userText);
            } 
            else {
                JOptionPane.showMessageDialog(this, "Invalid Username or Password");
            }
        }
        //Coding Part of RESET button
        if (e.getSource() == resetButton) {
            userTextField.setText("");
            passwordField.setText("");
        }
        //Coding Part of showPassword JCheckBox
        if (e.getSource() == showPassword) {
            if (showPassword.isSelected()) {
                passwordField.setEchoChar((char) 0);
            } else {
                passwordField.setEchoChar('*');
            }
        }
    }

So the login page alone works, with the right credentials we get the JOption MessageDialog that the credentials are correct. When I try to implement it in my main class it opens in front of the main Frame minimized like this:

登录框

Does anyone know what exactly needs to be changed to appear as a whole?

There are lots of problems with your code.

  1. You are shadowing member variables frame and lframe in the constructor of class TestFrame .
JFrame lframe=new JFrame();

and

JFrame frame = new JFrame();

Here lframe and frame are local variables and not the class members.

  1. You are incorrectly initializing class member container .
container = getContentPane();

Class TestFrame extends class javax.swing.JFrame so container actually refers to the content pane of TestFrame when you actually want the content pane of lframe . Hence you are not adding any components to lframe .

  1. The code in your question does not compile since class TestFrame does not correctly implement interface ActionListener since it does not contain a method named actionPerformed .

The below code is your code with my fixes added. Note that I don't have your images, so I added text to the JLabel s instead of icons. Also I added a main method – which the code in your question does not have – in order to be able to run the code as a Java application.

import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class TestFrame extends JFrame implements ActionListener{

    private JFrame frame; //main frame
    private JFrame lframe; //login frame
    private Container container;
    private JLabel userLabel;
    private JLabel passwordLabel;
    private JTextField userTextField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton resetButton;
    private JCheckBox showPassword;


    /**
     * Launch the application.
     */
    

    /**
     * Create the application. Rest of the program here.
     */
    public TestFrame() {
//        container = getContentPane();
        userLabel = new JLabel("USERNAME");
        passwordLabel = new JLabel("PASSWORD");
        userTextField = new JTextField();
        passwordField = new JPasswordField();
        loginButton = new JButton("LOGIN");
        resetButton = new JButton("RESET");
        showPassword = new JCheckBox("Show Password");
        /*JFrame*/ lframe=new JFrame();
        container = lframe.getContentPane(); // ADDED this line
        lframe.setTitle("Login BHMS");

        /*JFrame*/ frame = new JFrame();
        frame.setTitle("Test System");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JLabel(/*new ImageIcon("test.png")*/"test.png"));
        frame.setResizable(false);
        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);
        
        /**
         *
         * @Main Page, IGNORE-----------------------------------------------------------------------------------------------------------------
         */
        
        frame.setVisible(true); //the main frame
        lframe.setVisible(true); //if the login is successful then the main frame is visible
    }

    public void login() {
        setLayoutManager();
        setLocationAndSize();
        addComponentsToContainer();
        addActionEvent();
        lframe.setVisible(true);
    }

    public void setLayoutManager() {
        container.setLayout(null);
    }
 
    public void setLocationAndSize() {
        lframe.setBounds(500,500,500,500);
        userLabel.setBounds(50, 150, 100, 30);
        passwordLabel.setBounds(50, 220, 100, 30);
        userTextField.setBounds(150, 150, 150, 30);
        passwordField.setBounds(150, 220, 150, 30);
        showPassword.setBounds(150, 250, 150, 30);
        loginButton.setBounds(50, 300, 100, 30);
        resetButton.setBounds(200, 300, 100, 30);
    }
 
    public void addComponentsToContainer() {
        container.add(userLabel);
        container.add(passwordLabel);
        container.add(userTextField);
        container.add(passwordField);
        container.add(showPassword);
        container.add(loginButton);
        container.add(resetButton);
        
        JLabel lblNewLabel = new JLabel("test1.png");
//        lblNewLabel.setIcon(new ImageIcon(login.class.getResource("/development/test1.png")));
        lblNewLabel.setBounds(106, 10, 204, 113);
        getContentPane().add(lblNewLabel);
    }
 
    public void addActionEvent() {
        loginButton.addActionListener(this);
        resetButton.addActionListener(this);
        showPassword.addActionListener(this);
    }

    public void /*loginA*/actionPerformed(ActionEvent e) {
        //Coding Part of LOGIN button
        if (e.getSource() == loginButton) {
            String userText;
            String pwdText;
            userText = userTextField.getText();
            pwdText = passwordField.getText();
            if (userText.equalsIgnoreCase("Admin") && pwdText.equalsIgnoreCase("Admin")) {
                JOptionPane.showMessageDialog(this, "Login Successful."+" Hello "+userText);
            } 
            else {
                JOptionPane.showMessageDialog(this, "Invalid Username or Password");
            }
        }
        //Coding Part of RESET button
        if (e.getSource() == resetButton) {
            userTextField.setText("");
            passwordField.setText("");
        }
       //Coding Part of showPassword JCheckBox
        if (e.getSource() == showPassword) {
            if (showPassword.isSelected()) {
                passwordField.setEchoChar((char) 0);
            } else {
                passwordField.setEchoChar('*');
            }
        }        
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new TestFrame().login();
        });
    }
}

This is how lframe looks when I run the above code. Note that when I run the code, frame appears "behind" lframe and takes up the entire screen.

屏幕截图

However...

The experts say that a Swing application should only have one JFrame . Hence I suggest that you make lframe a JDialog and not a JFrame . I suggest that you initialize frame but do not make it visible. Only make it visible after the user has successfully logged in.

I also get the impression that you want frame to have a background image. If that is the case, then using a JLabel is not the way to do it. In order to do it, extend class javax.swing.JPanel and override its paintComponent method.

The below code demonstrates. Note that the below code uses layout managers . Also note that file test.png needs to be in the same folder as file TestFrame.class . Also, the below code uses method references .

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class TestFrame extends JPanel implements Runnable {
    private boolean initial;
    private char echoChar;
    private Image backgroundImage;
    private JCheckBox showPassword;
    private JDialog lframe; //login frame
    private JFrame frame; //main frame
    private JPasswordField passwordField;
    private JTextField userTextField;

    public TestFrame() {
        initial = true;
        try {
            backgroundImage = ImageIO.read(getClass().getResource("test.png"));
        }
        catch (IOException x) {
            x.printStackTrace();
        }
    }

    public void run() {
        createAndDisplayGui();
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (initial && backgroundImage != null) {
            initial = false;
            Container contentPane = frame.getContentPane();
            backgroundImage = backgroundImage.getScaledInstance(contentPane.getWidth(),
                                                                contentPane.getHeight(),
                                                                Image.SCALE_DEFAULT);
        }
        g.drawImage(backgroundImage, 0, 0, null);
    }

    private void checkLogin(ActionEvent event) {
        String userText = userTextField.getText();
        String password = new String(passwordField.getPassword());
        if ("Admin".equals(userText) && "Admin".equals(password)) {
            lframe.dispose();
            frame.setVisible(true);
        }
        else {
            JOptionPane.showMessageDialog(lframe,
                                          "Incorrect username or password.",
                                          "ERROR",
                                          JOptionPane.ERROR_MESSAGE);
        }
    }

    private void createAndDisplayGui() {
        frame = new JFrame("Test System");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.add(this);
        frame.setResizable(false);
        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);
        showLogin();
    }

    private JPanel createLoginButtons() {
        JPanel buttonsPanel = new JPanel();
        JButton loginButton = new JButton("LOGIN");
        loginButton.addActionListener(this::checkLogin);
        JButton resetButton = new JButton("RESET");
        resetButton.addActionListener(this::resetLogin);
        buttonsPanel.add(loginButton);
        buttonsPanel.add(resetButton);
        return buttonsPanel;
    }

    private JPanel createLoginForm() {
        JPanel loginForm = new JPanel(new GridBagLayout());
        loginForm.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.LINE_START;
        gbc.insets.bottom = 5;
        gbc.insets.left = 5;
        gbc.insets.right = 5;
        gbc.insets.top = 5;
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel userLabel = new JLabel("USERNAME");
        loginForm.add(userLabel, gbc);
        gbc.gridx = 1;
        userTextField = new JTextField(10);
        loginForm.add(userTextField, gbc);
        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel passwordLabel = new JLabel("PASSWORD");
        loginForm.add(passwordLabel, gbc);
        gbc.gridx = 1;
        passwordField = new JPasswordField(10);
        echoChar = passwordField.getEchoChar();
        loginForm.add(passwordField, gbc);
        gbc.gridy = 2;
        showPassword = new JCheckBox("Show Password");
        showPassword.addActionListener(this::showOrHidePassword);
        loginForm.add(showPassword, gbc);
        return loginForm;
    }

    private void resetLogin(ActionEvent event) {
        userTextField.setText("");
        passwordField.setText(null);
    }

    private void showLogin() {
        lframe = new JDialog(frame, "Login BHMS");
        lframe.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        lframe.add(createLoginForm(), BorderLayout.CENTER);
        lframe.add(createLoginButtons(), BorderLayout.PAGE_END);
        lframe.pack();
        lframe.setLocationRelativeTo(null);
        lframe.setVisible(true);
    }

    private void showOrHidePassword(ActionEvent event) {
        if (showPassword.isSelected()) {
            passwordField.setEchoChar((char) 0);
        }
        else {
            passwordField.setEchoChar(echoChar);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new TestFrame());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM