gpt4 book ai didi

java - 打印到文本字段的方法

转载 作者:行者123 更新时间:2023-11-30 07:46:45 24 4
gpt4 key购买 nike

如何将方法打印到 JavaFX 中的文本字段中,方法输出是整数?

我有这个类,它可以制作骰子,我想将数字打印到文本字段中。

import java.util.Random;


public class Dice {

public Die Die1 = new Die(6);
public Die Die2 = new Die(6);


public int throwDice(){
Die1.throwDie();
Die2.throwDie();
return(Die1.diceEyes+Die2.diceEyes);
}

public void isItaPair(){
if(Die1.diceEyes==Die2.diceEyes)
System.out.println("Its a pair, throw again.");
throwDice();
}

class Die {

private final int diceSides;
public int diceEyes;
private Random randomEyes = new Random();

public Die(int diceSides){
this.diceSides = diceSides;

}


public void throwDie(){
diceEyes = randomEyes.nextInt(diceSides)+1;
}
}
}

这是我的 JavaFX Controller 类,我想将 Die1.throwDice() 的结果打印到文本字段 dice_field 中。

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import moole15gop_1.Dice;
import moole15gop_1.Player;

public class FXMLDocumentController implements Initializable {




@FXML
private TextField user1;
@FXML
private TextField user2;
@FXML
private TextArea game_text1;
@FXML
private TextArea game_text2;
@FXML
private Button start_btn1;
@FXML
private Button start_btn2;
@FXML
private Button game_btn;
@FXML
private Label game_label;
@FXML
private TextField dice_field;

@Override
public void initialize(URL url, ResourceBundle rb) {

}

@FXML
private void start_action1(ActionEvent event) {
user1.setText(user1.getText());
System.out.println(user1.getText());
if(user1.getText().isEmpty()){
game_label.setText("You need to enter a username for the first player!");
}
else
{
game_text1.setText("Your username is " + user1.getText() + " and you have " + Player.playerMoney + ". You start at position " + Player.position);
}

}

@FXML
private void start_action2(ActionEvent event) {
user2.setText(user2.getText());
System.out.println(user2.getText());
if(user2.getText().isEmpty()){
game_label.setText("You need to enter a username for the second player!");
}
else
{
game_text2.setText("Your username is " + user2.getText() + " and you have " + Player.playerMoney + ". You start at position " + Player.position);
}
}

Dice die1 = new Dice();

@FXML
private void game_action(ActionEvent event) {

}


}

当 game_action 事件被激活时,应该打印该方法。

感谢您提前提供的帮助。

最佳答案

只需将从方法返回的 int 转换为 string,然后将其打印到文本字段。

使用

dice_field.setText(Integer.toString(new Dice().throwDice()));

或者

dice_field.setText(String.valueOf(new Dice().throwDice()));

关于java - 打印到文本字段的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com