问题描述
我有一个不可编辑且已禁用的JtextField
,其中将放置请求数据库之后获得的String
,并且我希望该JtextField
包装所有我的字符串.
I have an uneditable and disabled JtextField
in which I will put a String
obtained after requesting a Database, and I want that this JtextField
wraps All my String.
我看到了setColumn()
和setSize()
方法,但是我首先不知道我的String
长度.
I saw the setColumn()
and setSize()
methods but I don't know first my String
length.
非常感谢.
推荐答案
- JTextFields只能显示一行文本,即句点.
- 如果您需要一个用于包装文本的简单文本组件,请使用JTextArea.
- 设置其列和行.
- 将其放入JScrollPane(如果您认为文本超出了指定的行数).
- 在其上致电
setLineWrap(true)
- 在其上致电
setWrapStyleWord(true)
. - JTextFields can only display a single line of text, period.
- If you need a simple text component that wraps text, use a JTextArea.
- Set its columns and rows.
- Put it into a JScrollPane (if you feel the text will go beyond the number of rows specified).
- Call
setLineWrap(true)
on it - Call
setWrapStyleWord(true)
on it.
修改
您询问有关在添加或删除文本时调整JTextField大小的问题.我想您总是可以重写JTextField的getPreferredSize()
方法,并根据文本的任何更改重新验证/重绘其容器,但是这样做确实会带来风险.
Edit
You ask about resizing the JTextField as text is being added or removed. I suppose that you could always override a JTextField's getPreferredSize()
method, and revalidate/repaint its container on any change in text, but doing so does carry risk.
例如:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class VaryingTextFieldSize {
protected static final int GAP = 5;
public static void main(String[] args) {
final JTextField textField = new JTextField(1) {
@Override
public Dimension getPreferredSize() {
Dimension superPref = super.getPreferredSize();
FontMetrics fontMetrics = getFontMetrics(getFont());
String text = getText();
if (text.length() > 0) {
int width = fontMetrics.charsWidth(text.toCharArray(), 0, text.length()) + GAP;
return new Dimension(width, superPref.height);
}
return superPref;
}
};
textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
reSize();
}
@Override
public void insertUpdate(DocumentEvent e) {
reSize();
}
@Override
public void changedUpdate(DocumentEvent e) {
reSize();
}
private void reSize() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Container container = textField.getParent();
container.revalidate();
container.repaint();
}
});
}
});
JPanel enclosingPanel = new JPanel();
enclosingPanel.setPreferredSize(new Dimension(300, 100));
enclosingPanel.add(textField);
JOptionPane.showMessageDialog(null, enclosingPanel);
}
}
这篇关于设置JTextField的宽度来包装给定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!