简体   繁体   English

JScrollPane 不显示

[英]JScrollPane doesn't show up

I made a program and I want to add a JScrollPane to a JTextArea (but it doesn't show up).我制作了一个程序,我想将 JScrollPane 添加到 JTextArea (但它没有显示)。 Here's the code (or at least everything that has to deal with the JTextArea / JScrollPane, the whole code is a lot):这是代码(或者至少所有必须处理 JTextArea / JScrollPane 的代码,整个代码很多):


    static JPanel contentPane; // This one got initialised in the constructor
    static JTextArea tarMessages;

    public void addTextArea{
        tarMessages = new JTextArea();
        tarMessages.setForeground(Color.WHITE);
        tarMessages.setBackground(new Color(0, 0, 0, 0));
        tarMessages.setEditable(false);
        tarMessages.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        tarMessages.setBounds(600, 124, 200, 192);
        tarMessages.setOpaque(false);
        /*DefaultCaret dlcMessages = (DefaultCaret)tarMessages.getCaret();
        dlcMessages.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);*/
        tarMessages.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e) {
                requestFocus();
            }
        });
        JScrollPane scpMessages = new JScrollPane(tarMessages);
        scpMessages.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scpMessages.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scpMessages.setPreferredSize(new Dimension(10, 192));
        scpMessages.setEnabled(true);
        contentPane.add(scpMessages);
        contentPane.add(tarMessages);
    }

Thank you for helping.感谢您的帮助。 Have nice holidays.度过愉快的假期。

    JScrollPane scpMessages = new JScrollPane(tarMessages);
    ...
    contentPane.add(scpMessages);
    contentPane.add(tarMessages);

A Swing component can only have a single parent. Swing 组件只能有一个父组件。

First you add the text area to the scroll pane, which is correct.首先将文本区域添加到滚动窗格,这是正确的。

But then you remove it from the scroll pane when you add it to the content pane.但是,当您将其添加到内容窗格时,您将其从滚动窗格中删除。

Get rid of:摆脱:

    ///contentPane.add(tarMessages);

Also, when you create the text area use code like:此外,当您创建文本区域时,使用如下代码:

tarMessages = new JTextArea(5, 20);

This will specify the rows/columns of the text area so it can size itself appropriately.这将指定文本区域的行/列,以便它可以适当地调整自身大小。

Don't use setBounds(...)不要使用 setBounds(...)

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

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