添加可滚动的JTextArea(Java)

我正在尝试向JTextArea添加滚动条。 有人请告诉我下面的代码我做错了什么?

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

先谢谢你。

编辑:我修改了下面的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); 

它不起作用,因为您没有将ScrollPane附加到JFrame。

此外,您不需要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); 

滚动窗格是包含另一个组件的容器。 您无法将文本区域添加到两个不同的滚动窗格。 滚动窗格负责水平和垂直滚动条。

如果您从未将滚动窗格添加到框架,它将永远不可见。

阅读有关滚动窗格的swing教程 。

您不需要两个JScrollPanes

例:

 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); 
  1. 开放式设计视图
  2. 右键单击textArea
  3. 打开环绕选项
  4. 选择“… JScrollPane”。