Java/Swing JFC/CheckBox Button

Материал из Java эксперт
Перейти к: навигация, поиск

Adding an Icon to the Label of a JCheckBox Component

   <source lang="java">

import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JCheckBox checkbox = new JCheckBox();
String label = "<html>
<img src=file:" + "icon.gif" + "/>"
       // Retrieve the current label text
+ checkbox.getText() + "
</html>";
   // Add the icon
   checkbox.setText(label);
 }

}

 </source>
   
  
 
  



Bad Checkbox UI

   <source lang="java">

import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.AbstractButton; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.plaf.ruponentUI; import javax.swing.plaf.basic.BasicCheckBoxUI; public class MyCheckBoxUI extends BasicCheckBoxUI implements

   java.io.Serializable, MouseListener {
 private final static MyCheckBoxUI buttonUI = new MyCheckBoxUI();
 public MyCheckBoxUI() {
 }
 public static ComponentUI createUI(JComponent c) {
   return buttonUI;
 }
 public void installUI(JComponent c) {
   super.installUI(c);
   c.setBackground(Color.red);
   c.addMouseListener(this);
 }
 public void uninstallUI(JComponent c) {
   super.uninstallUI(c);
   c.removeMouseListener(this);
 }
 public void paint(Graphics g, JComponent c) {
   AbstractButton b = (AbstractButton) c;
   ButtonModel model = b.getModel();
   Dimension d = b.getSize();
   g.setFont(c.getFont());
   FontMetrics fm = g.getFontMetrics();
   g.setColor(Color.white);
   g.drawString("Am I a check box", 10, 10);
 }
 public void mouseClicked(MouseEvent e) {
 }
 public void mousePressed(MouseEvent e) {
 }
 public void mouseReleased(MouseEvent e) {
 }
 public void mouseEntered(MouseEvent e) {
   JComponent c = (JComponent) e.getComponent();
   c.setBackground(Color.blue);
   c.repaint();
 }
 public void mouseExited(MouseEvent e) {
   JComponent c = (JComponent) e.getComponent();
   c.setBackground(Color.red);
   c.repaint();
 }
 public static void main(String[] argv) {
   JFrame f = new JFrame();
   f.setSize(400, 300);
   f.getContentPane().setLayout(new FlowLayout());
   JPanel p = new JPanel();
   JCheckBox bt1 = new JCheckBox("Click Me");
   bt1.setUI(new MyCheckBoxUI());
   p.add(bt1);
   f.getContentPane().add(p);
   WindowListener wndCloser = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   f.addWindowListener(wndCloser);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



CheckBox Demo 2

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.Border; public class ACheckBox {

 public static void main(String args[]) {
   String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
   JFrame frame = new JFrame(title);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel panel = new JPanel(new GridLayout(0, 1));
   Border border = BorderFactory.createTitledBorder("Pizza Toppings");
   panel.setBorder(border);
   JCheckBox check = new JCheckBox("Anchovies");
   panel.add(check);
   check = new JCheckBox("Garlic");
   panel.add(check);
   check = new JCheckBox("Onions");
   panel.add(check);
   check = new JCheckBox("Pepperoni");
   panel.add(check);
   check = new JCheckBox("Spinach");
   panel.add(check);
   JButton button = new JButton("Submit");
   Container contentPane = frame.getContentPane();
   contentPane.add(panel, BorderLayout.CENTER);
   contentPane.add(button, BorderLayout.SOUTH);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Check boxes with item changed event.

   <source lang="java">

import java.awt.FlowLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JCheckBox; import javax.swing.JFrame; public class Main implements ItemListener {

 JCheckBox jcbControl = new JCheckBox("Translate");
 JCheckBox jcbOption1 = new JCheckBox("A");
 JCheckBox jcbOption2 = new JCheckBox("B");
 JCheckBox jcbOption3 = new JCheckBox("C");
 Main() {
   JFrame jfrm = new JFrame("Check Box Demo");
   jfrm.setLayout(new FlowLayout());
   jfrm.setSize(300, 200);
   jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   jcbOption1.setEnabled(false);
   jcbOption2.setEnabled(false);
   jcbOption3.setEnabled(false);
   jcbControl.addItemListener(new ItemListener() {
     public void itemStateChanged(ItemEvent ie) {
       if (jcbControl.isSelected()) {
         jcbOption1.setEnabled(true);
         jcbOption2.setEnabled(true);
         jcbOption3.setEnabled(true);
         System.out.println("enabled.");
       } else {
         jcbOption1.setEnabled(false);
         jcbOption2.setEnabled(false);
         jcbOption3.setEnabled(false);
         System.out.println("disabled.");
       }
     }
   });
   jcbOption1.addItemListener(this);
   jcbOption2.addItemListener(this);
   jcbOption3.addItemListener(this);
   jfrm.add(jcbControl);
   jfrm.add(jcbOption1);
   jfrm.add(jcbOption2);
   jfrm.add(jcbOption3);
   jfrm.setVisible(true);
 }
 public void itemStateChanged(ItemEvent ie) {
   JCheckBox cb = (JCheckBox) ie.getItem();
   if (ie.getStateChange() == ItemEvent.SELECTED)
     System.out.println(cb.getText() + " selected.");
   else
     System.out.println(cb.getText() + " cleared.");
   if (jcbOption1.isSelected())
     System.out.println("1");
   else if (jcbOption2.isSelected())
     System.out.println("2");
   else if (jcbOption3.isSelected())
     System.out.println("3");
   else
     System.out.println("None");
 }
 public static void main(String args[]) {
   new Main();
 }

}

 </source>
   
  
 
  



CheckBox Item Listener

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.AbstractButton; import javax.swing.ButtonModel; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class SelectingCheckBox {

 private static String DESELECTED_LABEL = "Deselected";
 private static String SELECTED_LABEL = "Selected";
 public static void main(String args[]) {
   JFrame frame = new JFrame("Selecting CheckBox");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JCheckBox checkBox = new JCheckBox(DESELECTED_LABEL);
   ActionListener actionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       AbstractButton abstractButton = (AbstractButton)actionEvent.getSource();
       boolean selected = abstractButton.getModel().isSelected();
       String newLabel = (selected ? SELECTED_LABEL : DESELECTED_LABEL);
       abstractButton.setText(newLabel);
     }
   };
   ChangeListener changeListener = new ChangeListener() {
     public void stateChanged(ChangeEvent changeEvent) {
       AbstractButton abstractButton = (AbstractButton)changeEvent.getSource();
       ButtonModel buttonModel = abstractButton.getModel();
       boolean armed = buttonModel.isArmed();
       boolean pressed = buttonModel.isPressed();
       boolean selected = buttonModel.isSelected();
       System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
     }
   };
   ItemListener itemListener = new ItemListener() {
     public void itemStateChanged(ItemEvent itemEvent) {
       AbstractButton abstractButton = (AbstractButton)itemEvent.getSource();
       Color foreground = abstractButton.getForeground();
       Color background = abstractButton.getBackground();
       int state = itemEvent.getStateChange();
       if (state == ItemEvent.SELECTED) {
         abstractButton.setForeground(background);
         abstractButton.setBackground(foreground);
       }
     }
   };
   checkBox.addActionListener(actionListener);
   checkBox.addChangeListener(changeListener);
   checkBox.addItemListener(itemListener);
   checkBox.setMnemonic(KeyEvent.VK_S);
   Container contentPane = frame.getContentPane();
   contentPane.add(checkBox, BorderLayout.NORTH);
   frame.setSize(300, 100);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



CheckBox Mnemonic

   <source lang="java">

import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; public class CheckBoxMnemonic extends JPanel {

 public CheckBoxMnemonic() {
   JCheckBox m_chkBold = new JCheckBox("Bold");
   m_chkBold.setMnemonic("b");
   m_chkBold.setToolTipText("Bold font");
   add(m_chkBold);
   setBorder(new TitledBorder(new EtchedBorder(), "Effects"));
   JCheckBox m_chkItalic = new JCheckBox("Italic");
   m_chkItalic.setMnemonic("i");
   m_chkItalic.setToolTipText("Italic font");
   add(m_chkItalic);
   JCheckBox m_chkUnderline = new JCheckBox("Underline");
   m_chkUnderline.setMnemonic("u");
   m_chkUnderline.setToolTipText("Underline font");
   add(m_chkUnderline);
   JCheckBox m_chkStrikethrough = new JCheckBox("Strikethrough");
   m_chkStrikethrough.setMnemonic("r");
   m_chkStrikethrough.setToolTipText("Strikethrough font");
   add(m_chkStrikethrough);
   JCheckBox m_chkSubscript = new JCheckBox("Subscript");
   m_chkSubscript.setMnemonic("t");
   m_chkSubscript.setToolTipText("Subscript font");
   add(m_chkSubscript);
   JCheckBox m_chkSuperscript = new JCheckBox("Superscript");
   m_chkSuperscript.setMnemonic("p");
   m_chkSuperscript.setToolTipText("Superscript font");
   add(m_chkSuperscript);
 }
 public static void main(String[] a) {
   JFrame f = new JFrame();
   f.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   f.getContentPane().add(new CheckBoxMnemonic());
   f.pack();
   f.setSize(new Dimension(300, 200));
   f.show();
 }

}


 </source>
   
  
 
  



Creating a JCheckbox Component

   <source lang="java">

import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   Action action = new AbstractAction("CheckBox Label") {
     // called when the button is pressed
     public void actionPerformed(ActionEvent evt) {
       JCheckBox cb = (JCheckBox) evt.getSource();
       // Determine status
       boolean isSel = cb.isSelected();
       if (isSel) {
         // selected
       } else {
         // deselected
       }
     }
   };
   // Create the checkbox from the action
   JCheckBox checkBox = new JCheckBox(action);
 }

}

 </source>
   
  
 
  



Customize JCheckBox icons

   <source lang="java">

import java.awt.FlowLayout; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFrame; public class JCheckBoxCustomIcon extends JFrame {

 public JCheckBoxCustomIcon() {
   setSize(300, 300);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLayout(new FlowLayout(FlowLayout.LEFT));
   JCheckBox checkBox = new JCheckBox("Check me!");
   checkBox.setSelected(true);
   // Set default icon for checkbox
   checkBox.setIcon(new ImageIcon("icon.png"));
   // Set selected icon when checkbox state is selected
   checkBox.setSelectedIcon(new ImageIcon("selectedIcon.png"));
   // Set disabled icon for checkbox
   checkBox.setDisabledIcon(new ImageIcon("disabledIcon.png"));
   // Set disabled-selected icon for checkbox
   checkBox.setDisabledSelectedIcon(new ImageIcon("disabledSelectedIcon.png"));
   // Set checkbox icon when checkbox is pressed
   checkBox.setPressedIcon(new ImageIcon("pressedIcon.png"));
   // Set icon when a mouse is over the checkbox
   checkBox.setRolloverIcon(new ImageIcon("rolloverIcon.png"));
   // Set icon when a mouse is over a selected checkbox
   checkBox.setRolloverSelectedIcon(new ImageIcon("rolloverSelectedIcon.png"));
   getContentPane().add(checkBox);
 }
 public static void main(String[] args) {
   new JCheckBoxCustomIcon().setVisible(true);
 }

}

 </source>
   
  
 
  



Customize these disabled icons

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JCheckBox checkbox = new JCheckBox();
   // Set the unselected state icon
   Icon unselDisIcon = new ImageIcon("nosel-dis-icon.gif");
   checkbox.setDisabledIcon(unselDisIcon);
   // Set the selected state icon
   Icon selDisIcon = new ImageIcon("sel-dis-icon.gif");
   checkbox.setDisabledSelectedIcon(selDisIcon);
 }

}

 </source>
   
  
 
  



