[英]Call function on a JFrame from a JPanel class
I have a login JPanel
which was programmatically added inside the JFrame
. 我有一个登录JPanel
,它以编程方式添加到JFrame
。 The problem is I want to call a function on a JFrame
from the login JPanel
class using a button. 问题是我想使用按钮从登录JPanel
类调用JFrame
上的函数。
Here, I've declared the MainFrame
as mainFrame
in the PartLogin
JPanel
class: 在这里,我已经在PartLogin
JPanel
类中将MainFrame
声明为mainFrame
:
public class PartLogin extends JPanel {
MainFrame mainFrame;
Then, I've created a public function from the JFrame
, then called it from PartLogin
through a button click 然后,我从JFrame
创建了一个公共函数,通过单击按钮从PartLogin
进行了调用
mainFrame.changeLabel();
I've got an NullPointerException
pointing inside the buttonclick code. 我在buttonclick代码中指向了一个NullPointerException
。
mainFrame.changeLabel();
A NullPointerException
normally says that an object that is needed to be not null is null. NullPointerException
通常表示需要为非null的对象为null。 Here, this is probably mainFrame
. 在这里,这可能是mainFrame
。 Java is not C++, so the statement is equal to: Java不是C ++,因此该语句等于:
MainFrame mainFrame = null;
You should change this so that mainFrame
is not null. 您应该对此进行更改,以使mainFrame
不为null。 There are two ways: 有两种方法:
assign value in declaration: 在声明中赋值:
MainFrame mainFrame = new MainFrame();
assign value in constructor: 在构造函数中赋值:
private MainFrame mainFrame; // don't must be private public PartLogin () { super(); // call ctor of superclass mainFrame = new MainFrame(); // ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.