如何使用按钮,复选框和单选按钮

原文: https://docs.oracle.com/javase/tutorial/uiswing/components/button.html

要创建一个按钮,您可以实例化来自 AbstractButton 类的许多类之一。下表显示了您可能想要使用的 Swing 定义的AbstractButton子类:

小结 在哪里描述
JButton 常用按钮。 如何使用 Common Button API如何使用 JButton 功能
JCheckBox 一个复选框按钮。 如何使用复选框
JRadioButton 一组单选按钮之一。 如何使用单选按钮
JMenuItem 菜单中的项目。 如何使用菜单
JCheckBoxMenuItem 具有复选框的菜单项。 如何使用菜单如何使用复选框
JRadioButtonMenuItem 带有单选按钮的菜单项。 如何使用菜单如何使用单选按钮
JToggleButton 实现JCheckBoxJRadioButton继承的切换功能。可以实例化或子类化以创建双状态按钮。 用于某些示例

Note: If you want to collect a group of buttons into a row or column, then you should check out tool bars.


首先,本节介绍AbstractButton定义的基本按钮 API - 因此所有 Swing 按钮都有共同点。接下来,它描述了JButton添加到AbstractButton的少量 API。之后,本节将向您展示如何使用专用 API 来实现复选框和单选按钮。

这是一个显示三个按钮的应用程序的图片:

A snapshot of ButtonDemo


Try this:

  1. Click the Launch button to run the Button Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ButtonDemo example

  2. 单击左键。 它禁用中间按钮(和它本身,因为它不再有用)并启用右按钮。

  3. 单击右键。 启用中间按钮和左按钮,并禁用自身。

ButtonDemo示例所示,Swing 按钮可以显示文本和图像。在ButtonDemo中,每个按钮的文本位于相对于其图像的不同位置。每个按钮文本中带下划线的字母显示每个按钮的*助记符 _ - 键盘替代方案。在大多数外观中,用户可以通过按 Alt 键和助记符来单击按钮。例如,Alt-M 将单击 ButtonDemo 中的“中间”按钮。

禁用按钮时,外观会自动生成按钮的禁用外观。但是,您可以提供替换正常图像的图像。例如,您可以提供左右按钮中使用的图像的灰色版本。

如何实现事件处理取决于您使用的按钮类型以及如何使用它。通常,您实现动作监听器,每次用户单击按钮时都会通知该动作监听器。对于复选框,您通常使用项目监听器,当选中或取消选中复选框时会通知该项目。

下面是 ButtonDemo.java 中的代码,它创建上一个示例中的按钮并对按钮点击作出反应。粗体代码是按钮没有图像时将保留的代码。

  1. //In initialization code:
  2. ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
  3. ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
  4. ImageIcon rightButtonIcon = createImageIcon("images/left.gif");
  5. b1 = new JButton("Disable middle button", leftButtonIcon);
  6. b1.setVerticalTextPosition(AbstractButton.CENTER);
  7. b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
  8. b1.setMnemonic(KeyEvent.VK_D);
  9. b1.setActionCommand("disable");
  10. b2 = new JButton("Middle button", middleButtonIcon);
  11. b2.setVerticalTextPosition(AbstractButton.BOTTOM);
  12. b2.setHorizontalTextPosition(AbstractButton.CENTER);
  13. b2.setMnemonic(KeyEvent.VK_M);
  14. b3 = new JButton("Enable middle button", rightButtonIcon);
  15. //Use the default text position of CENTER, TRAILING (RIGHT).
  16. b3.setMnemonic(KeyEvent.VK_E);
  17. b3.setActionCommand("enable");
  18. b3.setEnabled(false);
  19. //Listen for actions on buttons 1 and 3.
  20. b1.addActionListener(this);
  21. b3.addActionListener(this);
  22. b1.setToolTipText("Click this button to disable "
  23. + "the middle button.");
  24. b2.setToolTipText("This middle button does nothing "
  25. + "when you click it.");
  26. b3.setToolTipText("Click this button to enable the "
  27. + "middle button.");
  28. ...
  29. }
  30. public void actionPerformed(ActionEvent e) {
  31. if ("disable".equals(e.getActionCommand())) {
  32. b2.setEnabled(false);
  33. b1.setEnabled(false);
  34. b3.setEnabled(true);
  35. } else {
  36. b2.setEnabled(true);
  37. b1.setEnabled(true);
  38. b3.setEnabled(false);
  39. }
  40. }
  41. protected static ImageIcon createImageIcon(String path) {
  42. java.net.URL imgURL = ButtonDemo.class.getResource(path);
  43. ...//error handling omitted for clarity...
  44. return new ImageIcon(imgURL);
  45. }

