2013-04-09 77 views
1

這段代碼在我的教科書中,但我不明白的是TestPanels()方法。它沒有返回類型,也沒有void。這怎麼會發生?缺乏返回類型和無效的方法?

public class TestPanels extends JFrame { 

public TestPanels() { 
    JPanel p1 = new JPanel(); 
    p1.setLayout(new GridLayout(4,3)); 

    for (int i = 1; i <= 9; i++) { 
     p1.add(new JButton(""+i)); 
    } 

    p1.add(new JButton(""+0)); 
    p1.add(new JButton("Start")); 
    p1.add(new JButton("Stop")); 

    JPanel p2 = new JPanel(new BorderLayout()); 
    p2.add(new JTextField("Time to be displayed here"), BorderLayout.NORTH); 
    p2.add(p1, BorderLayout.CENTER); 

    add(p2, BorderLayout.EAST); 
    add(new JButton("Food to be placed here"), BorderLayout.WEST); 

} 

public static void main(String[] args) { 
    TestPanels frame = new TestPanels(); 
    frame.setTitle("The Front View of a Microwave Oven"); 
    frame.setSize(400, 250); 
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
} 
} 
+0

這是一個構造函數。在你的書的索引中查找「構造函數」,並從那裏開始閱讀。 – Yuushi 2013-04-09 04:25:09

+0

這就是一個構造函數,構造函數創建一個對象。它們不返回任何返回對象的方式。 – 2013-04-09 04:25:23

+0

購買一本關於Java的更好書籍。在閱讀關於用戶界面的書籍之前。這將在第1章中討論。即使在真正不好的書中。 – user93353 2013-04-09 04:25:39

回答

0

它是一個構造函數而不是方法。方法將始終具有返回類型或無效(無返回值)。

0

這是一個爲對象TestPanels構造。在諸如TestPanels t = new TestPanels()之類的語句中調用它將創建一個包含9 JButton的對象,並在TestPanels()中創建所有其他組件。

它基本上是一種啓動對象屬性的方式,與JButton b = new JButton("Button")會給你一個「Button」按鈕相同的方式。