【问题标题】:JScrollPane in JavaJava 中的 JScrollPane
【发布时间】:2015-11-19 23:55:50
【问题描述】:

我写了一个小代码来看看滚动窗格是如何工作的,但我的代码从来没有工作过。 这是代码,

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 的小窗口,在文本区域旁边有一个非常小的白色方块,我想这是滚动窗格,因为当我从代码中删除它时,这个方块消失了。当我在文本区域中书写并超出窗口的尺寸时,我无法使用鼠标滚轮垂直滚动,而且根本无法水平滚动。我在互联网上看到了很多例子,我不明白为什么我的代码不起作用?? 任何帮助解释滚动窗格的工作原理?

【问题讨论】:

    标签: java swing user-interface scrollbar jscrollpane


    【解决方案1】:
    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 );
    

    要获得更好的解决方案,请从 How to Use Text Areas 上的 Swing 教程中的工作示例开始,然后修改代码。这样,您将从遵循 Swing 标准的结构更好的程序开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      相关资源
      最近更新 更多