普通按钮 - JButton对象 - 具有比AbstractButton类提供的功能更多的功能:您可以将JButton设置为默认按钮。

顶级容器中的最多一个按钮可以是默认按钮。默认按钮通常具有突出显示的外观,只要顶级容器具有键盘焦点并且用户按下 Return 或 Enter 键,就会单击该按钮。这是一个对话框的图片,在 ListDialog 示例中实现,其中 Set 按钮是默认按钮:

In the Java Look & Feel, the default button has a heavy border

您可以通过在顶级容器的根窗格上调用setDefaultButton方法来设置默认按钮。以下是为ListDialog示例设置默认按钮的代码:

  1. //In the constructor for a JDialog subclass:
  2. getRootPane().setDefaultButton(setButton);

默认按钮功能的确切实现取决于外观。例如,在 Windows 外观中,默认按钮更改为具有焦点的任何按钮,以便按 Enter 键单击聚焦按钮。当没有按钮具有焦点时,最初指定为默认按钮的按钮将再次成为默认按钮。

JCheckBox 类为复选框按钮提供支持。您也可以使用 JCheckBoxMenuItem 类在菜单中放置复选框。因为JCheckBoxJCheckBoxMenuItem继承自AbstractButton,所以 Swing 复选框具有所有常用的按钮特征,如本节前面所述。例如,您可以指定要在复选框中使用的图像。

复选框类似于单选按钮,但按照惯例,它们的选择模型不同。可以选择组中的任意数量的复选框 - 无,部分或全部。另一方面,一组单选按钮只能选择一个按钮。

这是一个应用程序的图片,它使用四个复选框来自定​​义卡通:

NOT a tutorial reader!


Try this:

  1. Click the Launch button to run the CheckBox Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ButtonDemo example

  2. 单击 Chin 按钮或按 Alt-c。 Chin 复选框变为未选中,下巴从图片中消失。其他复选框保持选中状态。此应用程序有一个项监听器,侦听所有复选框。每次项监听器收到事件时,应用程序都会加载一个反映复选框当前状态的新图片。


复选框会为每次点击生成一个项目事件和一个操作事件。通常,您只收听项目事件,因为它们可以让您确定是单击选中还是取消选中复选框。下面是 CheckBoxDemo.java 中的代码,它创建上一个示例中的复选框并对点击作出反应。

  1. //In initialization code:
  2. chinButton = new JCheckBox("Chin");
  3. chinButton.setMnemonic(KeyEvent.VK_C);
  4. chinButton.setSelected(true);
  5. glassesButton = new JCheckBox("Glasses");
  6. glassesButton.setMnemonic(KeyEvent.VK_G);
  7. glassesButton.setSelected(true);
  8. hairButton = new JCheckBox("Hair");
  9. hairButton.setMnemonic(KeyEvent.VK_H);
  10. hairButton.setSelected(true);
  11. teethButton = new JCheckBox("Teeth");
  12. teethButton.setMnemonic(KeyEvent.VK_T);
  13. teethButton.setSelected(true);
  14. //Register a listener for the check boxes.
  15. chinButton.addItemListener(this);
  16. glassesButton.addItemListener(this);
  17. hairButton.addItemListener(this);
  18. teethButton.addItemListener(this);
  19. ...
  20. public void itemStateChanged(ItemEvent e) {
  21. ...
  22. Object source = e.getItemSelectable();
  23. if (source == chinButton) {
  24. //...make a note of it...
  25. } else if (source == glassesButton) {
  26. //...make a note of it...
  27. } else if (source == hairButton) {
  28. //...make a note of it...
  29. } else if (source == teethButton) {
  30. //...make a note of it...
  31. }
  32. if (e.getStateChange() == ItemEvent.DESELECTED)
  33. //...make a note of it...
  34. ...
  35. updatePicture();
  36. }

单选按钮是按钮组,按照惯例,一次只能选择一个按钮。 Swing 版本支持带有 JRadioButtonButtonGroup 类的单选按钮。要在菜单中放置单选按钮,请使用 JRadioButtonMenuItem 类。显示一个多选项的其他方式是组合框列表。单选按钮看起来类似于复选框,但按照惯例,复选框对一次可以选择的项目没有限制。

