TestToggleButtons.java
Select all
/* TestToggleButtons.java David Klick CIS 260 2/14/06 Demonstrates use of JCheckBoxes and JRadioButtons. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestToggleButtons extends JFrame { JCheckBox chk1, chk2; JRadioButton rdo1, rdo2; ButtonGroup grp; JLabel lblOut; public static void main(String[] args) { TestToggleButtons app = new TestToggleButtons("Toggle Button Test"); } public TestToggleButtons() { this(""); } public TestToggleButtons(String title) { super(title); init(); } private void init() { // make Window shut down graphics thread properly setDefaultCloseOperation(EXIT_ON_CLOSE); // get content pane and set to GridLayout Container c = getContentPane(); c.setLayout(new GridLayout(3, 1, 20, 5)); // create widgets lblOut = new JLabel(); chk1 = new JCheckBox("Option 1"); chk2 = new JCheckBox("Option 2", true); rdo1 = new JRadioButton("Red", true); rdo2 = new JRadioButton("Blue"); // create group to make radio buttons work properly grp = new ButtonGroup(); grp.add(rdo1); grp.add(rdo2); // create panels for rows where needed JPanel pnlTop = new JPanel(); JPanel pnlCenter = new JPanel(); pnlTop.setLayout(new GridLayout(1,2)); pnlCenter.setLayout(new GridLayout(1,2)); // add widgets to panels and then content pane pnlTop.add(chk1); pnlTop.add(chk2); pnlCenter.add(rdo1); pnlCenter.add(rdo2); c.add(pnlTop); c.add(pnlCenter); c.add(lblOut); // create and add event handlers (listeners) MyRadioListener rdoLstnr = new MyRadioListener(); MyCheckListener chkLstnr = new MyCheckListener(); rdo1.addActionListener(rdoLstnr); rdo2.addActionListener(rdoLstnr); chk1.addActionListener(chkLstnr); chk2.addActionListener(chkLstnr); // make it live setSize(200, 100); setVisible(true); } class MyRadioListener implements ActionListener { public void actionPerformed(ActionEvent e) { String s = "You picked radio button #"; if (e.getSource() == rdo1) s += "1: " + e.getActionCommand(); else s += "2: " + e.getActionCommand(); lblOut.setText(s); } } class MyCheckListener implements ActionListener { public void actionPerformed(ActionEvent e) { String s = "You picked checkbox #"; if (e.getSource() == chk1) s += "1: " + e.getActionCommand(); else s += "2: " + e.getActionCommand(); lblOut.setText(s); } } }