The following code produces an applet like this:
The radiobuttons are the circles that can be clicked on. Only one can be clicked at a time. This is different from a JCheckBox because more than one JCheckBox can be checked off.
They have the same life cycle as a button. The following happens in the init method.
Declare the JRadioButton | JRadioButton minsec; |
Construct the JRadioButton | minsec = new JRadioButton ("Minutes to seconds"); |
Set up the ActionListeners | minsec.addActionListener (this); |
minsec.setActionCommand ("minsec"); | |
Add the JRadioButton to the Applet | add (minsec); |
However, to control the JRadioButtons, so only one may selected at a time, all of the JRadioButtons need to be put in a ButtonGroup.
Declare and Construct the ButtonGroup | ButtonGroup group = new ButtonGroup (); |
Add the JRadioButton to the ButtonGroup | group.add (minsec); |
Then, in ActionPerformed, you can use the information from which JRadioButton is selected:
Check that the actionCommand matches the JRadioButton | if (e.getActionCommand ().equals ("minSec")) |
The full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class timeConvert extends Applet implements ActionListener
{
JRadioButton minsec, minhour;
JTextField mins;
JLabel result;
public void init ()
{
JLabel ins = new JLabel ("Enter the time in minuters: ");
mins = new JTextField (4);
Panel p = new Panel ();
p.add (ins);
p.add (mins);
minsec = new JRadioButton ("Minutes to seconds");
minsec.addActionListener (this);
minsec.setActionCommand ("minsec");
minhour = new JRadioButton ("Minutes to Hour:Minute");
minhour.addActionListener (this);
minhour.setActionCommand ("minhour");
ButtonGroup group = new ButtonGroup ();
group.add (minsec);
group.add (minhour);
Panel p2 = new Panel (new GridLayout (2, 1));
p2.add (minsec);
p2.add (minhour);
result = new JLabel ("The result is: ");
result.setPreferredSize (new Dimension (250, 20));
add (p);
add (p2);
add (result);
}
public void actionPerformed (ActionEvent e)
{
try
{
if (e.getActionCommand ().equals ("minSec"))
{
int minute = Integer.parseInt (mins.getText ());
minute *= 60;
result.setText ("The time in seconds is " + minute);
}
else
{
int minute = Integer.parseInt (mins.getText ());
int hour = minute / 60;
minute = minute % 60;
result.setText ("In hour:minute format it is " + hour + ":"
+ minute);
}
}
catch (Exception ee)
{
result.setText ("Enter a number first. Re-select radio button.");
}
}
}