Home > Blockchain >  Need to close JFrame on clicking Exit button on JFrame
Need to close JFrame on clicking Exit button on JFrame

Time:12-17

I am creating a simple Java application and I'm new to Java. kindly help me with this problem

I am using java 8 and I am trying to move from one frame to another frame and i can do that but for that, I have some exceptions occurring in the code and I can't figure it out why and what is that

Below is my code and the error occurred in given below.

package oops;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class HumanBenchmarkApp implements ActionListener{
    JFrame AppWindow, ReflexFrame, VisualFrame, CreditsFrame;
    JLabel Title;
    JButton Game1, Game2, Credits, Exit;
    public HumanBenchmarkApp(){
        AppWindow = new JFrame("Human Benchmark");
        AppWindow.setSize(400, 400);
        JPanel Content = new JPanel();
        Content.setBorder(new EmptyBorder(10, 10, 10, 10));
        Content.setLayout(new GridBagLayout());
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e){
            System.err.println(e.getMessage());
        }
        AppWindow.setLayout(new BoxLayout(AppWindow.getContentPane(),BoxLayout.Y_AXIS));
        Title = new JLabel("<html><h1><strong>Human Benchmark App</strong></h1><br></html>");
        Game1 = new JButton("<html><h4>Reflex Action Test</h4></html>");
        Game2 = new JButton("<html><h4>Visual Memory Test</h4></html>");
        Credits = new JButton("<html><h4>Credits</h4></html>");
        Exit = new JButton("<html><h4>Exit</h4></html>");
        Game1.addActionListener(this);
        Game2.addActionListener(this);
        Credits.addActionListener(this);
        Exit.addActionListener(this);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.anchor = GridBagConstraints.NORTH;
        Content.add(Title, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        JPanel Buttons = new JPanel(new GridBagLayout());
        Buttons.add(Game1, gbc);
        Buttons.add(Game2, gbc);
        Buttons.add(Credits, gbc);
        Buttons.add(Exit, gbc);
        gbc.weighty = 1;
        Content.add(Buttons);
        AppWindow.add(Content);
        AppWindow.setVisible(true);
        AppWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args){
        new HumanBenchmarkApp();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clicked = (JButton)e.getSource();
        if (clicked.getName().equals("Game1")){
            
        }
        else if(clicked.getName().equals("Game2")){
            
        }
        else if(clicked.getName().equals("Credits")){
            
        }
        else if(clicked.getName().equals("Exit")){
            System.exit(0);
        }
    }
}

This is my code and when I execute it, I get the below error on the NetBeans output area.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at oops.HumanBenchmarkApp.actionPerformed(HumanBenchmarkApp.java:56)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6539)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6304)
    at java.awt.Container.processEvent(Container.java:2239)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2297)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
    at java.awt.Container.dispatchEventImpl(Container.java:2283)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
    at java.awt.EventQueue$4.run(EventQueue.java:733)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Error is on console and the JFrame is not even closing.

CodePudding user response:

I don't really understand why such a confusing implementation of ActionListener, if you can use a lambda expression:

        ...

        Game1.addActionListener(this);
        Game2.addActionListener(this);
        Credits.addActionListener(this);
        Exit.addActionListener(e -> {   // <---- NEW HERE
            System.exit(0);             // <---- NEW HERE
        });                             // <---- NEW HERE
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.anchor = GridBagConstraints.NORTH;
        Content.add(Title, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        JPanel Buttons = new JPanel(new GridBagLayout());

        ...

EDIT:

or you can make this:

Exit.addActionListener(new ActionListener() {
            
    @Override
    public void actionPerformed(ActionEvent arg0) {
        System.exit(0); 
    }
});

or: You don't have to compare names, you can compare object references:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class HumanBenchmarkApp implements ActionListener {
    
    JFrame appWindow, reflexFrame, visualFrame, creditsFrame;
    JLabel title;
    JButton game1, game2, credits, exit;
    
    public HumanBenchmarkApp() {
        appWindow = new JFrame("Human Benchmark");
        appWindow.setSize(400, 400);
        JPanel content = new JPanel();
        content.setBorder(new EmptyBorder(10, 10, 10, 10));
        content.setLayout(new GridBagLayout());
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e){
            System.err.println(e.getMessage());
        }
        appWindow.setLayout(new BoxLayout(appWindow.getContentPane(),BoxLayout.Y_AXIS));
        title = new JLabel("<html><h1><strong>Human Benchmark App</strong></h1><br></html>");
        game1 = new JButton("<html><h4>Reflex Action Test</h4></html>");
        game2 = new JButton("<html><h4>Visual Memory Test</h4></html>");
        credits = new JButton("<html><h4>Credits</h4></html>");
        exit = new JButton("<html><h4>Exit</h4></html>");
        game1.addActionListener(this);
        game2.addActionListener(this);
        credits.addActionListener(this);
        exit.addActionListener(this);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.anchor = GridBagConstraints.NORTH;
        content.add(title, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        JPanel Buttons = new JPanel(new GridBagLayout());
        Buttons.add(game1, gbc);
        Buttons.add(game2, gbc);
        Buttons.add(credits, gbc);
        Buttons.add(exit, gbc);
        gbc.weighty = 1;
        content.add(Buttons);
        appWindow.add(content);
        appWindow.setVisible(true);
        appWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public static void main(String[] args) {
        new HumanBenchmarkApp();
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clicked = (JButton)e.getSource();
        if (clicked == game1) {

        }
        else if(clicked == game2) {

        }
        else if(clicked == credits) {

        }
        else if(clicked == exit) {
            System.exit(0);
        }
    }
}

CodePudding user response:

The problem is that your button Exit's name is not "Exit". Here's your code:

Exit = new JButton("<html><h4>Exit</h4></html>");

Instead you can compare if exit and clicked refers the same button as described by Agzam.

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clicked = (JButton)e.getSource();
        if (clicked == game1) {

        }
        else if(clicked == game2) {

        }
        else if(clicked == credits) {

        }
        else if(clicked == exit) {
            System.exit(0);
        }
    }
  • Related