以下两种方法都返回 gui 引用类型。
如果我用 void 替换 JFrame 和 JButton 返回类型并删除 return 语句,它仍然有效。我无法理解这两种方法之间的区别。
public class JavaGui {
JFrame frame;
JFrame createGui(){
GraphicsConfiguration g = null ;
frame = new JFrame(g);
frame.setTitle("gui");
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);
return frame;
}
JButton createButton(){
JButton button=new JButton();
button.setBounds(130,100,100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
frame.add(button);
return button;
}
public static void main(String[] args){
JavaGui javaGui=new JavaGui();
javaGui.createGui();
javaGui.createButton();
}
}
这些方法不需要返回任何东西,因为frame
对象存储在它们的类中。如果它在另一个类中或在 main 方法中,则需要 return 语句。
这两种方法都可以访问您的 JFrame,因此您可以在其中执行所有操作,但下面是一种更好的方法:
public class JavaGui {
JFrame frame;
public JavaGui() {
GraphicsConfiguration g = null;
frame = new JFrame(g);
frame.setTitle("gui");
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(null);
}
public void createButton(){
JButton button = new JButton();
button.setBounds(130,100,100, 40);
button.setText("aaa");
button.setSize(100, 40);
button.setLayout(null);
frame.add(button);
}
public static void main(String[] args) {
JavaGui gui = new JavaGui();
gui.createButton();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句