2015-08-26 61 views
0

我寫了一段代碼來看看滾動窗格如何運行,但我的代碼從未工作過。 這裏的代碼,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如何工作的任何幫助?

回答

3
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標準。