因为JRadioButton继承自AbstractButton,所以 Swing 单选按钮具有所有常用的按钮特征,如本节前面所述。例如,您可以指定单选按钮中显示的图像。

这是一个应用程序的图片,它使用五个单选按钮让您选择显示哪种宠物:

A snapshot of RadioButtonDemo


Try this:

  1. Click the Launch button to run the RadioButton Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ButtonDemo example

  2. 单击 Dog 按钮或按 Alt-d。 Dog 按钮被选中,这使得 Bird 按钮变为未被选中状态。图片从鸟变为狗。此应用程序有一个侦听所有单选按钮的动作监听器。每次动作监听器收到事件时,应用程序都会显示刚刚单击的单选按钮的图片。


每次用户单击单选按钮(即使已经选中),该按钮将触发动作事件。还会发生一个或两个项目事件 - 一个来自刚刚选择的按钮,另一个来自丢失选择的按钮(如果有的话)。通常,您使用动作监听器处理单选按钮单击。

以下是 RadioButtonDemo.java 中的代码,该代码在前一个示例中创建单选按钮并对点击作出反应。

  1. //In initialization code:
  2. //Create the radio buttons.
  3. JRadioButton birdButton = new JRadioButton(birdString);
  4. birdButton.setMnemonic(KeyEvent.VK_B);
  5. birdButton.setActionCommand(birdString);
  6. birdButton.setSelected(true);
  7. JRadioButton catButton = new JRadioButton(catString);
  8. catButton.setMnemonic(KeyEvent.VK_C);
  9. catButton.setActionCommand(catString);
  10. JRadioButton dogButton = new JRadioButton(dogString);
  11. dogButton.setMnemonic(KeyEvent.VK_D);
  12. dogButton.setActionCommand(dogString);
  13. JRadioButton rabbitButton = new JRadioButton(rabbitString);
  14. rabbitButton.setMnemonic(KeyEvent.VK_R);
  15. rabbitButton.setActionCommand(rabbitString);
  16. JRadioButton pigButton = new JRadioButton(pigString);
  17. pigButton.setMnemonic(KeyEvent.VK_P);
  18. pigButton.setActionCommand(pigString);
  19. //Group the radio buttons.
  20. ButtonGroup group = new ButtonGroup();
  21. group.add(birdButton);
  22. group.add(catButton);
  23. group.add(dogButton);
  24. group.add(rabbitButton);
  25. group.add(pigButton);
  26. //Register a listener for the radio buttons.
  27. birdButton.addActionListener(this);
  28. catButton.addActionListener(this);
  29. dogButton.addActionListener(this);
  30. rabbitButton.addActionListener(this);
  31. pigButton.addActionListener(this);
  32. ...
  33. public void actionPerformed(ActionEvent e) {
  34. picture.setIcon(new ImageIcon("images/"
  35. + e.getActionCommand()
  36. + ".gif"));
  37. }

对于每组单选按钮,您需要创建一个ButtonGroup实例并为其添加每个单选按钮。当用户选择组中的另一个按钮时,ButtonGroup负责取消选择先前选择的按钮。

您通常应该初始化一组单选按钮,以便选择一个。但是,API 不会强制执行此规则 - 一组单选按钮无法进行初始选择。一旦用户做出选择,从那时起只选择一个按钮。

下表列出了常用的与按钮相关的 API。您可能调用的其他方法,如setFontsetForeground,列在 JComponent 类的 API 表中。

使用按钮的 API 分为以下几类:

方法或构造器 目的
JButton(动作)

