gpt4 book ai didi

java - 在 Java fxml 应用程序中为动态创建的 Text 对象应用鼠标单击监听器

转载 作者:行者123 更新时间:2023-11-30 02:40:47 24 4
gpt4 key购买 nike

我刚刚开始学习java fxml应用程序开发。我的目标是显示带有随机文本的 fxml 屏幕。因此,我实现了一个 CustomLabel 类并动态生成对象,文本按我的预期显示在场景中。现在我想在每个标签上应用鼠标单击监听器。我尝试过使用 awt onClick 监听器,但没有效果。我正在寻找更好的实现方式。如果有人有任何想法或者我的实现方式在这种情况下是错误的,请纠正我。在这里我想展示我的 customLabel 类

 public class CustomLabel extends Text{

public interface ChoseListener{
void onChosed(String text);
}
private boolean onClicked = true;
ChoseListener choseListener;
private Random random = new Random();
private int y = 0;

public CustomLabel(ChoseListener choseListener,String text,int y){
super(text);

this.y = y;
initLabel();
startAnimation();
}

private void initLabel(){
//here I would like to add mouseclick listener to this object
//and I planed to call choseListener.onChosed(this.getText()) inside click listener so my scene can simply retrieve the text.
this.setFont(new Font("Arial", 25));
}

void startAnimation(){
this.setY(y);
final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
final KeyValue kv = new KeyValue(this.xProperty(), 700);
final KeyFrame kf = new KeyFrame(Duration.millis(9000), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
}
}

我有一个工厂类,它将为请求的场景创建 CustomLabel 对象列表。如果自定义文本对象无法存档此内容,请告诉我。我对java基础知识知之甚少。据我所知,有一种方法可以向该对象添加点击监听器。如果你遇到我的问题帮助我。

最佳答案

private void initLabel(){
this.setFont(new Font("Arial", 25));
this.setOnMouseClicked(e -> choseListener.onChosed(getText()) );
}

关于java - 在 Java fxml 应用程序中为动态创建的 Text 对象应用鼠标单击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775784/

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