The following code makes something like this:
The checkboxes are the little square things that you can check off.
They have the same life cycle as a button:
Declaring (Global or in Init) | JCheckBox shampoo; |
Construction (Only in Init) | shampoo = new JCheckBox ("Shampoo $15"); |
Setting up the ActionListener (Only in Init) | shampoo.setActionCommand ("shampoo"); shampoo.addActionListener (this); |
Adding it to the applet (Only in Init) | add(shampoo); |
Check if it was clicked (In ActionPerformed) | if (e.getActionCommand ().equals ("shampoo")) |
Set it to be unselected (ActionPerformed or Init) | shampoo.setSelected(false); |
The complete code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class petstore extends Applet implements ActionListener
{
JCheckBox shampoo, fleaDip, trim, cutNails;
JLabel result;
int total = 0;
public void init ()
{
JLabel title = new JLabel ("Select the pet grooming services:");
shampoo = new JCheckBox ("Shampoo $15");
shampoo.setActionCommand ("shampoo");
shampoo.addActionListener (this);
fleaDip = new JCheckBox ("Flea Dip $10");
fleaDip.setActionCommand ("fleaDip");
fleaDip.addActionListener (this);
trim = new JCheckBox ("Trim Hair $15");
trim.setActionCommand ("trim");
trim.addActionListener (this);
cutNails = new JCheckBox ("Cut Nails $5");
cutNails.setActionCommand ("cutNails");
cutNails.addActionListener (this);
JButton done = new JButton ("Next Customer - Reset");
done.setActionCommand ("done");
done.addActionListener (this);
result = new JLabel ("Total: $0.00 ");
Panel p = new Panel (new GridLayout (2, 2));
p.add (shampoo);
p.add (fleaDip);
p.add (trim);
p.add (cutNails);
add (title);
add (p);
add (result);
add (done);
}
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand ().equals ("shampoo"))
total += 15;
else if (e.getActionCommand ().equals ("fleaDip"))
total += 10;
else if (e.getActionCommand ().equals ("trim"))
total += 15;
else if (e.getActionCommand ().equals ("cutNails"))
total += 5;
else
{
total = 0;
shampoo.setSelected(false);
fleaDip.setSelected(false);
trim.setSelected(false);
cutNails.setSelected(false);
}
result.setText ("Total: $" + total);
}
}