首页 > 解决方案 > 从另一个类单击 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();
   }
}

标签: javaswing

解决方案


您的构造函数定义了一个具有本地(构造函数)范围的变量plzSelectLabel 。因此,类级别变量(具有相同名称)将不会被初始化,因此是 NPE。

提示:阅读有关变量范围的一些信息;-)


推荐阅读