Customizing the Icons in a JCheckBox Component

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JCheckBox checkbox = new JCheckBox();
   // Set the unselected state icon
   Icon unselIcon = new ImageIcon("nosel-icon.gif");
   checkbox.setIcon(unselIcon);
   // Set the selected state icon
   Icon selIcon = new ImageIcon("sel-icon.gif");
   checkbox.setSelectedIcon(selIcon);
 }

}

 </source>
   
  
 
  



Display an icon when the cursor is moved over the checkbox. This is called the rollover icon.

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JCheckBox checkbox = new JCheckBox();
   Icon rollIcon = new ImageIcon("roll-icon.gif");
   checkbox.setRolloverIcon(rollIcon);
 }

}

 </source>
   
  
 
  



Flat CheckBox

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.Border; public class FlatCheckBox {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Flat CheckBox Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel panel = new JPanel(new GridLayout(0, 1));
   Border border = BorderFactory.createTitledBorder("Pizza Toppings");
   panel.setBorder(border);
   JCheckBox check = new JCheckBox("Anchovies");
   check.setBorderPaintedFlat(true);
   panel.add(check);
   check = new JCheckBox("Garlic");
   panel.add(check);
   check = new JCheckBox("Onions");
   check.setBorderPaintedFlat(true);
   panel.add(check);
   check = new JCheckBox("Pepperoni");
   panel.add(check);
   check = new JCheckBox("Spinach");
   check.setBorderPaintedFlat(true);
   panel.add(check);
   JButton button = new JButton("Submit");
   Container contentPane = frame.getContentPane();
   contentPane.add(panel, BorderLayout.CENTER);
   contentPane.add(button, BorderLayout.SOUTH);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Get or set the selection state of JCheckBox

   <source lang="java">

import java.awt.FlowLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; public class CheckBoxState extends JFrame {

 public CheckBoxState() {
   setSize(300, 300);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLayout(new FlowLayout(FlowLayout.LEFT));
   JCheckBox checkBox = new JCheckBox("Check me!");
   checkBox.setSelected(true);
   boolean selected = checkBox.isSelected();
   if (selected) {
     System.out.println("Check box state is selected.");
   } else {
     System.out.println("Check box state is not selected.");
   }
   getContentPane().add(checkBox);
 }
 public static void main(String[] args) {
   new CheckBoxState().setVisible(true);
 }

}

 </source>
   
  
 
  



Getting and Setting the State of a JCheckbox Component

   <source lang="java">

import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JCheckBox checkbox = new JCheckBox();
   // Get the current state of the checkbox
   boolean b = checkbox.isSelected();
   // Set the state of the checkbox to off
   checkbox.setSelected(false);
   // Set the state of the checkbox to on
   checkbox.setSelected(true);
 }

}

 </source>
   
  
 
  



