用户需要输入要打印在固定尺寸标签上的文本。给定字体,标签具有固定的行数和固定的像素宽度。如何使 JTextArea(或 Swing 中的其他内容,如果有其他选项)适应此用例?
- 最大行数
- 每行字符不超过一定像素宽度
- 对于试图超过最大像素宽度的行,在字级上进行文本换行
我有一个 PlainDocument,它根据字符串的像素宽度限制单行文本的长度,以大写 Ws(我的字体中最宽的字符)测量:
public class StandardDocument extends PlainDocument {
/****** VARIABLES **********************************************/
public boolean upperCase = true;
private int textLimit;
private int textWidth;
private int fieldWidth;
private JTextField textField = new JTextField();
/** Get the maximum width of this text field, measured in capital Ws.
* @return textWidth - int
**/
public int getTextWidth() {
return textWidth;
}
/** Get the maximum width of this text field, measured in pixels.
* @return textWidth - int
**/
protected int getFieldWidth() {
return fieldWidth;
}
/** Core method for inserting value provided by user after "cleaning" user's value automatically. **/
public void insertString(int offs, String str, AttributeSet attr) throws BadLocationException {
if (str == null) { return; }
// Set field value when value is within character limit of field.
if (textWidth > 0) {
int attemptedWidth = textField.getFontMetrics(Constants.defaultFontLabels).stringWidth(getText(0, getLength()) + str);
if (attemptedWidth > fieldWidth) {
return;
}
}
// Set value in field.
super.insertString(offs, str, attr);
}
/** Set the maximum text width as a maximum number of capital Ws this field may hold. **/
public void setTextWidth(int wLimit) {
if (wLimit >= 0) {
textWidth = wLimit;
StringBuffer outputBuffer = new StringBuffer(wLimit);
for (int i = 0; i < wLimit; i++){
outputBuffer.append("W");
}
fieldWidth = textField.getFontMetrics(Constants.defaultFontLabels).stringWidth(outputBuffer.toString());
}
}
}
最佳答案
JTextArea 支持换行。您可以使用以下方法打开它:
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
行数计算会有点困难,因为您不知道新添加的文本是否会导致换行,直到文档更新为止。
因此,也许您需要一个交叉编辑,您可以在单击“打印”按钮时调用该编辑。也许您可以使用 Text Utilities 中的 getWrappedLines(...)
方法类(class)。如果换行数大于最大值,则会阻止打印。
或者,也许您会自动将文本插入到文档中。然后你检查行数。如果大于最大值,您将显示一条消息,然后立即调用 remove(...)
方法。
关于java - JTextArea:限制字符串宽度和行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32230988/