基本上,我想在Javafx中通过单击操作将所有按钮的大小调整为一个大小。
@FXML
private void OnClickResize(ActionEvent event) {
VBox vBox = new VBox();
vBox.setPrefWidth(300);
//Button btn1 = new Button("Short");
//Button btn2 = new Button("Super Long Button");
btn_preview.setMaxWidth(vBox.getPrefWidth());
btn_pdf_preview.setMaxWidth(vBox.getPrefWidth());
btn_bilingualfile.setMaxWidth(vBox.getPrefWidth());
btn_close.setMaxWidth(vBox.getPrefWidth());
vBox.getChildren().addAll(btn_preview,btn_pdf_preview,btn_bilingualfile,btn_close);
}
但这是针对vbox的,而vbox对我没有任何用处,所以我想要javafx中的tabpane这样的解决方案。
发布于 2018-06-07 15:29:06
这可能不是很容易和优雅的实现,但您可以尝试一下。您需要某种类型的单例类。如果你需要它是线程安全的,你可以改变实际的单例实现。
public class ButtonSizeManager {
private ButtonSizeManager instance;
private ButtonSizeManager() {}
public static final ButtonSizeManager getInstance() {
if (instance == null) instance = new ButtonSizeManager();
return instance;
}
private static final double LARGE_WIDTH = 100;
private static final double LARGE_HEIGHT = 30;
/* Similar constants for medium and small sizes */
private final ReadOnlyDoubleWrapper width = new ReadOnlyDoubleWrapper();
private final ReadOnlyDoubleWrapper height = new ReadOnlyDoubleWrapper();
public final void largeSize() {
width.set(LARGE_WIDTH);
height.set(LARGE_WIDTH);
}
/* Similar methods for medium and small */
public final ReadOnlyDoubleProperty widthProperty() {
return width.getReadOnlyProperty();
}
public final double getWidth() { this.width.get(); }
public final ReadOnlyDoubleProperty heightProperty() {
return height.getReadOnlyProperty();
}
public final double getHeight() { this.height.get(); }
}
然后你所有的按钮(是的,这将是繁琐的)将不得不绑定到这个。这意味着如果您有从FXML创建的按钮,那么您需要在FXML中为它们提供fx:id
,并在控制器类中获取它们的注入引用。
public class Controller {
@FXML private Button foo;
public void initialize() {
foo.setMinWidth(Region.USE_PREF_SIZE);
foo.setMinHeight(Region.USE_PREF_SIZE);
foo.setMaxWidth(Double.MAX_VALUE);
foo.setMaxHeight(Double.MAX_VALUE);
foo.prefWidthProperty.bind(ButtonSizeManager.getInstance().widthProperty());
foo.prefHeightProperty.bind(ButtonSizeManager.getInstance().heightProperty());
}
}
如果您不想为每个按钮做太多工作,那么您可以将一些代码移到ButtonSizeManager
中。
public final bindButtonSize(Button button) {
Objects.requireNonNull(button);
button.setMinWidth(Region.USE_PREF_SIZE);
button.setMinHeight(Region.USE_PREF_SIZE);
button.setMaxWidth(Double.MAX_VALUE);
button.setMaxHeight(Double.MAX_VALUE);
button.prefWidthProperty.bind(widthProperty());
button.prefHeightProperty.bind(heightProperty());
}
要更改大小,只需调用单例类中的方法(例如ButtonSizeManager.largeSize()
)
https://stackoverflow.com/questions/50733060
复制相似问题