How to Close One Java Swing Window and Open Another on Button Click

Question

How can I implement functionality in a Java Swing application that allows one window to close and another to open when a button is clicked?

public class MainFrame extends JFrame {
    private JButton openNewWindowButton;

    public MainFrame() {
        setTitle("Main Window");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        openNewWindowButton = new JButton("Open New Window");
        openNewWindowButton.addActionListener(e -> openNewWindow());
        add(openNewWindowButton);
    }

    private void openNewWindow() {
        NewWindow newWindow = new NewWindow(this);
        newWindow.setVisible(true);
        this.dispose(); // Closes the main window
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainFrame mainFrame = new MainFrame();
            mainFrame.setVisible(true);
        });
    }
}

class NewWindow extends JFrame {
    public NewWindow(JFrame parent) {
        setTitle("New Window");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Answer

In a Java Swing application, managing multiple windows is common for creating a responsive user interface. You can achieve the functionality of closing one window and opening another by utilizing Java's ActionListener interface in conjunction with JFrame class methods.

public class MainFrame extends JFrame {
    private JButton openNewWindowButton;

    public MainFrame() {
        setTitle("Main Window");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        openNewWindowButton = new JButton("Open New Window");
        openNewWindowButton.addActionListener(e -> openNewWindow());
        add(openNewWindowButton);
    }

    private void openNewWindow() {
        NewWindow newWindow = new NewWindow(this);
        newWindow.setVisible(true);
        this.dispose(); // Closes the main window
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainFrame mainFrame = new MainFrame();
            mainFrame.setVisible(true);
        });
    }
}

class NewWindow extends JFrame {
    public NewWindow(JFrame parent) {
        setTitle("New Window");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Causes

  • User needs to transition between different application states
  • Improving user experience by not cluttering the screen with multiple open windows

Solutions

  • Create a main JFrame that contains a JButton.
  • Implement an ActionListener for the button that handles opening the new JFrame and closing the current one.
  • Use `this.dispose()` in the main JFrame to close it when transitioning to the new window.

Common Mistakes

Mistake: Not using `dispose()` to close the current window, which keeps it in memory and may lead to resource leaks.

Solution: Always use `this.dispose()` after opening a new window to ensure proper closure.

Mistake: Forgetting to set the new window's visibility with `setVisible(true)`, causing the window not to appear.

Solution: Ensure to call `newWindow.setVisible(true);` immediately after creating the new window.

Helpers

  • Java Swing
  • close window
  • open new window
  • button click action
  • JFrame
  • Java GUI programming

Related Questions

⦿How to Use a For-Each Loop with a 2D Array in Programming?

Learn how to effectively utilize a foreach loop to iterate through a 2D array in programming with examples and solutions.

⦿How to Initialize Arrays Using the Ternary Operator in JavaScript?

Learn how to initialize arrays in JavaScript using the ternary operator with examples and best practices for effective coding.

⦿How to Dynamically Create a Button in Android

Learn how to dynamically create and add a Button in Android programmatically with stepbystep instructions code snippets and common debugging tips.

⦿Are Naked Objects a Good or Bad Approach in Software Development?

Explore the pros and cons of using Naked Objects in software development. Is it a beneficial pattern or a flawed design

⦿How to Fix Eclipse Errors in Your JPA Project

Learn how to troubleshoot and resolve errors in your JPA project in Eclipse with expert insights and practical solutions.

⦿How to Resolve "Illegal Attempt to Map a Non-Collection as @OneToMany, @ManyToMany or @CollectionOfElements" in Hibernate When Using ConcurrentHashMap

Learn how to fix the Hibernate error Illegal attempt to map a noncollection when using a ConcurrentHashMap and understand best practices for entity mapping.

⦿How to Determine if a String Matches Any Enum Values in Java

Learn how to check if a given string matches values from any Enum in Java with clear steps and code examples.

⦿How to Configure Maven with Spring Boot for Efficient Development?

Learn how to set up Maven for your Spring Boot projects including configurations dependencies and common mistakes to avoid.

⦿How to Check for Empty Strings in Java?

Learn how to effectively check for empty strings in Java with best practices and code examples for robust error handling.

⦿How to Invoke a Superclass Method (e.g., toString()) in a Derived Class Instance

Learn how to call superclass methods from a derived class in Java and other OOP languages with examples.

© Copyright 2025 - CodingTechRoom.com