[英]Methods lacking return types and no void?
這段代碼在我的教科書中,但是我不理解的是方法TestPanels()。 它沒有返回類型,也沒有空。 怎么會這樣
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);
}
}
它是構造函數,而不是方法。 請在此處查看文檔-http: //docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
它是構造函數,而不是方法。 方法將始終具有return-type或void(無返回值)。
那不是Method
(它是附加到類的函數),而是Constructor
。 Constructors
用於實例化或“創建”對象/類。
這些資源應幫助您進一步了解它們:
構造函數: http : //www.leepoint.net/notes-java/oop/constructors/constructor.html
它是對象TestPanels
的構造TestPanels
。 在諸如TestPanels t = new TestPanels()
類的語句中調用它會創建一個具有9個JButton
的對象,以及在TestPanels()
創建的所有其他組件。
基本上,這是一種初始化對象屬性的方法,就像JButton b = new JButton("Button")
會給您一個帶有“ Button”的按鈕一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.