【问题标题】:Methods lacking return types and no void?缺少返回类型且没有 void 的方法?
【发布时间】:2013-03-31 08:53:59
【问题描述】:

这段代码在我的教科书中,但我不明白的是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); 
}
}

【问题讨论】:

  • 它是一个构造函数。在书的索引中查找“构造函数”并从那里开始阅读。
  • 那是一个构造函数,构造函数创建一个对象。它们不会以返回对象的方式返回任何东西。
  • 购买一本更好的 Java 书籍。在阅读有关 UI 的书籍之前。这将在第 1 章中介绍。即使在非常糟糕的书中。

标签: java methods return void


【解决方案1】:

它是一个构造函数,而不是一个方法。请在此处查看文档 - http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

【讨论】:

  • 请提供一些参考,以丰富您的答案。
【解决方案2】:

它是构造函数而不是方法。方法将始终具有返回类型或 void(无返回值)。

【讨论】:

    【解决方案3】:

    这不是Method(它是附加到类的函数),而是ConstructorConstructors 用于实例化或“创建”对象/类。

    这些资源应该可以帮助您进一步了解它们:

    构造函数:http://www.leepoint.net/notes-java/oop/constructors/constructor.html

    方法:http://www.tutorialspoint.com/java/java_methods.htm

    【讨论】:

      【解决方案4】:

      它是对象TestPanels 的构造函数。在诸如TestPanels t = new TestPanels() 之类的语句中调用它会创建一个具有9 个JButtons 的对象,以及在TestPanels() 中创建的所有其他组件。

      它基本上是一种启动对象属性的方法,就像JButton b = new JButton("Button") 会给你一个显示“按钮”的按钮。

      【讨论】:

        猜你喜欢
        • 2012-11-24
        • 2020-01-16
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2021-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多