java - JTextArea:限制字符串宽度和行数?

标签 java swing jtextfield jtextarea word-wrap

用户需要输入要打印在固定尺寸标签上的文本。给定字体,标签具有固定的行数和固定的像素宽度。如何使 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/

相关文章:

java - Jasper 报告 JAVA Swing

java - 向 JComboBox 和 JTextField 添加标签

java - 在警告对话框后返回 JTextField 进行编辑

java - 让 ActionListener 监听 JTextField 中的变化而不是只输入?

java - 类的全局字段

java - 杀死Java进程时关闭BufferedReader和BufferedWriter

java - 如何在 JSONP 请求中使用 @RequestBody?

java - 是否有任何 Java 库可以将访问者函数应用于前泛型集合的多个元素?

java - 带有图像和文本的 JList : Where text is coming from an ArrayList<String>

java - 在 JPanel 中显示多个 JTextField 和 JLabels 时遇到困难