我写了一些代码来查看滚动 Pane 的功能,但我的代码从未工作过。 这是代码,
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);
}
当我运行它时,我会得到一个带有文本区域的小窗口,在文本区域旁边有一个非常小的白色方 block ,我想这是滚动 Pane ,因为当我从代码中删除它时,这个方 block 就会消失。当我在文本区域中书写并超出窗口尺寸时,我无法使用鼠标滚轮垂直滚动,也根本无法水平滚动。我在互联网上看到了很多例子,我不明白为什么我的代码不起作用?
有帮助解释滚动 Pane 如何工作吗?
最佳答案
scrollPane.setViewportView(textArea);
scrollPane.setViewportView(imad);
滚动 Pane 的视口(viewport)中只能添加一个组件,因此标签会替换文本区域。
content.add(textArea);
content.add(imad);
一个组件只能有一个父组件。上面的代码从滚动 Pane 中删除了标签,因此滚动 Pane 中现在没有任何内容。
尝试如下:
JScrollPane = new JScrollPane( textArea );
JPanel content = new JPanel( new BorderLayout() );
content.add(scrollPane, BorderLayout.CENTER);
content.add(imad, BorderLayout.PAGE_END);
setContentPane( content );
要获得更好的解决方案,请从 How to Use Text Areas 上的 Swing 教程中找到的工作示例开始然后修改代码。这样您就可以从一个遵循 Swing 标准的结构更好的程序开始。
关于java - Java 中的 JScrollPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32218224/