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
相关产品推荐
相关产品推荐

