java调整文本区域大小_java - 获取具有固定宽度的多行文本的高度,以使对话框正确调整大小 - 堆栈内存溢出...

这是对你的代码的改编,做你想做的事。 但是需要一点技巧来计算标签的大小并设置其首选大小。

import static javax.swing.GroupLayout.DEFAULT_SIZE;

import java.awt.Dimension;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

import javax.swing.text.View;

public class TextSizeProblem extends JFrame {

public TextSizeProblem() {

String dummyString = "";

for (int i = 0; i < 100; i++) {

dummyString += " word" + i; // Create a long text

}

JLabel text = new JLabel();

text.setText("" + dummyString + "");

Dimension prefSize = getPreferredSize(text.getText(), true, 400);

JButton packMeButton = new JButton("pack");

packMeButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

pack();

}

});

GroupLayout layout = new GroupLayout(this.getContentPane());

getContentPane().setLayout(layout);

layout.setVerticalGroup(layout.createParallelGroup().addComponent(packMeButton)

.addComponent(text,DEFAULT_SIZE, prefSize.height, prefSize.height));

layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(packMeButton)

.addComponent(text, DEFAULT_SIZE, prefSize.width, prefSize.width) // Lock the width to 400

);

pack();

}

public static void main(String args[]) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

JFrame frame = new TextSizeProblem();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

});

}

private static final JLabel resizer = new JLabel();

/**

* Returns the preferred size to set a component at in order to render an html string. You can

* specify the size of one dimension.

*/

public static java.awt.Dimension getPreferredSize(String html, boolean width, int prefSize) {

resizer.setText(html);

View view = (View) resizer.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey);

view.setSize(width ? prefSize : 0, width ? 0 : prefSize);

float w = view.getPreferredSpan(View.X_AXIS);

float h = view.getPreferredSpan(View.Y_AXIS);

return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值