How to use the check box button

   <source lang="java">

import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class CheckBoxDemo extends JFrame implements ActionListener {

 JLabel fontLabel = new JLabel("The quick brown fox jumps over the lazy dog.");
 private JCheckBox bold= new JCheckBox("Bold");
 private JCheckBox italic = new JCheckBox("Italic");
 public CheckBoxDemo() {
   setTitle("CheckBoxTest");
   setSize(300, 200);
   addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   JPanel p = new JPanel();
   p.add(bold);
   p.add(italic);
   bold.addActionListener(this);
   italic.addActionListener(this);
   getContentPane().add(p, "South");
   getContentPane().add(fontLabel, "Center");
 }
 public void actionPerformed(ActionEvent evt) {
   int m = (bold.isSelected() ? Font.BOLD : 0)
       + (italic.isSelected() ? Font.ITALIC : 0);
   fontLabel.setFont(new Font("SansSerif", m, 12));
 }
 
 public static void main(String[] args) {
   JFrame frame = new CheckBoxDemo();
   frame.show();
 }

}


 </source>
   
  
 
  



Icon CheckBox Demo

   <source lang="java">

import java.awt.Color; import java.awt.ruponent; import java.awt.Container; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.awt.Polygon; import javax.swing.AbstractButton; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFrame; public class IconCheckBoxSample {

 private static class CheckBoxIcon implements Icon {
   private ImageIcon checkedIcon = new ImageIcon("Plus.gif");
   private ImageIcon uncheckedIcon = new ImageIcon("Minus.gif");
   public void paintIcon(Component component, Graphics g, int x, int y) {
     AbstractButton abstractButton = (AbstractButton) component;
     ButtonModel buttonModel = abstractButton.getModel();
     g.translate(x, y);
     ImageIcon imageIcon = buttonModel.isSelected() ? checkedIcon
         : uncheckedIcon;
     Image image = imageIcon.getImage();
     g.drawImage(image, 0, 0, component);
     g.translate(-x, -y);
   }
   public int getIconWidth() {
     return 20;
   }
   public int getIconHeight() {
     return 20;
   }
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Iconizing CheckBox");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Icon checked = new DiamondIcon(Color.black, true);
   Icon unchecked = new DiamondIcon(Color.black, false);
   JCheckBox aCheckBox1 = new JCheckBox("Pizza", unchecked);
   aCheckBox1.setSelectedIcon(checked);
   JCheckBox aCheckBox2 = new JCheckBox("Calzone");
   aCheckBox2.setIcon(unchecked);
   aCheckBox2.setSelectedIcon(checked);
   Icon checkBoxIcon = new CheckBoxIcon();
   JCheckBox aCheckBox3 = new JCheckBox("Anchovies", checkBoxIcon);
   JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust", checked);
   Container contentPane = frame.getContentPane();
   contentPane.setLayout(new GridLayout(0, 1));
   contentPane.add(aCheckBox1);
   contentPane.add(aCheckBox2);
   contentPane.add(aCheckBox3);
   contentPane.add(aCheckBox4);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

} class DiamondIcon implements Icon {

 private Color color;
 private boolean selected;
 private int width;
 private int height;
 private Polygon poly;
 private static final int DEFAULT_WIDTH = 10;
 private static final int DEFAULT_HEIGHT = 10;
 public DiamondIcon(Color color) {
   this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
 }
 public DiamondIcon(Color color, boolean selected) {
   this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
 }
 public DiamondIcon(Color color, boolean selected, int width, int height) {
   this.color = color;
   this.selected = selected;
   this.width = width;
   this.height = height;
   initPolygon();
 }
 private void initPolygon() {
   poly = new Polygon();
   int halfWidth = width / 2;
   int halfHeight = height / 2;
   poly.addPoint(0, halfHeight);
   poly.addPoint(halfWidth, 0);
   poly.addPoint(width, halfHeight);
   poly.addPoint(halfWidth, height);
 }
 public int getIconHeight() {
   return height;
 }
 public int getIconWidth() {
   return width;
 }
 public void paintIcon(Component c, Graphics g, int x, int y) {
   g.setColor(color);
   g.translate(x, y);
   if (selected) {
     g.fillPolygon(poly);
   } else {
     g.drawPolygon(poly);
   }
   g.translate(-x, -y);
 }

}


 </source>
   
  
 
  



JCheckBox is a widget that has two states. On and Off.

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JCheckBox; import javax.swing.JFrame; public class CheckBox extends JFrame implements ActionListener {

 public CheckBox() {
   JCheckBox checkbox = new JCheckBox("Show Title", true);
   checkbox.addActionListener(this);
   add(checkbox);
   setSize(280, 200);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String[] args) {
   new CheckBox();
 }
 public void actionPerformed(ActionEvent e) {
   if (this.getTitle() == "") {
     this.setTitle("Checkbox example");
   } else {
     this.setTitle("");
   }
 }

}

 </source>
   
  
 
  



Radio button, ComboBox

   <source lang="java">

import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.border.Border; public class ARadioCombo {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Radio/Combo Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel panel = new JPanel(new GridLayout(0, 1));
   Border border = BorderFactory.createTitledBorder("Radio Buttons");
   panel.setBorder(border);
   ButtonGroup group = new ButtonGroup();
   JRadioButton aRadioButton = new JRadioButton("4 slices");
   panel.add(aRadioButton);
   group.add(aRadioButton);
   aRadioButton = new JRadioButton("8 slices", true);
   panel.add(aRadioButton);
   group.add(aRadioButton);
   aRadioButton = new JRadioButton("12 slices");
   panel.add(aRadioButton);
   group.add(aRadioButton);
   aRadioButton = new JRadioButton("16 slices");
   panel.add(aRadioButton);
   group.add(aRadioButton);
   Container contentPane = frame.getContentPane();
   contentPane.add(panel, BorderLayout.WEST);
   panel = new JPanel(new GridLayout(0, 1));
   border = BorderFactory.createTitledBorder("Check Boxes");
   panel.setBorder(border);
   JCheckBox aCheckBox = new JCheckBox("Anchovies");
   panel.add(aCheckBox);
   aCheckBox = new JCheckBox("Garlic", true);
   panel.add(aCheckBox);
   aCheckBox = new JCheckBox("Onions");
   panel.add(aCheckBox);
   aCheckBox = new JCheckBox("Spinach");
   panel.add(aCheckBox);
   contentPane.add(panel, BorderLayout.EAST);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Set pressed icon

   <source lang="java">

import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; public class Main {

 public static void main(String[] argv) throws Exception {
   JCheckBox checkbox = new JCheckBox();
   Icon pressedIcon = new ImageIcon("pres-icon.gif");
   checkbox.setPressedIcon(pressedIcon);
 }

}

 </source>
   
  
 
  



Swing CheckBox Demo

   <source lang="java">

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
*  this list of conditions and the following disclaimer in the documentation
*  and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /*

* SwingCheckBoxDemo.java is a 1.4 application that requires 16 image files
* in the images/geek directory: 
* geek-----.gif, geek-c---.gif, geek--g--.gif, geek---h-.gif, geek----t.gif,
* geek-cg--.gif, ..., geek-cght.gif.
*/

public class SwingCheckBoxDemo extends JPanel

                         implements ItemListener {
   JCheckBox chinButton;
   JCheckBox glassesButton;
   JCheckBox hairButton;
   JCheckBox teethButton;
   /*
    * Four accessory choices provide for 16 different
    * combinations. The image for each combination is
    * contained in a separate image file whose name indicates
    * the accessories. The filenames are "geek-XXXX.gif"
    * where XXXX can be one of the following 16 choices.
    * The "choices" StringBuffer contains the string that
    * indicates the current selection and is used to generate
    * the file name of the image to display.
      ----             //zero accessories
      c---             //one accessory
      -g--
      --h-
      ---t
      cg--             //two accessories
      c-h-
      c--t
      -gh-
      -g-t
      --ht
      -ght             //three accessories
      c-ht
      cg-t
      cgh-
      cght             //all accessories
    */
   StringBuffer choices;
   JLabel pictureLabel;
   public SwingCheckBoxDemo() {
       super(new BorderLayout());
       //Create the check boxes.
       chinButton = new JCheckBox("Chin");
       chinButton.setMnemonic(KeyEvent.VK_C);
       chinButton.setSelected(true);
       glassesButton = new JCheckBox("Glasses");
       glassesButton.setMnemonic(KeyEvent.VK_G);
       glassesButton.setSelected(true);
       hairButton = new JCheckBox("Hair");
       hairButton.setMnemonic(KeyEvent.VK_H);
       hairButton.setSelected(true);
       teethButton = new JCheckBox("Teeth");
       teethButton.setMnemonic(KeyEvent.VK_T);
       teethButton.setSelected(true);
       //Register a listener for the check boxes.
       chinButton.addItemListener(this);
       glassesButton.addItemListener(this);
       hairButton.addItemListener(this);
       teethButton.addItemListener(this);
       //Indicates what"s on the geek.
       choices = new StringBuffer("cght");
       //Set up the picture label
       pictureLabel = new JLabel();
       pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));
       updatePicture();
       /*Put the check boxes in a column in a panel*/
       
       JPanel checkPanel = new JPanel(new GridLayout(0, 1));
       checkPanel.add(chinButton);
       checkPanel.add(glassesButton);
       checkPanel.add(hairButton);
       checkPanel.add(teethButton);
       add(checkPanel, BorderLayout.LINE_START);
       add(pictureLabel, BorderLayout.CENTER);
       setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
   }
   /** Listens to the check boxes. */
   public void itemStateChanged(ItemEvent e) {
       int index = 0;
       char c = "-";
       Object source = e.getItemSelectable();
       if (source == chinButton) {
           index = 0;
           c = "c";
       } else if (source == glassesButton) {
           index = 1;
           c = "g";
       } else if (source == hairButton) {
           index = 2;
           c = "h";
       } else if (source == teethButton) {
           index = 3;
           c = "t";
       }
       //Now that we know which button was pushed, find out
       //whether it was selected or deselected.
       if (e.getStateChange() == ItemEvent.DESELECTED) {
           c = "-";
       }
       //Apply the change to the string.
       choices.setCharAt(index, c);
       updatePicture();
   }
   protected void updatePicture() {
       //Get the icon corresponding to the image.
       ImageIcon icon = createImageIcon(
                                   "images/geek/geek-"
                                   + choices.toString()
                                   + ".gif");
       pictureLabel.setIcon(icon);
       pictureLabel.setToolTipText(choices.toString());
       if (icon == null) {
           pictureLabel.setText("Missing Image");
       } else {
           pictureLabel.setText(null);
       }
   }
   /** Returns an ImageIcon, or null if the path was invalid. */
   protected static ImageIcon createImageIcon(String path) {
       java.net.URL imgURL = SwingCheckBoxDemo.class.getResource(path);
       if (imgURL != null) {
           return new ImageIcon(imgURL);
       } else {
           System.err.println("Couldn"t find file: " + path);
           return null;
       }
   }
   /**
    * Create the GUI and show it.  For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    */
   private static void createAndShowGUI() {
       //Make sure we have nice window decorations.
       JFrame.setDefaultLookAndFeelDecorated(true);
       //Create and set up the window.
       JFrame frame = new JFrame("SwingCheckBoxDemo");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       //Create and set up the content pane.
       JComponent newContentPane = new SwingCheckBoxDemo();
       newContentPane.setOpaque(true); //content panes must be opaque
       frame.setContentPane(newContentPane);
       //Display the window.
       frame.pack();
       frame.setVisible(true);
   }
   public static void main(String[] args) {
       //Schedule a job for the event-dispatching thread:
       //creating and showing this application"s GUI.
       javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               createAndShowGUI();
           }
       });
   }

}


 </source>
   
  
 
  



Swing CheckBoxes

   <source lang="java">

// : c14:SwingCheckBoxes.java // <applet code=SwingCheckBoxes width=200 height=200></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class SwingCheckBoxes extends JApplet {

 private JTextArea t = new JTextArea(6, 15);
 private JCheckBox cb1 = new JCheckBox("Check Box 1"), cb2 = new JCheckBox(
     "Check Box 2"), cb3 = new JCheckBox("Check Box 3");
 public void init() {
   cb1.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       trace("1", cb1);
     }
   });
   cb2.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       trace("2", cb2);
     }
   });
   cb3.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       trace("3", cb3);
     }
   });
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   cp.add(new JScrollPane(t));
   cp.add(cb1);
   cp.add(cb2);
   cp.add(cb3);
 }
 private void trace(String b, JCheckBox cb) {
   if (cb.isSelected())
     t.append("Box " + b + " Set\n");
   else
     t.append("Box " + b + " Cleared\n");
 }
 public static void main(String[] args) {
   run(new SwingCheckBoxes(), 200, 200);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~


 </source>