选中时,JCheckbox未在标签中显示文本

时间:2013-09-15 17:33:14

标签: java swing awt

我有一个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行中的文本。当我选中该框时,它显示此内容并且不显示文本。

1 个答案:

答案 0 :(得分:3)

你正在遮蔽这些字段:

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

将后者更改为:

chckbxIncludeExt = new JCheckBox("Include ext");

lblNewLabel_1

存在同样的问题