Java Tutorial/Swing/JCheckBox
Содержание
- 1 Adding an Icon to the Label of a JCheckBox Component
- 2 CheckBox List
- 3 Check if a JCheckBox is selected in its item change listener
- 4 Creating JCheckBox Components
- 5 Customizing JCheckBox Check Mark Icon
- 6 Customizing JCheckBox Look and Feel
- 7 Display an icon when the cursor is moved over the checkbox. This is called the rollover icon.
- 8 Event firing sequence: ActionListener, ItemListener and ChangeListener
- 9 Getting and Setting the State of a JCheckbox Component
- 10 JCheckBox.setMnemonic
- 11 Listening to JCheckBox Events with a ChangeListener: listen to armed, pressed, selected, or released state
- 12 Listening to JCheckBox Events with an ActionListener
- 13 Listening to JCheckBox Events with an ItemListener
- 14 Using JCheckBox
Adding an Icon to the Label of a JCheckBox Component
import javax.swing.JCheckBox;
public class Main {
public static void main(String[] argv) throws Exception {
JCheckBox checkbox = new JCheckBox();
String label = "<html><table cellpadding=0><tr><td><img src=file:"
+ "icon.gif" + "/></td><td width=" + 3 + "><td>"
// Retrieve the current label text
+ checkbox.getText() + "</td></tr></table></html>";
// Add the icon
checkbox.setText(label);
}
}
CheckBox List
/*
* Copyright (C) 2005 - 2007 JasperSoft Corporation. All rights reserved.
* http://www.jaspersoft.ru.
*
* Unless you have purchased a commercial license agreement from JasperSoft,
* the following license terms apply:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; and without the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
* or write to:
*
* Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330,
* Boston, MA USA 02111-1307
*
*
*
*
* CheckBoxList.java
*
* Created on October 5, 2006, 9:53 AM
*
*/
/**
*
* @author gtoffoli
*/
import java.awt.Color;
import java.awt.ruponent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class CheckBoxList extends JList {
public CheckBoxList() {
super();
setModel(new DefaultListModel());
setCellRenderer(new CheckboxCellRenderer());
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index != -1) {
Object obj = getModel().getElementAt(index);
if (obj instanceof JCheckBox) {
JCheckBox checkbox = (JCheckBox) obj;
checkbox.setSelected(!checkbox.isSelected());
repaint();
}
}
}
}
);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
@SuppressWarnings("unchecked")
public int[] getCheckedIdexes() {
java.util.List list = new java.util.ArrayList();
DefaultListModel dlm = (DefaultListModel) getModel();
for (int i = 0; i < dlm.size(); ++i) {
Object obj = getModel().getElementAt(i);
if (obj instanceof JCheckBox) {
JCheckBox checkbox = (JCheckBox) obj;
if (checkbox.isSelected()) {
list.add(new Integer(i));
}
}
}
int[] indexes = new int[list.size()];
for (int i = 0; i < list.size(); ++i) {
indexes[i] = ((Integer) list.get(i)).intValue();
}
return indexes;
}
@SuppressWarnings("unchecked")
public java.util.List getCheckedItems() {
java.util.List list = new java.util.ArrayList();
DefaultListModel dlm = (DefaultListModel) getModel();
for (int i = 0; i < dlm.size(); ++i) {
Object obj = getModel().getElementAt(i);
if (obj instanceof JCheckBox) {
JCheckBox checkbox = (JCheckBox) obj;
if (checkbox.isSelected()) {
list.add(checkbox);
}
}
}
return list;
}
}
/*
* Copyright (C) 2005 - 2007 JasperSoft Corporation. All rights reserved.
* http://www.jaspersoft.ru.
*
* Unless you have purchased a commercial license agreement from JasperSoft, the
* following license terms apply:
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; and without the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses/gpl.txt or write to:
*
* Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA USA
* 02111-1307
*
*
*
*
* CheckboxCellRenderer.java
*
* Created on October 5, 2006, 10:03 AM
*
*/
/**
*
* @author gtoffoli
*/
class CheckboxCellRenderer extends DefaultListCellRenderer {
protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
if (value instanceof CheckBoxListEntry) {
CheckBoxListEntry checkbox = (CheckBoxListEntry) value;
checkbox.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
if (checkbox.isRed()) {
checkbox.setForeground(Color.red);
} else {
checkbox.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
}
checkbox.setEnabled(isEnabled());
checkbox.setFont(getFont());
checkbox.setFocusPainted(false);
checkbox.setBorderPainted(true);
checkbox.setBorder(isSelected ? UIManager.getBorder("List.focusCellHighlightBorder")
: noFocusBorder);
return checkbox;
} else {
return super.getListCellRendererComponent(list, value.getClass().getName(), index,
isSelected, cellHasFocus);
}
}
}
/*
* Copyright (C) 2005 - 2007 JasperSoft Corporation. All rights reserved.
* http://www.jaspersoft.ru.
*
* Unless you have purchased a commercial license agreement from JasperSoft, the
* following license terms apply:
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; and without the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses/gpl.txt or write to:
*
* Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA USA
* 02111-1307
*
*
*
*
* CheckBoxListEntry.java
*
* Created on October 5, 2006, 10:19 AM
*
*/
/**
*
* @author gtoffoli
*/
class CheckBoxListEntry extends JCheckBox {
private Object value = null;
private boolean red = false;
public CheckBoxListEntry(Object itemValue, boolean selected) {
super(itemValue == null ? "" : "" + itemValue, selected);
setValue(itemValue);
}
public boolean isSelected() {
return super.isSelected();
}
public void setSelected(boolean selected) {
super.setSelected(selected);
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public boolean isRed() {
return red;
}
public void setRed(boolean red) {
this.red = red;
}
}
Check if a JCheckBox is selected in its item change listener
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class Main extends JFrame {
JCheckBox check = new JCheckBox("Checkbox", false);
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
check.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Checked? " + check.isSelected());
}
});
getContentPane().add(check);
pack();
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
Creating JCheckBox Components
public JCheckBox()
JCheckBox aCheckBox = new JCheckBox();
public JCheckBox(Icon icon)
JCheckBox aCheckBox = new JCheckBox(new DiamondIcon(Color.RED, false));
aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));
public JCheckBox(Icon icon, boolean selected)
JCheckBox aCheckBox = new JCheckBox(new DiamondIcon(Color.RED, false), true);
aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));
public JCheckBox(String text)
JCheckBox aCheckBox = new JCheckBox("Spinach");
public JCheckBox(String text, boolean selected)
JCheckBox aCheckBox = new JCheckBox("Onions", true);
public JCheckBox(String text, Icon icon)
JCheckBox aCheckBox = new JCheckBox("Garlic", new DiamondIcon(Color.RED, false));
aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));
public JCheckBox(String text, Icon icon, boolean selected)
JCheckBox aCheckBox = new JCheckBox("Anchovies", new DiamondIcon(Color.RED, false), true);
aCheckBox.setSelectedIcon(new DiamondIcon(Color.PINK, true));
public JCheckBox(Action action)
Action action = ...;
JCheckBox aCheckBox = new JCheckBox(action);
Customizing JCheckBox Check Mark Icon
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
class CheckBoxIcon implements Icon {
public void paintIcon(Component component, Graphics g, int x, int y) {
AbstractButton abstractButton = (AbstractButton)component;
ButtonModel buttonModel = abstractButton.getModel();
Color color = buttonModel.isSelected() ? Color.BLUE : Color.RED;
g.setColor(color);
g.drawRect(1, 1, 20,20);
}
public int getIconWidth() {
return 20;
}
public int getIconHeight() {
return 20;
}
}
public class IconCheckBoxSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Iconizing CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon checked = new CheckBoxIcon();
Icon unchecked = new CheckBoxIcon();
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);
frame.setLayout(new GridLayout(0,1));
frame.add(aCheckBox1);
frame.add(aCheckBox2);
frame.add(aCheckBox3);
frame.add(aCheckBox4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Customizing JCheckBox Look and Feel
Property StringObject TypeCheckBox.backgroundColorCheckBox.borderBorderCheckBox.darkShadowColorCheckBox.disabledTextColorCheckBox.focusColorCheckBox.focusInputMapObject[ ]CheckBox.fontFontCheckBox.foregroundColorCheckBox.gradientListCheckBox.highlightColorCheckBox.iconIconCheckBox.interiorBackgroundColorCheckBox.lightColorCheckBox.marginInsetsCheckBox.rolloverBooleanCheckbox.selectColorCheckBox.shadowColorCheckBox.textIconGapIntegerCheckBox.textShiftOffsetIntegerCheckBoxUIString
Display an icon when the cursor is moved over the checkbox. This is called the rollover icon.
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);
}
}
Event firing sequence: ActionListener, ItemListener and ChangeListener
import java.awt.BorderLayout;
import java.awt.Color;
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 {
public static void main(String args[]) {
JFrame frame = new JFrame("Selecting CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox checkBox = new JCheckBox("A");
// Define ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
String newLabel = (selected ? "A" : "B");
abstractButton.setText(newLabel);
}
};
// Define ChangeListener
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);
}
};
// Define ItemListener
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);
}
}
};
// Attach Listeners
checkBox.addActionListener(actionListener);
checkBox.addChangeListener(changeListener);
checkBox.addItemListener(itemListener);
checkBox.setMnemonic(KeyEvent.VK_S);
frame.add(checkBox, BorderLayout.NORTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
Getting and Setting the State of a JCheckbox Component
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);
}
}
JCheckBox.setMnemonic
/*
* Copyright (c) 1995 - 2008 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:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions 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 nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
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;
/*
* CheckBoxDemo.java 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 CheckBoxDemo 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 CheckBoxDemo() {
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 = CheckBoxDemo.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() {
// Create and set up the window.
JFrame frame = new JFrame("CheckBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new CheckBoxDemo();
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();
}
});
}
}
Listening to JCheckBox Events with a ChangeListener: listen to armed, pressed, selected, or released state
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 JCheckBoxChangeListener {
public static void main(String args[]) {
JFrame frame = new JFrame("Iconizing CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust");
// Define ChangeListener
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);
}
};
aCheckBox4.addChangeListener(changeListener);
frame.add(aCheckBox4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Changed: false/false/false Changed: true/false/false Changed: true/true/false Changed: true/true/true Changed: true/false/true Changed: false/false/true Changed: false/false/true
Listening to JCheckBox Events with an ActionListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class JCheckBoxActionListener {
public static void main(String args[]) {
JFrame frame = new JFrame("Iconizing CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println(selected);
// abstractButton.setText(newLabel);
}
};
aCheckBox4.addActionListener(actionListener);
frame.add(aCheckBox4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Listening to JCheckBox Events with an ItemListener
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class JCheckBoxItemListener {
public static void main(String args[]) {
JFrame frame = new JFrame("Iconizing CheckBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust");
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);
}
}
};
aCheckBox4.addItemListener(itemListener);
frame.add(aCheckBox4);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Using JCheckBox
import java.awt.FlowLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JCheckBoxTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JCheckBox Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox ac = new JCheckBox("A/C");
ac.setSelected(true);
JCheckBox cdPlayer = new JCheckBox("A");
JCheckBox cruiseControl = new JCheckBox("B");
JCheckBox keylessEntry = new JCheckBox("C");
JCheckBox antiTheft = new JCheckBox("D");
JCheckBox centralLock = new JCheckBox("E");
frame.add(new JLabel("Car Features"));
frame.add(ac);
frame.add(cdPlayer);
frame.add(cruiseControl);
frame.add(keylessEntry);
frame.add(antiTheft);
frame.add(centralLock);
frame.pack();
frame.setVisible(true);
}
}