[英]java fx : Text display upon button click
我正在使用JAVA FX和堆棧制作一個基本的計算器。 當我單擊任何按鈕時,我都會在屏幕上顯示該數字,但是我希望在單擊各種按鈕時顯示連續的表達式,例如,如果我單擊“ 5”,“ +”,“ 3”,“-”,然后1 ,因此當我單擊相應的按鈕時,屏幕應該顯示“ 5 + 3-1”,而不是顯示每個數字。
public class Main extends Application {
/*The keyboard key values*/
private static final String[][] key_values = {
{ "7", "8", "9", "/" },
{ "4", "5", "6", "*" },
{ "1", "2", "3", "-" },
{ "0", "c", "=", "+" }
};
private Button btn[][] = new Button[4][4]; //all the keys
TextField calculator_screen; //the calculator screen
String num;
Stack <String>stack = new Stack<>();
MyStack s = new MyStack();
public static void main(String[] args)
{
launch(args);
System.out.print("123456789");
}
@Override public void start(Stage stage) {
/*The outside layout*/
final VBox layout = new VBox(30); //the size vertically
/*The inside layout for keys or buttons*/
TilePane keypad = new TilePane(); //even it is called keypad, it is a layout
keypad.setVgap(7);
keypad.setHgap(7); //set the gap between keys
/*Create Calculator Screen */
calculator_screen = new TextField();
calculator_screen.setStyle("-fx-background-color: #FFFFFF;"); //set the style of the screen
calculator_screen.setAlignment(Pos.CENTER_RIGHT); //make the screen in the center of the calculator
calculator_screen.setEditable(true); //make sure the screen cannot be typed in manually
calculator_screen.setPrefWidth(500); //set the windth of the screen
/*Create Calculator keyboard*/
keypad.setPrefColumns(key_values[0].length); //set the preferred number of columns
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
btn[i][j] = new Button(key_values[i][j]);
final int a = i;
final int b = j;
/*Add button event*/
btn[i][j].setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
calculator_screen.setText(key_values[a][b]);
}
}
);
keypad.getChildren().add(btn[i][j]);
}
}
/*Put the calculator screen and keypad into a VBox layout*/
layout.setAlignment(Pos.CENTER);
//layout.setStyle("-fx-background-color: #797983; -fx-padding: 20; -fx-font-size: 20;");
layout.getChildren().addAll(calculator_screen, keypad);
calculator_screen.prefWidthProperty().bind(keypad.widthProperty());
/*Show the window*/
stage.setTitle("Calculator");
stage.initStyle(StageStyle.UTILITY);
stage.setResizable(false);
Scene scene = new Scene(layout);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
}
![示例圖片] http://imgur.com/DUOU4vH
有一個簡單的解決方案。 而不是使用
Calculator_screen.setText(key_values [a] [b]);
使用,calculator_screen.appendText(key_values [a] [b]);
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.