【问题标题】:JCheckbox is not showing text in label when being selected选中时,JCheckbox 未在标签中显示文本
【发布时间】:2017-10-13 22:14:39
【问题描述】:

我有一个 JCheckbox,当单击复选框时,我想在标签内设置文本。

到目前为止,我已经声明了变量以及复选框和标签的框架内的设置:

JCheckBox chckbxIncludeExt;
        JLabel lblNewLabel_1;


JCheckBox chckbxIncludeExt = new JCheckBox("Include ext");
chckbxIncludeExt.setForeground(UIManager.getColor("Button.background"));
chckbxIncludeExt.setBackground(UIManager.getColor("Button.darkShadow"));
chckbxIncludeExt.setBounds(0, 264, 113, 25);
panel.add(chckbxIncludeExt);

JLabel lblNewLabel_1 = new JLabel("");
        lblNewLabel_1.setBounds(12, 311, 230, 16);
        panel.add(lblNewLabel_1);

我创建了一个类并在复选框中添加了一个项目侦听器:

CheckboxStatus checkboxd = new CheckboxStatus();
        chckbxIncludeExt.addItemListener(checkboxd);

这是我创建的类:

private class CheckboxStatus implements ItemListener{
        public void itemStateChanged(ItemEvent event){

            if (chckbxIncludeExt.isSelected()){
                lblNewLabel_1.setText("You have selected the checkbox");
            }



        }
    }

这给了我一个错误,显示:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.example.android.apis.appwidget.VFSTool$CheckboxStatus.itemStateChanged(VFSTool.java:199)
    at javax.swing.AbstractButton.fireItemStateChanged(Unknown Source)

错误出现在第 199 行,其中标签在第 199 行设置了文本。当我选中该框时,它显示了这一点,但不显示文本。

【问题讨论】:

  • 你如何将chckbxIncludeExt 设置为CheckboxStatus 类?

标签: java swing awt


【解决方案1】:

你正在遮蔽这些领域:

JCheckBox chckbxIncludeExt;
...
// and later:
JCheckBox chckbxIncludeExt = new JCheckBox("Include ext");

将后者改为:

chckbxIncludeExt = new JCheckBox("Include ext");

lblNewLabel_1 也有同样的问题

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 1970-01-01
    • 2012-04-09
    • 2021-11-27
    • 2019-07-26
    • 2017-08-21
    • 2014-02-13
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多