0

I have been looking for this for days now and I haven't found a solution so I just made my account.

I want to figure out how should I open another JPanel from the current JPanel in my JFrame. I have made three classes till now in the view package: mainView (JFrame), loginAs (JPanel), loginPanel (JPanel). What I want to do is, I want to display loginAs Panel as my first panel where user selects whether he is an Admin or Staff and then after clicking the desired option, it should open the loginPanel where they can log in. I'm stuck here as I don't know how I can give back the information to mainView that the user has selected Admin or Staff and that mainView should now move to the next panel that is loginPanel.

Here is the coding I did:

mainView

package view;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import java.awt.Color;

public class mainView extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    mainView frame = new mainView();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public mainView() {
        setTitle("COVID'19 Management System");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 550, 410);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new CardLayout(0, 0));
        
        JPanel p1 = new loginAs();
        contentPane.add(p1, "t1");
        
        JPanel p2 = new loginPanel();
        contentPane.add(p2, "t2");
        
        JPanel p3 = new JPanel();
        contentPane.add(p3, "t3");
        
        JPanel p4 = new JPanel();
        contentPane.add(p4, "t4");
    }

}

loginAs

package view;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import view.mainView;

public class loginAs extends JPanel {

    /**
     * Create the panel.
     */
    public loginAs() {
        setBackground(Color.BLACK);
        setLayout(null);
        
        JLabel lblNewLabel = new JLabel("COVID'19 Management System");
        lblNewLabel.setForeground(Color.WHITE);
        lblNewLabel.setFont(new Font("Calibri", Font.BOLD, 18));
        lblNewLabel.setBounds(140, 27, 262, 28);
        add(lblNewLabel);
        
        JLabel lblNewLabel_1 = new JLabel("LOGIN AS");
        lblNewLabel_1.setForeground(Color.WHITE);
        lblNewLabel_1.setFont(new Font("Calibri", Font.BOLD, 16));
        lblNewLabel_1.setBounds(35, 87, 97, 28);
        add(lblNewLabel_1);
        
        JButton btnAdmin = new JButton("ADMIN");
        btnAdmin.setForeground(Color.BLACK);
        btnAdmin.setBackground(Color.WHITE);
        btnAdmin.setBounds(35, 134, 97, 39);
        add(btnAdmin);
        btnAdmin.setBorderPainted(false);
        btnAdmin.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnAdmin.setBackground(Color.GREEN);
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                btnAdmin.setBackground(Color.WHITE);
            }

            public void mouseClicked(java.awt.event.MouseEvent e)
            {
                
            }
        });
        
        JButton btnStaff = new JButton("STAFF");
        btnStaff.setForeground(Color.BLACK);
        btnStaff.setBackground(Color.WHITE);
        btnStaff.setBounds(35, 200, 97, 39);
        add(btnStaff);
        btnStaff.setBorderPainted(false);
        btnStaff.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnStaff.setBackground(Color.GREEN);
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                btnStaff.setBackground(Color.WHITE);
            }

            public void mouseClicked(java.awt.event.MouseEvent e)
            {
                
            }
        });
    }
}

loginPanel

package view;

import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;

public class loginPanel extends JPanel {
    private JTextField txt_uname;
    private JTextField txt_pass;

    /**
     * Create the panel.
     */
    public loginPanel() {
        setBackground(Color.BLACK);
        setLayout(null);
        
        JLabel lblNewLabel = new JLabel("COVID'19 Management System");
        lblNewLabel.setForeground(Color.WHITE);
        lblNewLabel.setFont(new Font("Calibri", Font.BOLD, 18));
        lblNewLabel.setBounds(140, 27, 262, 28);
        add(lblNewLabel);
        
        JLabel lblNewLabel_1 = new JLabel("LOGIN PAGE");
        lblNewLabel_1.setForeground(Color.WHITE);
        lblNewLabel_1.setFont(new Font("Calibri", Font.BOLD, 16));
        lblNewLabel_1.setBounds(35, 87, 97, 28);
        add(lblNewLabel_1);
        
        JLabel lblNewLabel_2 = new JLabel("Username");
        lblNewLabel_2.setFont(new Font("Calibri", Font.BOLD, 14));
        lblNewLabel_2.setForeground(Color.WHITE);
        lblNewLabel_2.setBounds(35, 142, 74, 14);
        add(lblNewLabel_2);
        
        txt_uname = new JTextField();
        txt_uname.setBounds(123, 137, 147, 20);
        add(txt_uname);
        txt_uname.setColumns(10);
        
        JLabel lblNewLabel_2_1 = new JLabel("Password");
        lblNewLabel_2_1.setForeground(Color.WHITE);
        lblNewLabel_2_1.setFont(new Font("Calibri", Font.BOLD, 14));
        lblNewLabel_2_1.setBounds(35, 188, 74, 14);
        add(lblNewLabel_2_1);
        
        txt_pass = new JTextField();
        txt_pass.setColumns(10);
        txt_pass.setBounds(123, 183, 147, 20);
        add(txt_pass);
        
        JButton btn_login = new JButton("Login");
        btn_login.setBounds(123, 229, 89, 23);
        add(btn_login);

    }
}

