简体   繁体   English

JTextArea无法与JPanel中的JScrollPane配合使用

[英]JTextArea not working well with JScrollPane inside JPanel

I have been trying to make a JTextArea which I can write in like one would in a Word Document; 我一直在尝试制作一个JTextArea,它可以像在Word文档中那样编写。 it wraps around when the texts gets too wide, and scrolls down when it gets too high). 当文字过宽时,它会回绕;当文字过高时,它会向下滚动)。
So far, the wrap when it gets too wide works just fine. 到目前为止,当包包太宽时效果很好。 However, the scroll bar does not work. 但是,滚动条不起作用。 It does show up, but it does not ever get any longer which means that anything outside of the original dimensions of the JTextArea cannot be viewed no matter what. 它的确显示了,但是再也无法显示了,这意味着无论如何都无法查看JTextArea原始尺寸之外的任何内容。
Does anyone know what I am doing wrong? 有人知道我在做什么错吗? Here's how the code looks like; 代码是这样的: it is the JPanel named panel which I am using later on by adding it to another JPanel which in turn is added to a JFrame. 这是我稍后使用的通过命名为JPanel的面板 ,方法是将其添加到另一个JPanel中,该面板又添加到JFrame中。

JTextArea text = new JTextArea(rows, columns);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));
JScrollPane scroll = new JScrollPane(text);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(scroll);

Worked fine, when I deleted - text.setPreferredSize 删除时工作正常text.setPreferredSize

import java.awt.Dimension;
import java.awt.HeadlessException;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class ScrollTest extends JFrame {

    public ScrollTest() throws HeadlessException {
        JTextArea text = new JTextArea(5, 20);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
//      text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));

        JScrollPane scroll = new JScrollPane(text);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.add(scroll);

        this.add(panel);

        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ScrollTest();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM