2013-08-12 63 views
0

我想向我的文本區域添加滾動條,並且知道添加滾動條的簡單代碼,但是當我將滾動條的代碼放到整個文本區域時,消失了!將ScrollBar添加到JTextArea

什麼問題?

這裏是我的代碼:

private JFrame frame; 
private JTextArea textarea; 

public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 

       SmsForm window = new SmsForm(); 
       window.frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

public SmsForm() { 
    initialize(); 
} 

private void initialize() { 
    frame = new JFrame("???"); 
    frame.setBounds(100, 100, 450, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 
    JPanel groupBoxEncryption = new JPanel(); 

    final JTextArea textarea=new JTextArea(); 
    textarea.setBounds(50, 100, 300, 100); 
    frame.getContentPane().add(textarea); 
    textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 

    JScrollPane scrollPanePlain = new JScrollPane(textarea); 
    groupBoxEncryption.add(scrollPanePlain); 
    scrollPanePlain.setBounds(100, 30, 250, 100); 
    scrollPanePlain.setVisible(true); 
+0

綜合各方面的意見已經提供了,但不是加'textarea'到幀中,添加'scrollPanePlain',而不是... – MadProgrammer

+0

停止使用'創造絕對Positioning''GUI'而是使用正確的'佈局經理「,這將幫助您以更少的努力獲得美妙的結果。一個相關的[示例](http://stackoverflow.com/a/13098108/1057230),對於一些幫助:-) –

回答

2

有許多的問題

  • 您需要的JPanelgroupBoxEncryption添加到應用程序JFrame
  • 不要textarea添加到框架 - 組件只能有一個父組件
  • 如前所述,您使用的是null沒有大小組件的佈局 - 忘記不是佈局管理器。
  • 由於JPanel默認使用FlowLayout,因此面板groupBoxEncryption需要覆蓋getPreferredSize。更好的是使用佈局管理器如GridLayout即自動調整大小的組件

JPanel groupBoxEncryption = new JPanel(new GridLayout()); 
2
  1. Java的圖形用戶界面可能會使用不同的PLAFs &在多個平臺工作,在不同的屏幕分辨率。因此,它們不利於組件的準確放置。要組織強健的GUI組件,請改爲使用佈局管理器或combinations of them,以及white space的佈局填充&邊框。
  2. 在行數和列數中建議文本區域的首選大小。
  3. 在將滾動窗格添加到GUI之前,將文本區域添加到滾動窗格。