You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JFrame窗口无法关闭求助:测验应用Back按钮功能失效

问题排查与解决

你的代码核心问题是没有给按钮注册事件监听器——虽然你的类实现了ActionListener接口,但按钮并没有绑定这个监听器,所以点击Back按钮时,actionPerformed方法根本不会被触发,setVisible(false)这类代码自然不会执行。

修复步骤

  • 在初始化按钮后,给Rules和Back按钮添加监听器:调用Rules.addActionListener(this)和Back.addActionListener(this)
  • 若需要彻底释放窗口资源,可在Back按钮的逻辑里追加dispose();如果是要退出整个应用,还可以加上System.exit(0)

修改后的完整代码

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

public class Login extends JFrame implements ActionListener {
    JButton Rules, Back;

    Login() {
        getContentPane().setBackground(Color.white);
        ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("icon/login.jpeg"));//<-- to pick images from directory
        setLayout(null);
        JLabel image = new JLabel(i1);

        JLabel heading = new JLabel("Quiz Bazzi");
        heading.setBounds(750,50,300,50);
        heading.setFont(new Font("Mongolian Baiti",Font.BOLD,42));
        heading.setForeground(Color.ORANGE);
        add(heading);

        JLabel name = new JLabel("Enter Your Name");
        name.setBounds(785,150,350,20);
        name.setFont(new Font("Mongolian Baiti",Font.BOLD,18));
        name.setForeground(Color.black);
        add(name);

        JTextField tfname = new JTextField();
        tfname.setBounds(715,180,300,25);
        tfname.setFont(new Font("Times New Roman",Font.BOLD,18));
        tfname.setForeground(Color.black);
        add(tfname);

        Rules = new JButton("Rules");
        Rules.setBounds(715,220,120,25);
        Rules.setBackground(Color.black);
        Rules.setForeground(Color.white);
        Rules.addActionListener(this); // 给按钮绑定监听器
        add(Rules);

        Back = new JButton("Back");
        Back.setBounds(895,220,120,25);
        Back.setBackground(Color.black);
        Back.setForeground(Color.white);
        Back.addActionListener(this); // 给按钮绑定监听器
        add(Back);

        image.setBounds(0,0,500,400);
        add(image);

        setSize(1200,439);
        setLocation(180,100);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e){
        if(e.getSource() == Rules){
            // 此处可根据需求跳转到规则页面,当前仅保持窗口可见
            setVisible(true);
        } else if (e.getSource() == Back) {
            setVisible(false);
            dispose(); // 释放窗口资源(可选)
            // System.exit(0); // 若要退出整个应用可开启此行
        }
    }

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

内容的提问来源于stack exchange,提问作者Newbie coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:41:12