Here is the visual representation:

This is what is displayed and where user can select Admin or Staff

This is what should appear next

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • 1
    You should also separate your ui from your business logic. Into a model view pattern. Where you have a class (model) that holds all the information, this could even be a singleton, and this gets either passed to the next `JPanel` (view) via the constructor or if its a singleton you simply get it using its instance accesor. This way you can share information between the various `JPanel`s on your application. – David Kroukamp Jan 29 '21 at 13:00
  • oh thanks, that will help in information sharing. But now when I have that information, how can I switch the JPanel though? It is stuck on loginAs JPanel, whereas now I want to show loginPanel. – Malik Farrukh Rabah Jan 29 '21 at 13:20
  • To answer you switching of JPanels you will see I've closed your question as a duplicate. The link (at the top of your question under the title) should show you how to switch between various jpanels on a single jframe – David Kroukamp Jan 29 '21 at 13:22
  • I understand how to change panels if it is written in the same JFrame code. But the problem is, my main JFrame is mainVIew, and I have other external JPanels that have buttons on them and I cannot access those buttons from my mainView JFrame. So if I had that button in mainView, then I can change JPanel but I have that button in the loginAs Panel. That's confusing me a lot.... – Malik Farrukh Rabah Jan 29 '21 at 13:30
  • That's why I made an account and asked this question. I saw like 50+ threads but they all had the code as a singleton. I have different JPanels which I link with the main JFrame. I cannot find the solution to this problem anywhere :/ – Malik Farrukh Rabah Jan 29 '21 at 13:35
  • 1
    Not sure I fully understand, but it should working something like this. JFrame has LoginPanel, user clicks login button on the LoginPanel, the panel should then communicate back to the JFrame telling it to switch to the next panel. This would be easier should you implement a [MVC pattern](https://stackoverflow.com/a/65179483/1133011), but it's not necessary, you can simply get the JFrame instance the LoginPanel is added to using `mainView topFrame = (mainView) SwingUtilities.getWindowAncestor(this);` and call whatever method you want on it to switch the panels using the CardLayout – David Kroukamp Jan 29 '21 at 13:36
  • 1
    I will reopen this question as perhaps it was not correct to be closed as a duplicate, with that said I'd strongly look into using the MVC pattern I linked to switch between views and this will also help you hold information across your panels – David Kroukamp Jan 29 '21 at 13:37

1 Answers1

1

I took your code, cleaned it up, and added an ActionListener for the JButtons on the first page.

Here's the GUI first page.

First page

Here's the GUI second page.

Second page

The first thing I did was to get rid of the absolute positioning. I used a GridBagLayout on both JPanels.

The next thing I did was to factor out the button coloring on a mouse in and mouse out.

I created an application model to hold the variables I've seen. Eventually, this model will hold all the variables for the entire application.

I made all the classes inner classes so I can copy and paste this code into one block. You can and should separate my inner classes into separate classes.

Here's the complete runnable code.

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class Covid19GUI extends JFrame {

    private static final long serialVersionUID = 1L;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Covid19GUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    private Covid19Model model;

    private JPanel contentPane;

    /**
     * Create the frame.
     */
    public Covid19GUI() {
        this.model = new Covid19Model();
        
        setTitle("COVID'19 Management System");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new CardLayout(5, 5));

        JPanel p1 = new LoginAs(this, model);
        contentPane.add(p1, "t1");

        JPanel p2 = new LoginPanel(this, model);
        contentPane.add(p2, "t2");

        JPanel p3 = new JPanel();
        contentPane.add(p3, "t3");

        JPanel p4 = new JPanel();
        contentPane.add(p4, "t4");

        add(contentPane, BorderLayout.CENTER);
        pack();
        setLocationByPlatform(true);
        setVisible(true);
    }
    
    public JPanel getCardLayoutPanel() {
        return contentPane;
    }

    public class LoginAs extends JPanel {

        private static final long serialVersionUID = 1L;

        /**
         * Create the panel.
         */
        public LoginAs(Covid19GUI frame, Covid19Model model) {      
            setBackground(Color.BLACK);
            setLayout(new GridBagLayout());
            
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.gridx = 0;
            gbc.gridy = 0;

            JLabel lblNewLabel = new JLabel("COVID'19 Management System");
            lblNewLabel.setForeground(Color.WHITE);
            lblNewLabel.setFont(new Font("Calibri", Font.BOLD, 18));
            add(lblNewLabel, gbc);

            gbc.gridy++;
            JLabel lblNewLabel_1 = new JLabel("LOGIN AS");
            lblNewLabel_1.setForeground(Color.WHITE);
            lblNewLabel_1.setFont(new Font("Calibri", Font.BOLD, 16));
            add(lblNewLabel_1, gbc);
            
            ButtonListener listener = new ButtonListener(frame, model);

            gbc.gridy++;
            JButton btnAdmin = new JButton("ADMIN");
            btnAdmin.addActionListener(listener);
            btnAdmin.addMouseListener(new ColorListener(btnAdmin));
            btnAdmin.setForeground(Color.BLACK);
            btnAdmin.setBackground(Color.WHITE);
            btnAdmin.setBorderPainted(false);
            add(btnAdmin, gbc);
            
            gbc.gridy++;
            JButton btnStaff = new JButton("STAFF");
            btnStaff.addActionListener(listener);
            btnStaff.addMouseListener(new ColorListener(btnStaff));         
            btnStaff.setForeground(Color.BLACK);
            btnStaff.setBackground(Color.WHITE);
            btnStaff.setBorderPainted(false);
            add(btnStaff, gbc);
        }
    }
    
    public class ColorListener extends MouseAdapter {
        
        private JButton button;
        
        public ColorListener(JButton button) {
            this.button = button;
        }

        @Override
        public void mouseEntered(MouseEvent evt) {
            button.setBackground(Color.GREEN);
        }

        @Override
        public void mouseExited(MouseEvent evt) {
            button.setBackground(Color.WHITE);
        }
    }
    
    public class ButtonListener implements ActionListener {
        
        private Covid19GUI frame;
        
        private Covid19Model model;

        public ButtonListener(Covid19GUI frame, Covid19Model model) {
            this.frame = frame;
            this.model = model;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            if (button.getText().equals("ADMIN")) {
                model.setAdmin(true);
            } else {
                model.setAdmin(false);
            }
            
            JPanel panel = frame.getCardLayoutPanel();
            CardLayout layout = (CardLayout) panel.getLayout();
            layout.show(panel, "t2");
        }
        
    }

    public class LoginPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        
        private Covid19GUI frame;
        
        private Covid19Model model;

        private JTextField txt_uname;
        private JTextField txt_pass;

        /**
         * Create the panel.
         */
        public LoginPanel(Covid19GUI frame, Covid19Model model) {
            this.frame = frame;
            this.model = model;
            
            setBackground(Color.BLACK);
            setLayout(new GridBagLayout());
            
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.anchor = GridBagConstraints.LINE_START;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.gridwidth = 2;
            gbc.gridx = 0;
            gbc.gridy = 0;

            JLabel lblNewLabel = new JLabel("COVID'19 Management System");
            lblNewLabel.setForeground(Color.WHITE);
            lblNewLabel.setFont(new Font("Calibri", Font.BOLD, 18));
            add(lblNewLabel, gbc);

            gbc.gridy++;
            JLabel lblNewLabel_1 = new JLabel("LOGIN PAGE");
            lblNewLabel_1.setForeground(Color.WHITE);
            lblNewLabel_1.setFont(new Font("Calibri", Font.BOLD, 16));
            add(lblNewLabel_1, gbc);

            gbc.gridwidth = 1;
            gbc.gridy++;
            JLabel lblNewLabel_2 = new JLabel("Username");
            lblNewLabel_2.setFont(new Font("Calibri", Font.BOLD, 14));
            lblNewLabel_2.setForeground(Color.WHITE);
            add(lblNewLabel_2, gbc);

            gbc.gridx++;
            txt_uname = new JTextField();
            txt_uname.setColumns(10);
            add(txt_uname, gbc);
            
            gbc.gridx = 0;
            gbc.gridy++;
            JLabel lblNewLabel_2_1 = new JLabel("Password");
            lblNewLabel_2_1.setForeground(Color.WHITE);
            lblNewLabel_2_1.setFont(new Font("Calibri", Font.BOLD, 14));
            add(lblNewLabel_2_1, gbc);

            gbc.gridx++;
            txt_pass = new JTextField();
            txt_pass.setColumns(10);
            add(txt_pass, gbc);

            gbc.gridwidth = 2;
            gbc.gridx = 0;
            gbc.gridy++;
            JButton btn_login = new JButton("Login");
            add(btn_login, gbc);
        }
        
        public String getUserName() {
            return txt_uname.getText().trim();
        }
        
        public String getPassword() {
            return txt_pass.getText().trim();
        }
        
    }
    
    public class Covid19Model {
        
        private boolean isAdmin;
        
        private String userName;
        private String password;
        
        public boolean isAdmin() {
            return isAdmin;
        }
        
        public void setAdmin(boolean isAdmin) {
            this.isAdmin = isAdmin;
        }
        
        public String getUserName() {
            return userName;
        }
        
        public void setUserName(String userName) {
            this.userName = userName;
        }
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
        
    }

}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111