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

Java Swing报错Cannot invoke JFrame.setVisible因secondFrame为null怎么解决

错误原因

  • 你在构造方法中重复声明了局部变量JFrame secondFrame,这个局部变量和类成员变量secondFrame是两个完全独立的变量。
  • 构造方法里的初始化逻辑只赋值给了局部的secondFrame,类成员的secondFrame自始至终都没有被赋值,保持默认的null值,点击按钮调用secondFrame.setVisible()时就会触发空指针异常。

修复方案

把构造方法中JFrame secondFrame = new JFrame("Currency Converter");这行的JFrame声明去掉,直接给类成员变量赋值即可。

修改后完整代码

package com.company;

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

public class MyClass implements ActionListener
{
    JFrame firstFrame;
    JFrame secondFrame;
    JButton firstButton;

    public MyClass()
    {
        firstButton = new JButton("Convert Currencies");
        firstButton.setBounds(150, 100, 200, 50);
        firstButton.setText("Convert Currencies");
        firstButton.setFocusable(false);
        firstButton.setVisible(true);
        firstButton.setLayout(null);
        firstButton.addActionListener(this);

        firstFrame = new JFrame("Currency Converter");
        firstFrame.getContentPane().setBackground(new Color(0xD3D3D3));
        firstFrame.setSize(500, 700);
        firstFrame.setLocation(870,15);
        firstFrame.setResizable(false);
        firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        firstFrame.setVisible(true);
        firstFrame.setLayout(null);
        firstFrame.add(firstButton);

        // 去掉前面的JFrame声明,直接给成员变量赋值
        secondFrame = new JFrame("Currency Converter");
        secondFrame.getContentPane().setBackground(new Color(0xD3D3D3));
        secondFrame.setSize(500, 700);
        secondFrame.setLocation(870,15);
        secondFrame.setResizable(false);
        secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        secondFrame.setLayout(null);
        secondFrame.setVisible(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == firstButton)
        {
            firstFrame.setVisible(false);
            secondFrame.setVisible(true);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:06:04