问题
For example, I created a button labeled "1". Whenever this button is pressed, 1 is appended to a textField. However, I can add 1 to a textField simply by typing 1 on my keyboard. When doing so, I'd like by button to get view as if it was pressed instead if a key. I've been thinking thant may be it's possible to manage this issue in this way:
rootNode.setOnKeyTyped(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
textField.appendText(event.getCharacter());
if(event.getCharacter().equals("1")){
// here button should be pressed
}
}
});
Is there some method, that can change appearance of the button? Thanks is advance.
@James_D , You program works correctly, but I connt apply your solution to my program. Maybe it's because I customized my buttons. Have a look at a part of my code:
HashMap<String, Button> buttons = new HashMap<>();
int btnVal = 1;
for(int j = 5 ; j >= 3; j --){
for(int i = 1; i <= 3; i ++){
Button btn = createNumberButton(Integer.toString(btnVal++), inputField, i, j);
rootNode.getChildren().add(btn);
buttons.put(Integer.toString(btnVal), btn);
}
}
rootNode.setOnKeyPressed(event -> {
Button btn = buttons.get(event.getText());
if (btn != null) {
System.out.println(event.getText());
btn.arm();
inputField.appendText(event.getText());
}
});
rootNode.setOnKeyReleased(event -> {
Button btn = buttons.get(event.getText());
if (btn != null) {
btn.disarm();
}
});
回答1:
Use button.arm() (and button.disarm() to "release" it).
SSCCE:
import java.util.HashMap;
import java.util.Map;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class PressButtonOnTyping extends Application {
@Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
TextField textField = new TextField();
textField.setDisable(true);
root.add(textField, 0, 0, 3, 1);
Map<String, Button> buttons = new HashMap<>();
for (int i = 1 ; i <= 9; i++) {
Button button = createButton(i, textField);
buttons.put(Integer.toString(i), button);
root.add(button, (i-1)%3, 1+ (i-1) / 3);
}
Button zeroButton = createButton(0, textField);
root.add(zeroButton, 1, 4);
buttons.put("0", zeroButton);
root.setOnKeyPressed(e -> {
Button button = buttons.get(e.getText());
if (button!=null) {
button.arm();
textField.appendText(e.getText());
}
});
root.setOnKeyReleased(e -> {
Button button = buttons.get(e.getText());
if (button!=null) {
button.disarm();
}
});
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
private Button createButton(int value, TextField target) {
String s = Integer.toString(value);
Button button = new Button(s);
button.setOnAction(e -> target.appendText(s));
return button ;
}
public static void main(String[] args) {
launch(args);
}
}
来源:https://stackoverflow.com/questions/31371887/how-make-a-button-pressed-when-corresponding-key-on-a-keyboard-is-pressed-javaf