添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

For appeals, questions and feedback about Oracle Forums, please email [email protected] . Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

JTextArea: size dynamic with text

843806 Jan 19 2009 — edited Jan 20 2009
I''m trying to size a JTextArea according to the text that is occupy it.
The width I have from another JPanel, but the height I can't get right.
I need to get the number of lines that the text will occupy and then set the size accordingly.
As it is, I've hard-coded the number of lines, even so, that doesn't work. e.g. if i set # of lines = 5, it still shows only 2, though the dlg box can be resized by hand to show them all.
Any suggestions?
public class TextPanel extends JPanel {
    private final Insets insets =  new Insets(10,20,10,20); // top, left, bottom, right
    private JTextArea textArea;
    private FontMetrics metrics;
    private double widthButtonPanel;
     * @param message
     * @param dimension dimensions of button panel
    public TextPanel(String message, Dimension dimension) {
	 // get bg color of panel so we can set bg of text area to same color
    	Color color = getBackground(); 
       TextArea = new JTextArea (message);
	textArea.setLineWrap(true);
	textArea.setWrapStyleWord(true);
	textArea.setBackground(color);
       TextArea.setMargin(insets);
	// this will be width of the text area
	// height can't be set until painting it because we need to get the text size
       widthButtonPanel = dimension.getWidth();
	add(textArea);
     * override default insets
    public Insets getInsets() 
    	return insets;
    @Override
     * override in order to set height of text area
     * @param g Graphics 
    public void paintComponent(Graphics g)
    	// automatically called when repaint
    	super.paintComponent(g);
	Font font = this.getFont();
    	Graphics graphics = this.getGraphics();
    	// get metrics from the graphics
    	metrics = graphics.getFontMetrics(font);
	// get the height of a line of text in this font and render context
       // line height must be that of text only, not space above and below
    	final int HEIGHT_SPACE = 7; // empirically derived
	int heightTextAreaLine = metrics.getHeight() + HEIGHT_SPACE;
	// set height
	final int numberOfLines = 5;
        // truncate double, doesn't matter because it is *.0 anyway
	Dimension newDimension = new Dimension((int)widthButtonPanel, heightTextAreaLine * numberOfLines);
        TextArea.setPreferredSize(newDimension);
        //textArea.setMaximumSize(newDimension);
        TextArea.setMinimumSize(newDimension);
}
Edited by: allelopath on Jan 19, 2009 2:33 PM