简体   繁体   中英

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). Here's the code (or at least everything that has to deal with the JTextArea / JScrollPane, the whole code is a lot):


    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.

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(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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