2012-10-27 170 views
0

我正在將文本從文本文件掃描到JPanel。文本正在顯示,但不會向下滾動。有任何想法嗎?這裏是我的代碼:JScrollPane不滾動

rFrame = new JFrame(); 
rFrame.setBounds(10, 10, 502, 502); 
rFrame.getContentPane().setLayout(null); 


JPanel pan = new JPanel(); 
pan.setBackground(Color.WHITE); 
pan.setBounds(100, 100, 400, 400); 
rFrame.getContentPane().add(pan); 
pan.setEnabled(false); 

JScrollPane scrollBar=new JScrollPane(pan,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
              JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 

rFrame.add(scrollBar); 

JTextArea area = new JTextArea(); 
area.setText(printToFrame()); //Function prints from text file 
pan.add(area); 
rFrame.add(pan); 

rFrame.setVisible(true); 
rFrame.setLayout(new FlowLayout()); 
rFrame.getContentPane().add(pan); 
rFrame.pack(); 

ClientWindow window = new ClientWindow(); 
window.rFrame.setVisible(true); 
+1

鍋是完全無用的在這裏。直接將文本區域添加到滾動窗格。另外,如果我沒有記錯,setEnabled不適用於嵌套組件 - 但我可能在這裏是錯誤的。 – ignis

+1

你是對的,我因此刪除了我的答案。 WM,你需要學習Swing教程,因爲這裏解釋了所有這些。 –

+0

另外,請研究在JDK安裝目錄的「demo」子目錄中找到的SwingSet2的源代碼。另外:不要setLayout(null),除非你有一個很好的理由(在這種情況下你沒有),滾動窗格不是滾動條,也不會將文本區域和框架添加到面板,因爲你已經添加了滾動窗格。 – ignis

回答

2

這不是向下滾動,因爲JPanel的尺寸不小於JScrollPane的視口較大。您必須通過調用*Object name*.setPreferredSize(new Dimension(int w, int h)),來增加JPanel的尺寸,方法是在JTextArea之內顯示文本,該文本是爲此目的而製作的組件。

例:

public static void main(String[] args) { 
    JTextArea ta = new JTextArea(); 
    JScrollPane sp = new JScrollPane(ta); 

    // disables editing 
    ta.setEditable(false); 

    // enable line wrap to wrap text around 
    ta.setLineWrap(true); 

    // words will not be cut off when wrapped around 
    ta.setWrapStyleWord(true); 

    // displays the text you read in 
    ta.append(*text you read in*); 
} 

甲骨文如何使用JTextAreas一個頁面,你也可以看看該API其他方法使用

+2

而不是使用設置的大小,你應該從preferredSize返回適當的值或使用Scrollable接口...恕我直言 – MadProgrammer

+0

哦對。哎呀,不知怎的,忘記了 – Alex