2013-04-09 76 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”按钮相同的方式。