JButton(字符串,图标) JButton(字符串) JButton(图标) JButton() | 创建JButton实例,将其初始化为具有指定的文本/图像/操作。 | | void setAction(动作) 动作 getAction() | 根据Action实例中的值设置或获取按钮的属性。 | | void setText(String) String getText() | 设置或获取按钮显示的文本。您可以使用 HTML 格式,如在 Swing 组件中使用 HTML 中所述。 | | void setIcon(Icon) Icon getIcon() | 未选择或按下按钮时,设置或获取按钮显示的图像。 | | void setDisabledIcon(Icon) Icon getDisabledIcon() | 禁用时,设置或获取按钮显示的图像。如果未指定禁用的图像,则外观会通过操作默认图像来创建一个。 | | void setPressedIcon(Icon) Icon getPressedIcon() | 按下按钮时设置或获取按钮显示的图像。 | | void setSelectedIcon(Icon) Icon getSelectedIcon() void setDisabledSelectedIcon(Icon) Icon getDisabledSelectedIcon() | 选择时,设置或获取按钮显示的图像。如果未指定禁用的选定图像,则外观会通过操作所选图像来创建一个。 | | setRolloverEnabled(boolean) boolean isRolloverEnabled() void setRolloverIcon(Icon) Icon getRolloverIcon() void setRolloverSelectedIcon(Icon) Icon getRolloverSelectedIcon() | 当光标经过时,使用setRolloverIcon(someIcon)使按钮显示指定的图标。 setRolloverSelectedIcon方法允许您在选择按钮时指定翻转图标 - 这对于双状态按钮(如切换按钮)非常有用。设置翻转图标会自动调用setRollover(true),启用翻转。 |

方法或构造器 目的
void setHorizo​​ntalAlignment(int)

void setVerticalAlignment(int) int getHorizo​​ntalAlignment() int getVerticalAlignment() | 设置或获取按钮的位置应放置其内容。 AbstractButton类允许以下任何一个值进行水平对齐:RIGHTLEFTCENTER(默认值),LEADINGTRAILING。对于垂直对齐:TOPCENTER(默认值)和BOTTOM。 | | void setHorizo​​ntalTextPosition(int) void setVerticalTextPosition(int) int getHorizo​​ntalTextPosition() int getVerticalTextPosition() | 设置或获取按钮的文本相对于按钮图像的放置位置。 AbstractButton类允许水平位置的以下任何一个值:LEFTCENTERRIGHTLEADINGTRAILING(默认值)。对于垂直位置:TOPCENTER(默认值)和BOTTOM。 | | void setMargin(Insets) Insets getMargin() | 设置或获取按钮边框与其内容之间的像素数。 | | void setFocusPainted(boolean) boolean isFocusPainted() | 设置或获取具有焦点时按钮是否应该看起来不同。 | | void setBorderPainted(boolean) boolean isBorderPainted() | 设置或获取是否应绘制按钮的边框。 | | void setIconTextGap(int) int getIconTextGap() | 设置或获取此按钮中显示的文本和图标之间的空间量。 |

方法或构造器 目的
void setMnemonic(int)

char getMnemonic() | 设置或获取键盘替代单击按钮。 setMnemonic方法的一种形式接受一个字符参数;但是,Swing 团队建议您使用int参数,指定KeyEvent.VK_ _X_常量。 | | void setDisplayedMnemonicIndex(int) int getDisplayedMnemonicIndex() | 设置或获取关于文本中哪个字符应该被装饰以表示助记符的提示。请注意,并非所有外观都支持此功能。 | | void setActionCommand(String) String getActionCommand() | 设置或获取按钮执行的操作的名称。 | | void addActionListener(ActionListener) ActionListener removeActionListener() | 添加或删除侦听按钮触发的操作事件的对象。 | | void addItemListener(ItemListener) ItemListener removeItemListener() | 添加或删除侦听按钮触发的项事件的对象。 | | void setSelected(boolean) boolean isSelected() | 设置或获取是否选中该按钮。仅对具有开/关状态的按钮有意义,例如复选框。 | | void doClick() void doClick(int) | 以编程方式执行“单击”。可选参数指定按钮应该按下的时间量(以毫秒为单位)。 | | void setMultiClickThreshhold(long) long getMultiClickThreshhold() | 设置或获取按钮的鼠标按下事件之间所需的时间量(以毫秒为单位)以生成相应的操作事件。 |

构造器 目的
JCheckBox(动作)

JCheckBox(字符串) JCheckBox(字符串,布尔) JCheckBox(图标) JCheckBox(图标,布尔) JCheckBox(字符串,图标) JCheckBox(字符串,图标,布尔) JCheckBox() | 创建JCheckBox实例。字符串参数指定复选框应显示的文本(如果有)。同样,Icon参数指定应使用的图像,而不是外观的默认复选框图像。将布尔参数指定为true会初始化要选中的复选框。如果缺少布尔参数或false,则最初取消选中复选框。 | | JCheckBoxMenuItem(动作) JCheckBoxMenuItem(String) JCheckBoxMenuItem(String,boolean) JCheckBoxMenuItem(Icon) JCheckBoxMenuItem(String,Icon) JCheckBoxMenuItem(String,Icon,boolean) JCheckBoxMenuItem() | 创建JCheckBoxMenuItem实例。参数的解释方式与JCheckBox构造器的参数相同,只是除了普通复选框图标外还显示任何指定的图标。 |

