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

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

问题描述

如何将滚动条添加到我的文本区域.我已经尝试过使用此代码,但无法正常工作.

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 );
}

这是您得到的:

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

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