如何知道 Java 组件将接收的最大宽度以请求正确的高度?
我正在基于 Java 1.4.2 Personal Basis Profile 为 Amazon Kindle KDK 创建自定义 Java 组件。该组件将包含必要时将重排为多行的文本。我想使用 getMinimumSize()
、getPreferredSize()
和 getMaximumSize()
方法请求包含确切文本的大小。我需要根据组件在布局期间接收的宽度来请求所需的确切高度。
例如,如果组件将收到足够的宽度来包含一行上的所有文本,那么它将只请求一行的高度。但是,如果它仅收到足够的宽度以使文本适合三行,那么它将请求允许三行文本的高度。
看来我需要分两遍完成布局,第一遍请求尽可能多的宽度以适合一行上的文本。然后,一旦收到允许的宽度量,如有必要,请求高度量以适合多行文本。找出这个宽度的最佳方法是什么,以便在 getMinimumSize()
、getPreferredSize()
中返回正确的 Dimension
> 和getMaximumSize()
?
编辑:为了澄清,我很乐意使用 JTextArea
,但 PBP 没有任何 swing 和有限的 AWT 组件。 Kindle KDK 本身有一些基本组件,包括 KTextArea 和 KLabelMultiline。问题是两者都存在极大的缺陷,并且在灵活的布局情况下无法正确调整自身大小。它们在固定布局下工作得很好,所有东西都被赋予了固定的使用区域。但是,当将它们放置在具有粘合元素和其他可以具有可变大小的文本组件的布局中时,它们无法正确扩展以显示所有文本,这是我试图使用自定义组件解决的问题。
I am creating a custom Java component for the Amazon Kindle KDK based on the Java 1.4.2 Personal Basis Profile. The component will contain text that will reflow to multiple lines if necessary. I want to request a size using getMinimumSize()
, getPreferredSize()
and getMaximumSize()
methods that will contain the text exactly. I will need to request the exact height needed based on how much width the component will receive during layout.
For example, if the component will receive enough width to contain all the text on one line, then it will only request one line worth of height. But if it will only receive enough width to have the text fit on three lines, then it will request a height which will allow for three lines of text.
It seems I need the layout to be done in two passes, the first to request as much width as it needs to fit the text on one line. Then once it's received the amount of width it is allowed, to request the amount of height to fit the text on multiple lines if necessary. What is the best way to go about finding out what this width will be in order to return the proper Dimension
in getMinimumSize()
, getPreferredSize()
and getMaximumSize()
?
EDIT: To clarify, I'd gladly use a JTextArea
, but the PBP doesn't have any swing and limited AWT components. The Kindle KDK has some basic components itself, including a KTextArea and KLabelMultiline. Problem is both are extremely buggy and don't size themselves properly in flexible layout situations. They work fine with fixed layouts, where everything is given a fixed area to use. But when placing them in a layout that has glue elements and other text components that can have variable sizes, they don't expand properly to display all their text, the problem I'm trying to address with a custom component.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许只是使用 JTextArea 来显示文本。
如果这个解决方案太简单,那么发布一个 SSCCE 来更好地演示您正在尝试执行的操作,以便我们可以看到您遇到的问题正在拥有。
Maybe just use a JTextArea to display the text.
If this solution is too simple, then post a SSCCE that better demonstrates what you are trying to do so we can see the problems you are having.