如何在JTextArea中更改文本的位置

时间:2013-05-28 19:41:13

标签: java swing jtextarea

通常,在JTextArea中,文本从左上角开始。我希望它在左下角。你怎么能这样做?

enter image description here

(如果我的笔迹不可读,请道歉)

1 个答案:

答案 0 :(得分:6)

您可以将JTextArea锚定到容器的BorderLayout.PAGE_END位置,并允许文本向上滚动。

Amazing Base JTextArea Application

public class BaseTextAreaDemo {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JFrame frame = new JFrame("Base JTextArea App");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                JPanel textAreaPanel = getBaseTextArea();
                JScrollPane scrollPane = new JScrollPane(textAreaPanel)  {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(300, 230);
                    }
                };

                frame.add(scrollPane);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }

            private JPanel getBaseTextArea() {
                JTextArea textArea = new JTextArea();
                textArea.setLineWrap(true);
                textArea.setWrapStyleWord(true);
                textArea.append("bla bla bla\n");
                textArea.append("new text here");
                JPanel panel = new JPanel(new BorderLayout());
                panel.setBackground(textArea.getBackground());
                panel.setBorder(textArea.getBorder());
                textArea.setBorder(null);
                panel.add(textArea, BorderLayout.PAGE_END);

                return panel;
            }
        });
    }
}