I'm trying to run the following code for a simple Applet but i keep getting an error when I invoke the ItemListener. any1 know how I could fix this. When I check on any of the checkboxes " Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException" and the message i'm trying to display does not get displayed. The buttons work fine.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Hotel extends JApplet implements ActionListener{
JCheckBox cb1, cb2;
JButton b1, b2;
JLabel lb;
JTextField jt;
double tot,num;
public void init(){
Container cp=getContentPane();
cp.setLayout(null);
cb1=new JCheckBox("Single");
cb2=new JCheckBox ("Double");
b1=new JButton ("Amount");
b2= new JButton("Exit");
lb= new JLabel("");
jt=new JTextField();
jt.setBounds (100,100,70,20);
cb1.setBounds(100, 50,70,20);
cb2.setBounds(100,200,70,20);
b1.setBounds(100,250,100,20);
b2.setBounds(100,300,70,20);
lb.setBounds(100,400,200,20);
cp.add(lb);
cp.add(cb1);
cp.add(cb2);
cp.add(b1);
cp.add(b2);
cp.add(jt);
b1.addActionListener(this);
b2.addActionListener(new BtnExit());
cb1.addItemListener(new CBox());
cb2.addItemListener(new CBox2());
}
@Override
public void actionPerformed(ActionEvent ae) {
//this one works fine
num=Double.parseDouble(jt.getText());
if (cb1.isSelected()){
tot=10000*num;
}
if (cb2.isSelected()){
tot=15000*num;
lb.setText("15 000/room");
}
lb.setText(String.valueOf(tot));
}
}
class CBox implements ItemListener {
@Override
public void itemStateChanged(ItemEvent ie) {
//to display the price per room once the user ticks on "Single"
Hotel h=new Hotel();
h.lb.setVisible(true);
h.lb.setText("You will pay 10000/room");
}
}
class CBox2 implements ItemListener{
@Override
public void itemStateChanged(ItemEvent ie) {
//to display the price per room once the user ticks on the "Double" checkbox
Hotel h=new Hotel();
h.lb.setVisible(true);
h.lb.setText("You will pay 15 000/room");
}
}
You are creating new
Hotel
instances in the listeners, instead of modifying the old. You should pass the existing instance to the listener:And used like:
Furthermore, you should likely check the new check box state, rather than setting the label visible unconditionally. Just as an observation about the intended functionality (Implemented in the above code).
Similarly for the other item listener.
Alternatively you could use anonymous classes:
Also, you should really use layout managers. Swing is designed to work with those.
null
layouts are a disaster waiting to happen.