Java中的JScrollPane

我写了一些代码来看看滚动窗格如何起作用但我的代码从未起作用。 这是代码,

public Fenetre(){ this.setTitle("Data Simulator"); this.setSize(300, 300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); String hello = "hello"; int number = 69; JPanel content = new JPanel(); content.setBackground(Color.LIGHT_GRAY); //Box imad = Box.createHorizontalBox(); JTextArea textArea = new JTextArea(10, 10); JLabel imad = new JLabel(); imad.setText(hello + " your favorite number is " + number + "\nRight?"); JScrollPane scrollPane = new JScrollPane(); setPreferredSize(new Dimension(450, 110)); scrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setEnabled(true); scrollPane.setWheelScrollingEnabled(true); scrollPane.setViewportView(textArea); scrollPane.setViewportView(imad); add(scrollPane, BorderLayout.CENTER); //--------------------------------------------- //On ajoute le conteneur scrollPane.add(textArea); scrollPane.add(imad); content.add(textArea); content.add(imad); content.add(scrollPane); this.setContentPane(content); this.setVisible(true); this.setResizable(false); 

}
当我运行它时,我得到一个带有textArea的小窗口,并在文本区域旁边有一个非常小的白色方块,这是我想的滚动窗格,因为当我从代码中删除它时,这个方块消失了。 当我在文本区域中写入并超出窗口的尺寸时,我无法使用鼠标滚轮垂直滚动,而不是水平滚动。 我在互联网上看到很多例子,我无法理解为什么我的代码不起作用? 任何有助于解释scrollpane如何工作的帮助?

 scrollPane.setViewportView(textArea); scrollPane.setViewportView(imad); 

只能将一个组件添加到滚动窗格的视口中,因此标签将替换文本区域。

 content.add(textArea); content.add(imad); 

组件只能有一个父组件。 上面的代码从滚动窗格中删除了标签,因此滚动窗格中现在没有任何内容。

尝试以下方法:

 JScrollPane = new JScrollPane( textArea ); JPanel content = new JPanel( new BorderLayout() ); content.add(scrollPane, BorderLayout.CENTER); content.add(imad, BorderLayout.PAGE_END); setContentPane( content ); 

要获得更好的解决方案,请参阅Swing教程中有关如何使用文本区域的工作示例,然后修改代码。 这样,您将从遵循Swing标准的更好的结构化程序开始。