我正在尝试为一个简单的 Applet 运行以下代码,但是当我调用 ItemListener 时,我不断收到错误消息。any1 知道我该如何解决这个问题。当我检查任何复选框“线程“AWT-EventQueue-1”中的异常“java.lang.NullPointerException”并且我尝试显示的消息没有显示时。按钮工作正常。
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");
}
}