2017-07-30 47 views
1

若干年後用Java開發的後端我結束了在一個項目建立一個GUI和Java Swing是快把我逼瘋了。在當我我JScrollPane中添加到我的面板沒有任何的Java Swing出現

所以我做一些測試與JScrollPane,因爲我有一個JPanel是太大,無法在屏幕上。在下面的示例中,我將幾個按鈕添加到JPanel中,然後使用JPanel創建JScrollPane,但屏幕上沒有顯示任何按鈕。

import java.awt.Container; 
import java.awt.FlowLayout; 

import javax.swing.JButton; 
import javax.swing.JDialog; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 

public class TestScrollPane extends JDialog { 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     try { 
      TestScrollPane dialog = new TestScrollPane(); 
      dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
      dialog.setVisible(true); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Create the dialog. 
    */ 
    public TestScrollPane() { 
     setBounds(100, 100, 857, 541); 
     getContentPane().setLayout(null); 
     { 
      JPanel panel = new JPanel(); 
      panel.setBounds(131, 167, 141, 221); 
      getContentPane().add(panel); 
      panel.setLayout(null); 
      { 
       JButton btnNewButton = new JButton("New button"); 
       btnNewButton.setBounds(0, 0, 115, 29); 
       panel.add(btnNewButton); 
      } 
      { 
       JButton btnNewButton_1 = new JButton("New button"); 
       btnNewButton_1.setBounds(26, 192, 115, 29); 
       panel.add(btnNewButton_1); 
      } 

      JScrollPane jsp = new JScrollPane(panel); 
      getContentPane().add(jsp); 

     } 
     { 
      JPanel buttonPane = new JPanel(); 
      buttonPane.setBounds(0, 446, 835, 39); 
      buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); 
      getContentPane().add(buttonPane); 
      { 
       JButton okButton = new JButton("OK"); 
       okButton.setActionCommand("OK"); 
       buttonPane.add(okButton); 
       getRootPane().setDefaultButton(okButton); 
      } 
      { 
       JButton cancelButton = new JButton("Cancel"); 
       cancelButton.setActionCommand("Cancel"); 
       buttonPane.add(cancelButton); 
      } 
     }  
    } 

} 

我不明白爲什麼沒有出現。我創建了JPanel,我添加了按鈕,以及添加到窗口中的JScrollPane。我正在使用WindwBuilder Pro,這就是爲什麼代碼看起來很奇怪。

謝謝。

+0

Java的圖形用戶界面有不同的OS」,屏幕大小,屏幕分辨率等方面的工作在不同的地區使用不同的PLAFs。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

1

一個面板的組件,如果不使用一個佈局管理器,即,使用setLayout(null)時必須是由代碼佈局。大多數組件以零維開始,因此不會顯示。

在上面的代碼中存在缺失的滾動窗格的位置和維數:jsp.setBounds(...)像與其它組分進行。

通常它不建議給自己佈置的部件,更好地使用佈局管理(如GridBagLayout中,BorderLayout的,...)了點。

見Oracle的教程:Lesson: Laying Out Components Within a Container

2

我已經改變

getContentPane().setLayout(null); 
panel.setLayout(null); 

getContentPane().setLayout(new FlowLayout()); 
panel.setLayout(new FlowLayout()); 

現在我看到所有的4個按鈕。

相關問題