簡體   English   中英

Java中的JScrollPane

[英]JScrollPane in Java

我寫了一些代碼來查看滾動窗格的功能,但是我的代碼從未起作用。 這是代碼,

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.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標准的結構更好的程序開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM