更改JTextPane的大小

时间:2013-02-23 10:48:15

标签: java swing jtextarea jtextpane preferredsize

我是Java新手,我刚刚在StackOverflow中找到了这段代码:ResizeTextArea

我想使用JTextPane代替JTextArea。在JTextPane中,没有setRows()方法来更改行数。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:8)

StyledDocument中各行的高度可能会有所不同,因此JTextPane中限制的概念无用。您可以将滚动窗格视口的首选大小限制为主面板大小的某个有用部分,如here及以下所示。

附录:正如@camickr评论的那样,在getPreferredSize()中覆盖JScrollPane更容易一些。我还更新了代码,将生长限制在当前大小的一小部分: 1 / 3

image

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 * @see https://stackoverflow.com/a/15042241/230513
 * @see https://stackoverflow.com/a/14858272/230513
 */
public class LimitTextPaneSize {

    private static final int SIZE = 200;
    private static final double LIMIT = 1 / 3d;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                display();
            }
        });
    }

    private static void display() {
        final JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
        mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        JPanel topPanel = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(SIZE, SIZE);
            }
        };
        final JTextPane chatArea = new JTextPane();
        final JScrollPane scrollPane = new JScrollPane(chatArea){
            @Override
            public Dimension getPreferredSize() {
                Dimension d = super.getPreferredSize();
                int desired = (int) (mainPanel.getSize().height * LIMIT);
                int limit = Math.min(desired, d.height);
                return new Dimension(SIZE, limit);
            }
        };
        chatArea.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                updateSize();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateSize();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateSize();
            }

            private void updateSize() {
                mainPanel.revalidate();
            }
        });
        mainPanel.add(topPanel, BorderLayout.CENTER);
        mainPanel.add(scrollPane, BorderLayout.SOUTH);

        JFrame f = new JFrame("LimitTextPaneSize");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(mainPanel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}