2015-04-02 48 views
0

我主要的代碼圖形用戶界面不可見的錯誤

import javax.swing.JFrame; 

public class PotLuck { 

private static JFrame frame; 

public static void main(String[] args) { 
    frame = new JFrame("POT LUCK V1.0"); 
    PotLuckPanel panel3 = new PotLuckPanel(); 
    frame.add(panel3); 
    frame.setSize(300,300); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 
} 

我PotLuckPanel類

import java.awt.BorderLayout; 

public class PotLuckPanel extends JPanel { 

private JLabel statusBar; 
private int guessCounter=0; 

public PotLuckPanel(){ 

JPanel panel = new JPanel(new BorderLayout()); 
JPanel panel2 = new JPanel(); 

panel2.setLayout(new GridLayout(5,5)); 
for(int i=0 ; i< 25 ; i++){ 
    JButton buttoni = new JButton(); 
    panel2.add(buttoni); 
} 

statusBar = new JLabel("Number of guess:"+ guessCounter); 
panel.add(statusBar, BorderLayout.NORTH); 
panel.add(panel2, BorderLayout.SOUTH); 
} 
} 

按鈕不可見,無論是面板。只有框架出現。當我編譯時,沒有錯誤。我的錯誤是什麼?我該如何解決它?

回答

0

問題是,你的PotLuckPanel是一個JPanel,但你永遠不會添加任何組件。

您不需要創建「面板」變量。您只需設置班級的佈局,然後直接添加組件即可:

//JPanel panel = new JPanel(new BorderLayout()); 
setLayout(new BorderLayout()): 

... 

//panel.add(statusBar, BorderLayout.NORTH); 
//panel.add(panel2, BorderLayout.SOUTH); 
add(statusBar, BorderLayout.NORTH); 
add(panel2, BorderLayout.SOUTH); 
0

嘗試設置佈局幀作爲

frame.setLayout(new FlowLayout()); 

或者在主方法的任何其他佈局。它將可見。