Java:将滚动添加到文本区域 [英] Java :Add scroll into text area

查看:144
本文介绍了Java:将滚动添加到文本区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将滚动条添加到文本区域。我已尝试使用此代码,但它无效。

How can i add the scroll bar to my text area. i have tried with this code but it's not working.

            middlePanel=new JPanel();
        middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

        // create the middle panel components

        display = new JTextArea(16, 58);
        display.setEditable(false); // set textArea non-editable
        scroll = new JScrollPane(display);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        //Add Textarea in to middle panel
        middlePanel.add(scroll);
        middlePanel.add(display);

谢谢

推荐答案

在这里将JTextArea添加到JScrollPane之后:

After adding JTextArea into JScrollPane here:

scroll = new JScrollPane(display);

您不需要像以下那样将其重新添加到其他容器中:

You don't need to add it again into other container like you do:

middlePanel.add(display);

只需删除最后一行代码,它就能正常工作。像这样:

Just remove that last line of code and it will work fine. Like this:

    middlePanel=new JPanel();
    middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

    // create the middle panel components

    display = new JTextArea(16, 58);
    display.setEditable(false); // set textArea non-editable
    scroll = new JScrollPane(display);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    //Add Textarea in to middle panel
    middlePanel.add(scroll);

JScrollPane只是另一个容器,可以在需要时在组件周围放置滚动条,也有自己的布局。当你想把任何东西包装成滚动时你需要做的就是把它传递给JScrollPane构造函数:

JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:

new JScrollPane( myComponent ) 

或设置如下视图:

JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );

其他:

以下是完整的工作示例,因为您仍然无法正常工作:

Here is fully working example since you still did not get it working:

public static void main ( String[] args )
{
    JPanel middlePanel = new JPanel ();
    middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

    // create the middle panel components

    JTextArea display = new JTextArea ( 16, 58 );
    display.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane ( display );
    scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

    //Add Textarea in to middle panel
    middlePanel.add ( scroll );

    // My code
    JFrame frame = new JFrame ();
    frame.add ( middlePanel );
    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

这是你得到的:

And here is what you get:

这篇关于Java:将滚动添加到文本区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