【发布时间】:2020-02-28 02:48:44
【问题描述】:
我正在尝试在 JavaFX 中设计一组相关的类。
我有一个 Board 类的对象,它创建了 Box 类的一些对象。 在 Box 类中,我创建了一些 Button 类的对象。
当我点击一个Button时,我想要执行Box的方法触发器。
在Box的触发方法里面,我想要Board的方法计算的执行。
如果计算方法返回为真,则按钮改变颜色,否则包含按钮的Box改变颜色。
我必须实现的第一个想法是使用某种从 Board 传递到 Box 以及从 Box 传递到 Button 的回调。
然后我有另一个需求:对另一个函数重复这个机制(如果按钮是用右键按下的,如果Board的calculation_shape方法返回true,则按钮变成圆形,否则Box变成圆形)。 所以我添加了另一组回调。
无论如何,这在我看来是一种代码味道,因为要添加第二个功能,我修改了所有接口和所有类。
在 GUI 领域还有其他方法吗?
谢谢
这里是 MRE。这种行为很愚蠢,但我的问题是:
1) 这是在 GUI 元素之间进行通信的正确方式吗?
2)如果我需要在孩子和父母之间增加更多的交流接口怎么办?我会有很长的构造函数,有很多接口......在我看来就像代码味道......
public interface Triggerable {
boolean trigger(int size);
}
public class MyButton extends Button {
Triggerable method;
int buttonSize;
String buttonName;
public MyButton(String name, int size, Triggerable t) {
super(name);
buttonName = name;
this.setMinSize(100, 30);
this.setOnMouseClicked(e -> MouseClickedAction(e));
buttonSize = size;
method = t;
}
void MouseClickedAction(MouseEvent e) {
if(method.trigger(buttonSize) == true ) {
System.out.println(buttonName + " triggered.");
}
}
}
public interface Calculable {
boolean calculate(int totalSize);
}
public class Box extends VBox {
String boxName;
int numberOfButtons = 3;
int boxSize;
Calculable method;
public Box (String name, int size, Calculable m) {
boxName = name;
for ( int i = 0; i < numberOfButtons; i++ ) {
this.getChildren().add(new MyButton("Button" + i + boxName , i, block -> trigger(block)));
}
boxSize = size;
method = m;
}
public boolean trigger(int buttonSize) {
if(method.calculate(boxSize+buttonSize) == true) {
System.out.println( boxName + " triggered.");
return false;
} else {
return true;
}
}
}
public class Board extends HBox {
String boardName;
int numberOfBoxes = 3;
int boardThreshold = 2;
public Board (String name) {
boardName = name;
for ( int i = 0; i < numberOfBoxes; i++ ) {
this.getChildren().add(new Box("Box" + i , i, block -> calculate(block) ));
}
}
public boolean calculate(int totalSize) {
if(totalSize > boardThreshold) {
return true;
} else {
return false;
}
}
}
【问题讨论】:
-
修改了帖子以添加最小的可重现示例。
标签: user-interface javafx