-
Problem with checkboxes
Hi, 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?
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();
}
}
Thanks.
-
Code:
C:\jexp>javac compiletest.java
compiletest.java:7: CompileTest is not abstract and does not override abstract m
ethod actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListen
er
public class CompileTest extends JApplet implements ActionListener
^
compiletest.java:36: cannot find symbol
symbol : method getState()
location: class javax.swing.JCheckBox
if(cocktailBox.getState())
^
compiletest.java:40: cannot find symbol
symbol : method getState()
location: class javax.swing.JCheckBox
if(dinnerBox.getState())
^
3 errors
1 — The class signature implements ActionListener. The rule/contract with interfaces is this: if you implement an interface you promise to provide an implementation for each method it defines. Look up the ActionListener interface in the javadocs and find its only method is
Code:
public void actionPerformed(ActionEvent e) { }
This exact method signature must appear in the class that implements the ActionListener interface.
2 — getState is in the java.awt.Checkbox class api.
You are using a javax.swing.JCheckBox, a very different component. For this class you would use the isSelected method which JCheckBox inherits from its superclass AbstractButton - see JCheckBox api.
This method signature is incorrect.
Code:
public void itemStateChanged(ActionEvent check)
The itemStateChanged method is defined by the ItemListener interface and its argument is an ItemEvent.