构造器 目的
JRadioButton(动作)

JRadioButton(String) JRadioButton(String,boolean) JRadioButton(Icon) JRadioButton(图标,布尔) JRadioButton(字符串,图标) JRadioButton(字符串,图标,布尔) JRadioButton() | 创建JRadioButton实例。字符串参数指定单选按钮应显示的文本(如果有)。同样,Icon参数指定应使用的图像,而不是外观的默认单选按钮图像。指定 boolean 参数为true初始化要选择的单选按钮,但需经ButtonGroup对象的批准。如果缺少布尔参数或false,则最初取消选择单选按钮。 | | JRadioButtonMenuItem(动作) JRadioButtonMenuItem(String) JRadioButtonMenuItem(Icon) JRadioButtonMenuItem(String,Icon) JRadioButtonMenuItem() | 创建JRadioButtonMenuItem实例。参数的解释方式与JRadioButton构造器的参数相同,但除了普通的单选按钮图标外,还会显示任何指定的图标。 |

构造器 目的
JToggleButton(动作)

JToggleButton(字符串) JToggleButton(字符串,布尔值) JToggleButton(图标) JToggleButton(图标,布尔) JToggleButton(字符串,图标) JToggleButton(字符串,图标,布尔值) JToggleButton() | 创建一个JToggleButton实例,类似于JButton,但有两个状态。通常,您使用JRadioButtonJCheckBox而不是直接实例化JToggleButton,但是当您不需要典型的单选按钮或复选框外观时,JToggleButton会很有用。字符串参数指定切换按钮应显示的文本(如果有)。同样,Icon参数指定应使用的图像。将布尔参数指定为true会初始化要选择的切换按钮。如果缺少布尔参数或false,则最初取消选择切换按钮。 |

构造器或方法 目的
ButtonGroup() 创建ButtonGroup实例。
void add(AbstractButton)

void remove(AbstractButton) | 向组中添加按钮,或从组中删除按钮。 | | public ButtonGroup getGroup() (在DefaultButtonModel中) | 获取控制按钮的ButtonGroup(如果有)。例如: ButtonGroup group = ((DefaultButtonModel)button.getModel()).getGroup(); | | public ButtonGroup clearSelection() | 清除 ButtonGroup 中所选按钮的状态。 ButtonGroup 中没有任何按钮被选中。 |

以下示例使用按钮。另请参见使用工具栏的示例,其中列出了将JButton对象添加到JToolBar的程序。

在哪里描述 笔记
ButtonDemo 如何使用 Common Button API 使用助记符和图标。指定相对于按钮图标的按钮文本位置。使用动作命令。
ButtonHtmlDemo 在 Swing 组件中使用 HTML ButtonDemo 的一个版本,在其按钮中使用 HTML 格式。
ListDialog 如何使用 JButton 功能 使用两个按钮实现一个对话框,其中一个按钮是默认按钮。
DialogDemo 如何制作对话 有“显示”按钮,其行为与单选按钮的状态相关联。使用相当大的,虽然是匿名的内部类来实现动作监听器。
ProgressBarDemo 如何监控进度 使用命名的内部类实现按钮的动作监听器。
CheckBoxDemo 如何使用复选框 使用复选框按钮确定应显示的 16 个图像中的哪一个。
ActionDemo 如何使用行动 使用复选框菜单项来设置程序的状态。
RadioButtonDemo 如何使用单选按钮 使用单选按钮确定应显示的五个图像中的哪一个。
DialogDemo 如何制作对话 包含几组单选按钮,用于确定要显示的对话框。
MenuDemo 如何使用菜单 包含单选按钮菜单项和复选框菜单项。
ColorChooserDemo2 如何使用颜色选择器 CrayonPanel中的蜡笔实现为切换按钮。
ScrollDemo 如何使用滚动窗格 cm 按钮是一个切换按钮。

您可以从以下文档中了解有关 JavaFX 按钮组件的更多信息: