2014-09-30 32 views
0

我想在java中做一個簡單的界面,但我有一個框架添加多個面板的問題。我希望它是一個咖啡館軟件,所以會有多個表。是我的代碼添加多個小面板到一個框架

public class CafeView extends JFrame{ 

private JButton takeMoneyBtn = new JButton("Hesabı Al"); 

public CafeView(){ 
    JPanel table1 = new JPanel(); 
    this.setSize(800,600); 
    this.setLocation(600, 200); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setVisible(true); 

    table1.setBounds(100, 100, 150, 150); 
    table1.setLayout(null); 
    this.add(table1); 
    table1.add(takeMoneyBtn); 

} 
} 

當我運行它,我只看到一個空frame.In這段代碼我只是想添加一個簡單的面板,如果我能做到這一點,我可以添加其他嫌我think.So怎麼能我解決它,並添加小框架和很多面板,我錯過了什麼?謝謝你的幫助(這裏沒有一個主要的方法,因爲我把它稱爲另一個類的接口類)。

+2

也許你的框架是不是空的。嘗試使用setBorder()爲面板添加邊框,以便實際看到JPanel。 – MarsAtomic 2014-09-30 17:40:21

+3

在將所有可視化組件放在一起之前調用setVisible(true)也是錯誤的 – ControlAltDel 2014-09-30 17:43:12

+0

Java GUI必須在不同的OS,屏幕大小,屏幕分辨率等上工作。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 – 2014-10-01 08:21:50

回答

1

你安排你的組件的位置是在使用.setBounds(..,..)這種情況下JPanel,而應該用它來頂層容器(JFrameJWindowJDialog,或JApplet)不JPanel 。 所以刪除:

table1.setBounds(100, 100, 150, 150); 

我們通過LayoutManager提供來安排組件,請參閱LayoutManager

public class CafeView extends JFrame{ 

private JButton takeMoneyBtn = new JButton("Hesabı Al"); 

public CafeView(){ 
    JPanel table1 = new JPanel(); 
    this.setSize(800,600); 
    this.setLocation(600, 200); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setVisible(true); 

    //table1.setBounds(100, 100, 150, 150); 
    //table1.setLayout(null); 
    this.add(table1,BorderLayout.CENTER); 
    table1.add(takeMoneyBtn); 

} 
1

我將使用LayoutManager來放置所有控件並直接訪問內容窗格。 How to use FlowLayout

public class CafeView extends JFrame{ 

private JButton takeMoneyBtn = new JButton("Hesabı Al"); 

public CafeView(){ 
    JPanel table1 = new JPanel(); 
    this.setSize(800,600); 
    this.setLocation(600, 200); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    Container c = this.getContentPanel(); 
    c.setLayout(new FlowLayout()); 

    c.add(table1); 
    c.add(takeMoneyBtn); 
    //c.add() more stuff.. 

    this.setVisible(true); 
    } 
} 
+0

+1。進一步說明。應該在EDT上創建和更新Swing GUI。有關更多詳細信息,請參見[Swing中的併發](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 – 2014-10-01 08:23:24