Reputation: 1229
I have a JCheckbox and when clicking the checkbox I want to setText within a label.
So far I have the variables declared and the settings within the frame for the checkbox and the label:
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);
I have created a class and added an item listener to the checkbox:
CheckboxStatus checkboxd = new CheckboxStatus();
chckbxIncludeExt.addItemListener(checkboxd);
This is the class I have created:
private class CheckboxStatus implements ItemListener{
public void itemStateChanged(ItemEvent event){
if (chckbxIncludeExt.isSelected()){
lblNewLabel_1.setText("You have selected the checkbox");
}
}
}
This is giving me an error that shows:
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)
The error is on line 199 where the label sets the text in line 199. When I check the box it shows this and does not show the text.
Upvotes: 0
Views: 648
Reputation: 6618
You are shadowing the fields:
JCheckBox chckbxIncludeExt;
...
// and later:
JCheckBox chckbxIncludeExt = new JCheckBox("Include ext");
Change the later to just:
chckbxIncludeExt = new JCheckBox("Include ext");
You have the same problem with lblNewLabel_1
Upvotes: 3