在JavaFX-8中(编辑:我意识到我使用的是jdk-9.0.1,可能有所不同?),我想要一个具有Button功能的组件,但其标签可以设置为富文本。到目前为止,我已经尝试过:
还有其他方法可以实现这一目标,还是有一些合理的方法来制作我已经尝试过的方法之一?
总结一下,我需要一些重要的事情:
每个请求,一个MCVE,其中#3不适合我:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class TestWindow extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
VBox mainLayout = new VBox();
Text t = new Text(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis blandit dolor non dui porttitor, sit amet commodo ipsum condimentum. Proin quis tincidunt massa.");
TextFlow a = new TextFlow(t);
a.setTextAlignment(TextAlignment.CENTER);
Button b = new Button();
b.setGraphic(a);
b.setAlignment(Pos.CENTER);
b.setPrefSize(300, 100);
mainLayout.getChildren().addAll(b);
Scene scene = new Scene(mainLayout);
primaryStage.setScene(scene);
primaryStage.show();
}
}
此代码生成以下结果
如果按钮有一些文本,例如它是用单个空格创建的
Button b = new Button(" ");
部分解决方案
我一直无法找到一种解决方案,它既可以使文本居中,也可以在文本过大时将其剪切。目前,我的解决方法是仅将文本居中。
通过将其maxHeight设置为较小的值,可以垂直居中TextFlow。在问题中使用MCVE作为#3,添加a.setMaxHeight(0);
就足够了。这将使文本居中,因为TextFlow将不再展开以占用所有可用空间。