JavaFX automatically resize Button's font size to fit in

谁说胖子不能爱 提交于 2020-01-06 02:58:51

问题


I am programming a JavFX UI on Java 8 where I create Buttons with sizes calculated at construction time.

The problem is that the button's text (usually just a single letter in my case) sometimes is too big to fit in the button and then the button just stays blank.

How can I set the font size for a JavaFX Button so that the text is not too high to not get displayed?


回答1:


I found a solution. It's probably not very beautiful and I have no idea where the 0.45 come from (found it by trying), but it seems to work for me:

int buttonSize = 70; 
Button button = new Button("A");
button.setMinSize(buttonSize, buttonSize);
button.setPrefSize(buttonSize, buttonSize);
button.setMaxSize(buttonSize, buttonSize);

button.setStyle(String.format("-fx-font-size: %dpx;", (int)(0.45 * buttonSize)));

The last line calculates the font height in px units and sets it as style for this button.



来源:https://stackoverflow.com/questions/34812022/javafx-automatically-resize-buttons-font-size-to-fit-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!