How to tell the maximum width a Java component will receive in order to request the proper height?
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.
Maybe just use a JTextArea to display the text.
import java.awt.*;
import javax.swing.*;
public class TextAreaHeight extends JFrame
{
public TextAreaHeight()
{
JTextArea textArea = new JTextArea();
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setText("one two three four five six seven eight nine ten");
add(textArea, BorderLayout.NORTH);
JPanel center = new JPanel();
center.setBackground(Color.ORANGE);
add(center, BorderLayout.CENTER);
setSize(200, 200);
setLocationRelativeTo( null );
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new TextAreaHeight();
}
}
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.
精彩评论