I introduce 5 nodes, Button, CheckBox, ChoiceBox,ColorPicker, and ComboBox.
At first, I made such a window using ScenBuilder(SB).
チョイスボックスとコンボボックスには初めから3つの要素が入っていて、クリックするとこんな感じです。コンボボックスは、「プロパティ」タブでeditableにチェックを入れるとテキストフィールドのように入力できるようになります。
CheckBox and Combo box have 3 elements in the initial states.If you check "editable" in the "property" tab on SB, you can edit the field in the ComboBox.
それぞれのノードの名前は頭文字を小文字にした文字列にしました。
そしてボタンにはこのようにイベントハンドラを登録します。(頭の#を忘れずに)
I registered the event handler for the action event in this way.(Don't forget the # of the head)
On Actionは、マウスやキーによってボタンが押された時に呼ばれます。
buttonAction will be called when the Button pressed.
ちなみに、Buttonの「プロパティ」タブでDefault Buttonにチェックを入れると、そのボタンにフォーカスがなくても押されるようになります。Cancel Buttonの場合はESCキーです。(テキストエリアなどエンターキーが何か役割をもつノードの上では発動しないそうです)
To press the Button from anywhere(without focus), check "default button" in "property" tab.
If you check "cancel button", that Button will be pressed with ESC key.
*On the node which Enter key has a role in,(for example: TextArea) that can't trigger the action.
コントローラにはこのように書いて実行します。
I wrote like this in the controller and excuted.
public class JavaFXApplication1Controller implements Initializable {
//@FXML //名指ししないので不要
//private Button button;
@FXML
private CheckBox checkBox;
@FXML
private ChoiceBox choiceBox;
@FXML
private ColorPicker colorPicker;
@FXML
private ComboBox comboBox;
@FXML //こっちには「#」をつけない!no need #
public void buttonAction(ActionEvent e) {
//チェックされていればtrue,そうでなければfalse whether checkBox is checked or not
boolean selected = checkBox.isSelected();
System.out.println("checkBox= " + selected);
//選択されている要素が上から何番目か(0から) get the selected index
int selection = choiceBox.getSelectionModel().getSelectedIndex();
//選択されている要素の内容(Objectで返ってくる) get the selected item
String value = choiceBox.getValue() + "";
System.out.println("choiceBox num= " + selection + " item= " + value);
//getItemsで要素のリストが得られ、削除などの操作ができる getItems() gets the lists of the items
choiceBox.getItems().remove(2);
// choiceBox.getItems().remove("アイテム2");
// choiceBox.getItems().clear();
// choiceBox.getItems().add("要素の追加");
// choiceBox.getItems().addAll("コンマ区切りで","何個でも","追加");
//選択されている色を返す get selected color
Color color = colorPicker.getValue();
//こうすると.toString()されてrgbaの8桁の16進数になる toString() converts color into String
System.out.println("colorPicker= " + color);
//選択されている要素が上から何番目か(0から) get index
selection = comboBox.getSelectionModel().getSelectedIndex();
//選択されている要素の内容とは限らない get String from the field in the ComboBox
value = comboBox.getValue() + "";
System.out.println("comboBox num= " + selection + " item= " + value);
}
例えば画面をこのように操作すると、(コンボボックスはアイテム3を選び、表示された文字列の「3」を消しました)
I operated like this for example.(select item3 in the comboBox and deleted "3")
checkBox= true choiceBox num= 0 item= アイテム1 colorPicker= 0xb31a1aff comboBox num= 2 item= アイテム