[英]How to resize a button depending on the text in JavaFX?
這可能是一個微不足道的問題,但到目前為止我無法找到解決方案。
如果您創建一個帶有較長單詞作為文本的按鈕,例如“Überspringen”(跳過的德語單詞),JavaFx 將自動將文本截斷為“Übersprin”+EllipsisString。
Button skipButton = new Button("\Überspringen");
是否有避免截斷的簡單解決方案? 我只能硬編碼一個新的大小,但在 Swing 中,按鈕大小是自動調整的。
我已經嘗試過setWrapText(true)
但這沒有用,我想是因為沒有空格。
public class ButtonTest extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { Scene scene = new Scene(getBottomPanel(),600,50); primaryStage.setScene(scene); primaryStage.show(); } private AnchorPane getBottomPanel() { HBox infraBox = new HBox(5); infraBox.setAlignment(Pos.CENTER); infraBox.getChildren().add(new Label("Input (manuell):")); infraBox.getChildren().add(new TextField()); Button shortButton = new Button("OK"); Button longButton = new Button("\Überspringen"); ButtonBar buttonBar = new ButtonBar(); buttonBar.getButtons().addAll(shortButton, longButton); AnchorPane bottomPanel = new AnchorPane(infraBox, buttonBar); bottomPanel.setPadding(new Insets(5)); AnchorPane.setLeftAnchor(infraBox, 0.0); AnchorPane.setRightAnchor(buttonBar, 5.0); return bottomPanel; } }
通常按鈕會調整大小,以便按鈕的標簽完全可見:
“例如,Button 對象的計算大小取決於文本的長度和用於標簽的字體的大小,以及任何圖像的大小。通常,計算的大小剛好足夠控件和標簽完全可見。” ( https://docs.oracle.com/javase/8/javafx/layout-tutorial/size_align.htm )。
但是,當您將按鈕存儲在具有最大寬度和高度的容器(例如VBox
或HBox
)中時,例如,按鈕將被擠壓到該容器中,即標簽被截斷:
“默認情況下,按鈕只會增長到他們喜歡的大小。但是,如果最小寬度沒有被覆蓋,按鈕會縮小到標簽顯示為三個點 (...) 的位置。”。
我鏈接的文章描述了您的問題:
“為了防止按鈕變得小於其首選寬度,請將其最小寬度設置為其首選寬度”中的“將節點保持在其首選大小”部分。
如果您沒有手動設置按鈕的首選大小,則計算出的大小將自動用於其首選大小:
“默認情況下,UI 控件根據控件的內容為其首選大小計算默認值”
您的代碼示例不會產生所描述的問題(對我而言):
(Sry 我想評論你的帖子,但我的聲譽太低了)
我不知道為什么,所以我希望你們中有人......
public class ButtonTest extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) throws Exception { Scene scene = new Scene(getBottomPanel(), 600, 50); primaryStage.setScene(scene); primaryStage.show(); } private BorderPane getBottomPanel() { HBox infraBox = new HBox(5); infraBox.setAlignment(Pos.CENTER); infraBox.getChildren().add(new Label("Input (manuell):")); infraBox.getChildren().add(new TextField()); Button shortButton = new Button("OK"); Button longButton = new Button("\Überspringen"); ButtonBar buttonBar = new ButtonBar(); buttonBar.getButtons().addAll(shortButton, longButton); /*using BorderPane instead of AnchorPane*/ BorderPane bottomPanel = new BorderPane(); bottomPanel.setPadding(new Insets(5)); bottomPanel.setLeft(infraBox); bottomPanel.setCenter(buttonBar); return bottomPanel; } }
我希望這能解決你的問題
只需使用計算的大小...
這意味着:
button.setPrefSize(Control.USE_COMPUTED_SIZE);
據我所知,此方法將寬度設置為適合文本的按鈕
抱歉英語不好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.