简体   繁体   English

添加可滚动的JTextArea(Java)

[英]Adding a Scrollable JTextArea (Java)

I am trying to add a scroll bar to a JTextArea. 我正在尝试向JTextArea添加滚动条。 Would someone please tell me what I did wrong with the code below? 有人请告诉我下面的代码我做错了什么?

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scrollV = new JScrollPane (textArea);
JScrollPane scrollH = new JScrollPane (textArea);

scrollV.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollH.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setVisible (true);

Thank you in advance. 先感谢您。

EDIT: I fixed the code with the Adel Boutros' advice below. 编辑:我修改了下面的Adel Boutros建议的代码。

    //FRAME
JFrame frame = new JFrame ("Test");
frame.setSize(500,500);
frame.setResizable(false);
//

//TEXT AREA
JTextArea textArea = new JTextArea("TEST");
textArea.setSize(400,400);    

    textArea.setLineWrap(true);
    textArea.setEditable(false);
    textArea.setVisible(true);

    JScrollPane scroll = new JScrollPane (textArea);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    frame.add(scroll);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

It doesn't work because you didn't attach the ScrollPane to the JFrame. 它不起作用,因为您没有将ScrollPane附加到JFrame。

Also, you don't need 2 JScrollPanes: 此外,您不需要2个JScrollPanes:

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scroll = new JScrollPane (textArea, 
   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

frame.add(scroll);
frame.setVisible (true);

You don't need two JScrollPanes . 您不需要两个JScrollPanes

Example: 例:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);  

// Add the scroll pane into the content pane
JFrame f = new JFrame();
f.getContentPane().add(sp);

A scroll pane is a container which contains another component. 滚动窗格是包含另一个组件的容器。 You can't add your text area to two different scroll panes. 您无法将文本区域添加到两个不同的滚动窗格。 The scroll pane takes care of the horizontal and vertical scroll bars. 滚动窗格负责水平和垂直滚动条。

And if you never add the scroll pane to the frame, it will never be visible. 如果您从未将滚动窗格添加到框架,它将永远不可见。

Read the swing tutorial about scroll panes . 阅读有关滚动窗格swing教程

  1. Open design view 开放式设计视图
  2. Right click to textArea 右键单击textArea
  3. open surround with option 打开环绕选项
  4. select "...JScrollPane". 选择“... JScrollPane”。

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

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