Helpful Information
 
 
Category: Java and JSP
Java code problem

Here's a program I'm trying to write that uses checkboxes. But when I compile it, it doesn't work. Can anyone please point out any errors they see in the code?

import java.applet.Applet.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test extends JApplet implements ActionListener
{
String companyName = new String("Event Handlers, Inc");
Font bigFont = new Font("Arial", Font.PLAIN, 24);
JCheckBox cocktailBox = new JCheckBox("Cocktails");
JCheckBox dinnerBox = new JCheckBox("Dinner");
int cocktailPrice = 300, dinnerPrice = 600, totalPrice = 200;

public void init()
{
add(cocktailBox);
cocktailBox.addActionListener(this);
add(dinnerBox);
dinnerBox.addActionListener(this);
}

public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName, 10, 100);
gr.drawString("Event Price Estimate", 10, 150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice), 280, 150);
}

public void itemStateChanged(ActionEvent check)
{
totalPrice = 200;
if(cocktailBox.getState())
{
totalPrice += cocktailPrice;
}
if(dinnerBox.getState())
{
totalPrice += dinnerPrice;
}
repaint();
}
}

What's the error message you get when compiling?

Taken from official Java API doc:

The JApplet class is slightly incompatible with java.applet.Applet. JApplet contains a JRootPane as it's only child. The contentPane should be the parent of any children of the JApplet. This is different than java.applet.Applet, e.g. to add a child to an an java.applet.Applet you'd write:

applet.add(child);

However using JApplet you need to add the child to the JApplet's contentPane instead:

applet.getContentPane().add(child);










privacy (GDPR)