java - 从另一个类单击 JButton 时更新 JLabel
问题描述
我想在单击 JButton 时更新 JLabel 的文本。问题是他们在不同的班级。
我尽可能地最小化了我的代码,所以这段代码并不包含我实际拥有的所有代码。
下面是第一个面板的代码,其中包含一个将触发文本更新方法的按钮。
public class CultureCategorySelectPanel extends JPanel {
public CultureCategorySelectPanel(JFrame mf) {
setVisible(true);
setLayout(null);
setSize(1000, 600);
JButton bookCategoryBtn = new JButton("Book");
// When Clicking on JButton
bookCategoryBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
mf.getContentPane().removeAll();
CultureListPanel myPanel = new CultureListPanel(mf);
mf.getContentPane().add(myPanel);
String text = “This text will be shown”;
myPanel.updateLabel(text);
mf.setVisible(true);
mf.repaint();
}
});
}
}
下面是第二个面板的代码,其中有一个将被更新的 textLabel。
private JLabel plzSelectLabel;
public CultureListPanel(JFrame mf) {
setVisible(true);
setLayout(null);
setSize(1000, 600);
JLabel plzSelectLabel = new JLabel(“This text soon be changed”);
plzSelectLabel.setHorizontalAlignment(SwingConstants.CENTER);
plzSelectLabel.setBounds(138, 89, 367, 34);
rightPanel.add(plzSelectLabel);
// 'rightPanel' is on the top of CultureListPanel, I put plzSelectLabel on the panel called 'rightPanel'
}
public void updateLabel(String text) {
plzSelectLabel.setText(text);
}
当我运行时,我在 com.kh.mini_Project.view.CultureListPanel.updateLabel(CultureListPanel.java:169) 错误
的线程“AWT-EventQueue-0” java.lang.NullPointerException中出现异常。
我也尝试过使用 getter/setter,但它显示了同样的错误。
编辑
下面的代码是 MainFrame。
import javax.swing.JFrame;
public class MainFrame extends JFrame{
public MainFrame() {
this.setTitle("--");
this.setSize(1000, 600);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.getContentPane().add(new WelcomPage(this));
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
编辑
Driver 类在这里。
public class Run {
public static void main(String[] args) {
new MainFrame();
}
}
解决方案
您的构造函数定义了一个具有本地(构造函数)范围的变量plzSelectLabel 。因此,类级别变量(具有相同名称)将不会被初始化,因此是 NPE。
提示:阅读有关变量范围的一些信息;-)
推荐阅读
- dialogflow-es - 如何在 dialogeflow 聊天机器人中将后续问题添加为 s 按钮?
- android - 如何在 android 中编辑和删除 XMPP 中的特定消息?
- javascript - Ajax 避免重新加载页面
- android - 使用 Android-ViewModel (MV-VM) 避免重复的网络调用
- python - 输出问题打印
- flutter - 将原始字符串转换为字符串
- php - PHP Dependency 为 5.5,当前运行的 PHP 为 7.2
- swift - iOS 13 大型导航栏外观 + Tabbar 图像
- excel - 如何将分组结果应用于 VAR.S?
- java - 如何制作具有动态值的@JSONProperty?