Toggle Buttons (2)

Source: Internet
Author: User

5.3 JToggleButton class

JToggleButton is the first component that can be switched. First, we will discuss the JToggleButton class because it is the parent class of its non-menu-oriented components, JCheckBox and JRadioButton. JToggleButton is similar to JButton. When selected, the press status is processed. On the contrary, the status is returned to the unselected status. To cancel a selected component, we must reselect it. JToggleButton is not a widely used component, but we will find this component useful on the toolbar, for example, in Microsoft Word or in a file, as shown in Figure 5-2.

The JToggleButton structure is the objects of the two custom AbstractButton parent classes: ToggleButonModel and ToggleButtonUI. The ToggleButtonModel class indicates the custom ButtonModel data model of the component, while the ToggleButtonUI is delegated by the user interface.

Next we have learned different aspects of JToggleButton, and now let's take a look at how to use it.

5.3.1 create a JToggleButton component

There are eight constructors for JToggleButton:

public JToggleButton()JToggleButton aToggleButton = new JToggleButton();   
public JToggleButton(Icon icon)JToggleButton aToggleButton = new JToggleButton(new DiamondIcon(Color.PINK))   
public JToggleButton(Icon icon, boolean selected)JToggleButton aToggleButton = new JToggleButton(new DiamondIcon(Color.PINK), true);   
public JToggleButton(String text)JToggleButton aToggleButton = new JToggleButton("Sicilian");   
public JToggleButton(String text, boolean selected)JToggleButton aToggleButton = new JToggleButton("Thin Crust", true);   
public JToggleButton(String text, Icon icon)
JToggleButton aToggleButton = new JToggleButton("Thick Crust",  new DiamondIcon(Color.PINK));  
 public JToggleButton(String text, Icon icon, boolean selected)JToggleButton aToggleButton = new JToggleButton("Stuffed Crust",  new DiamondIcon(Color.PINK), true);   public JToggleButton(Action action)Action action = ...;JToggleButton aToggleButton = new JToggleButton(action);

Each one allows us to customize one or more labels, icons, or initial selected States. Unless specified, the label is empty and there is no text or icon, and the button is not selected at the beginning.

5.3.2 JToggleButton attributes

After JToggleButton is created, we can modify its attributes. Although JToggleButton has nearly 100 inherited attributes, Table 5-1 only displays the two attributes introduced by JToggleButton. The other attributes are called AbstractButton, JComponent, iner, and Component.

JToggleButton attributes

Attribute name
Data Type

Accessibility

AccessibleContext
AccessibleContext

Read-Only

UIClassID
String

Read-Only

We can modify one or more text, icon, or selected attributes in the constructor, and other AbstractButton attributes described in Chapter 4th. You can use the getter and setter methods to configure three basic attributes: get/setText (), get/setIcon (), is/setSelected (), or setAction (action ). Other attributes also have corresponding getter and setter methods.

More visual configuration options of JToggleButton include various icons in different states of the button. In addition to the standard icon, when the button is selected, We can display a different icon. However, if we are modifying the icon Based on the selected status, JToggleButton may not be the most suitable component. We can modify its subclass, JCheckBox or JRadioButton, which will be discussed later in this chapter.

5.3.3 process selected JToggleButton events

After JToggleButton is configured, you can use three methods to process selected events: ActionListener, ItemListener, or ChangeListener. In addition to providing an Action to the constructor, the notification method is similar to ActionListener.

Use ActionListener to listen to JToggleButton events

If we are only interested in events that occur when you select or deselect JToggleButton, we associate ActionListener with the component. After the user selects the button, the component notifies any registered ActionListener object. Unfortunately, this is not the action we need, because we must proactively determine the button status so that we can make a correct response to the selected or unselected button. To determine the selected status, we must obtain the model of the event source and query the selected status, as shown in the following ActionListener sample source code:

ActionListener actionListener = new ActionListener() {  public void actionPerformed(ActionEvent actionEvent) {    AbstractButton abstractButton = (AbstractButton)actionEvent.getSource();    boolean selected = abstractButton.getModel().isSelected();    System.out.println("Action - selected=" + selected + " n");  }};

Use ItemListener to listen to JToggleButton events

The better listener associated with JToggleButton is ItemListener. The ItemEvent will be passed to the itemStateChanged () method of ItemListener, including the current selected status of the button. This allows us to make a correct response without querying the current button status.

For demonstration, the following ItemListener reports the status of the selected ItemEvent generation component:

ItemListener itemListener = new ItemListener() {  public void itemStateChanged(ItemEvent itemEvent) {    int state = itemEvent.getStateChange();    if (state == ItemEvent.SELECTED) {      System.out.println("Selected");    }  else {      System.out.println("Deselected");    }  }};

Use ChangeListener to listen to JToggleButton events

Associating ChangeListener to JToggleButton provides more flexibility. Any associated listener will be notified of changes to the button data model, responding to changes to the armed, pressed, and selected attributes. The three listeners listen for notifications-ActionListener, ItemListener, and ChangeListener-, which gives us seven different responses.

Figure 5-3 shows the change sequence of the ButtonModel attribute and the time when the model notifies each listener.

To demonstrate the ChangeListener notification, the following code snippet defines a ChangeListener that reports three attribute state changes in the button model:

ChangeListener changeListener = new ChangeListener (){
Public void stateChanged (ChangeEvent changeEvent ){
AbstractButton using actbutton = (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 );
}
};
After we associate ChangeListener with JToggleButton and press and release the selected component over the component, the output result is as follows:

Changed: true/false

Changed: true/false

Changed: true/true

Changed: true/false/true

Changed: false/true

When three listeners are associated with the same button, the registered ItemListener object notification will occur after the selected Attribute changes. In other words, the notification is between row 3rd and row 4th. List 5-2 demonstrates all three listeners that are rebellious to the same JToggleButton. Taking into account the registered ActionListener object, the notification takes place after the release button, but before the armed state changes to false, between the second row and the second row.

Package swingstudy. ch04; import java. awt. BorderLayout;
Import java. awt. EventQueue;
Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import java. awt. event. ItemEvent;
Import java. awt. event. ItemListener; import javax. swing. AbstractButton;
Import javax. swing. ButtonModel;
Im

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.