简体   繁体   English

如何将swing jButton上文本的字体大小设置为适合jButton的最大大小

[英]How do I set the font size of the text on a swing jButton to the maximum size who fits the jButton

I've got a jPanel with a jButton, and the user can define the size of the jPanel when launching the application using parameters, the jButton sizes according to the jPanel. 我有一个带有jButton的jPanel,用户可以在使用参数启动应用程序时定义jPanel的大小,jButton大小根据jPanel。

The problem is when I use a fixed font and the Panel is large, then the font looks very small, and vica versa. 问题是当我使用固定字体而Panel很大时,字体看起来很小,反之亦然。

So the font size should always be the maximum font size who fits in the button. 因此字体大小应始终是适合按钮的最大字体大小。

Not sure, but you might find the size using the Graphics.getFontMetrics() method inside the paintComponent-method? 不确定,但您可以使用paintComponent方法中的Graphics.getFontMetrics()方法找到大小? Maybe you can use the FontMetrics.getStringBounds() methods and test if the button contains that rectangle (RectangularShape.contains()). 也许您可以使用FontMetrics.getStringBounds()方法并测试按钮是否包含该矩形(RectangularShape.contains())。

You could use a binary search algorithm to find the max font. 您可以使用二进制搜索算法来查找最大字体。

Make sure you take the insets into account. 确保考虑插入。

Rather than messing with different font sizes. 而不是搞乱不同的字体大小。 I would suggest playing with the layout and keep the button from growing with the Panel size. 我建议玩布局,并保持按钮不随面板尺寸增长。 Allow the extra space to be taken up by other components in your panel. 允许额外的空间被面板中的其他组件占用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM