Search code examples
javaswing

How to remove the previous tab after opening the new tab?


So I'm making a group project which is Java console GUI. This is my code for the Java console GUI:

package com.nono.groupproject;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.ButtonGroup;

public class UserRegistrationGUIConsole extends JFrame {

    private JTextField nameField, addressField, phoneNumberField;
    private JRadioButton maleRadioButton, femaleRadioButton;
    private ButtonGroup sexButtonGroup;

    public UserRegistrationGUIConsole() {
        setTitle("User Registration");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(7, 2, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 20));
        
        panel.add(new JLabel("Name:"));
        nameField = new JTextField();
        panel.add(nameField);

        panel.add(new JLabel("Address:"));
        addressField = new JTextField();
        panel.add(addressField);

        panel.add(new JLabel("Phone Number:"));
        phoneNumberField = new JTextField();
        panel.add(phoneNumberField);

        panel.add(new JLabel("Sex:"));
        maleRadioButton = new JRadioButton("Male");
        femaleRadioButton = new JRadioButton("Female");
        sexButtonGroup = new ButtonGroup();
        sexButtonGroup.add(maleRadioButton);
        sexButtonGroup.add(femaleRadioButton);
        panel.add(maleRadioButton);
        panel.add(femaleRadioButton);

        JButton registerButton = new JButton("Register");
        registerButton.addActionListener(e -> handleRegistration(e));

        panel.add(registerButton);

        setContentPane(panel);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void handleRegistration(ActionEvent e) {
        // Your registration logic goes here
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static void main(String[] args) {
        new UserRegistrationGUIConsole();
    }
}

enter image description here

So I input the username and password for the login, after I input the password and username it appears a new tab but the login tab didn't close. How to make it close by itself after I open the new tab?


Solution

  • I think you have to call this.dispose() method in handleRegistration(ActionEvent e) when the login process is completed