官术网_书友最值得收藏!

Button and Event Handlers

The first and most common control is button's family. Button has an EventHandler that is called when Button is clicked (or fired). All code in the event handler is always run on JavaFX Application Thread:

// chapter2/other/ButtonDemo.java
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});

In addition to text, you can use any Node inside a button:

Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setGraphic(new Circle(10));

Button can be assigned the roles of default button or cancel button, responding to Enter or Esc correspondingly:

btn.setDefaultButton(true);
//or
btn.setCancelButton(true);

Button can be easily assigned with a mnemonic (Alt + letter) by using the _ sign:

btn.setText("_Press Alt+P to fire me."):

Note you can disable this behavior by calling btn.setMnemonicParsing(false);.

There are also 4 more classes that share a common ancestor (ButtonBase) and most functionality with Button:

  • ToggleButton saves state clicked/unclicked and changes visuals accordingly. Its state can be retrieved by calling the isSelected() method.
  • CheckBox has the same behavior as ToggleButton but different visuals and API. CheckBox state is controlled by the getState() method.
  • Hyperlink is a button with no extra decorations, which also remembers if it was already clicked.
  • MenuButton is a part of the Menu API that allows you to create user and context menus.
主站蜘蛛池模板: 盖州市| 衡南县| 祥云县| 册亨县| 利辛县| 海宁市| 赤水市| 调兵山市| 道真| 民县| 上高县| 图片| 苏州市| 雅安市| 凉城县| 济宁市| 紫云| 镇平县| 金坛市| 醴陵市| 庐江县| 和顺县| 榆树市| 汤阴县| 马龙县| 子洲县| 胶州市| 浪卡子县| 山东省| 东城区| 尚义县| 金阳县| 峨眉山市| 浦北县| 鹰潭市| 静海县| 石嘴山市| 阿拉善右旗| 丽水市| 乐亭县| 那坡县|