簡體   English   中英

Java GUI - 將登錄頁面設置為出現在主框架之前

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

我目前正在處理這段代碼,它在主頁面之前實現了一個登錄頁面。 代碼如下:

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('*');
            }
        }
    }

所以登錄頁面單獨工作,使用正確的憑據,我們會得到憑據正確的 JOption MessageDialog。 當我嘗試在我的主類中實現它時,它會在最小化的主框架前面打開,如下所示:

登錄框

有誰知道究竟需要改變什么才能作為一個整體出現?

你的代碼有很多問題。

  1. 您在類TestFrame的構造函數中隱藏成員變量framelframe
JFrame lframe=new JFrame();

JFrame frame = new JFrame();

這里lframeframe是局部變量而不是類成員。

  1. 您錯誤地初始化了類成員container
container = getContentPane();

TestFrame類擴展了javax.swing.JFrame類,因此當您實際需要TestFrame內容窗格時, container實際上是指lframe的內容窗格。 因此,您沒有向lframe添加任何組件。

  1. 您問題中的代碼無法編譯,因為TestFrame類沒有正確實現接口ActionListener ,因為它不包含名為actionPerformed的方法。

下面的代碼是您添加了我的修復的代碼。 請注意,我沒有您的圖像,因此我在JLabel中添加了文本而不是圖標。 我還添加了一個main方法(您問題中的代碼沒有該方法),以便能夠將代碼作為 Java 應用程序運行。

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();
        });
    }
}

這是我運行上述代碼時lframe的外觀。 請注意,當我運行代碼時, frame出現在lframe的“后面”並占據了整個屏幕。

屏幕截圖

然而...

專家說,一個Swing應用程序應該只有一個JFrame 因此,我建議您將lframe JDialog而不是JFrame 我建議您初始化frame但不要使其可見。 僅在用戶成功登錄后才可見。

我還覺得您希望frame具有背景圖像。 如果是這種情況,那么使用JLabel不是這樣做的方法。 為了做到這一點,擴展類javax.swing.JPanel並覆蓋它的paintComponent方法。

下面的代碼演示。 請注意,以下代碼使用布局管理器 另請注意,文件test.png需要與文件TestFrame.class位於同一文件夾中。 此外,以下代碼使用方法引用

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());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM