0

我有一个 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 行设置了文本。当我选中该框时,它显示了这一点并且不显示文本。

4

1 回答 1

3

您正在遮蔽这些字段:

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

将后者更改为:

chckbxIncludeExt = new JCheckBox("Include ext");

你有同样的问题lblNewLabel_1

于 2013-09-15T17:43:52.910 回答