java中的类和方法
当我想尝试从类而不是方法完成我的工作时,我只是在玩弄java。看看我做了什么java中的类和方法,java,eclipse,javabeans,Java,Eclipse,Javabeans,当我想尝试从类而不是方法完成我的工作时,我只是在玩弄java。看看我做了什么 import javax.swing.*; class foolingAround{ public static void main(String ARG[]) { createMyInterface(); } private static void createMyInterface(){ JFrame f = new JFrame("Frame from
import javax.swing.*;
class foolingAround{
public static void main(String ARG[]) {
createMyInterface();
}
private static void createMyInterface(){
JFrame f = new JFrame("Frame from Swing but not from other class");
f.setSize(100,100);
f.setVisible(true);
new createAnotherInterface();
}
}
class createAnotherInterface{
public static void main(String arg[]){
giveMe();
}
static JFrame giveMe(){
JFrame p = new JFrame("Frame from Swing and from another class");
p.setSize(100,100);
p.setVisible(true);
return p;
}
}
它编译时没有显示任何错误,但CreateAnortheInterface类中的帧没有显示。为什么?什么时候创建不同的类而不是方法?实例化第二个类不会调用其主方法-您必须从第一个类显式调用giveMe方法:
private static void createMyInterface(){
JFrame f = new JFrame("Frame from Swing but not from other class");
f.setSize(100,100);
f.setVisible(true);
new createAnotherInterface().giveMe();
}
主函数称为入口点,它是JVM在启动java应用程序时跳转到的函数。由于在不同的类中可能有多个main,这就是为什么在使用新的createAnotherInterface从命令行启动时必须指定哪个类的原因;您只是在创建一个新对象,而不是启动giveMe或main
有多种方法可以解决您的问题,最简单的方法可能是改变:
创建新的接口
进入
创建另一个接口
另外,请注意createAnotherInterface不是一个接口,一旦愚弄阶段完成,您应该遵循该步骤 createAnotherInterface类不应该有main方法,如果有,则不会调用它。它应该有一个构造函数,或者您应该使用对该类实例的引用来调用giveMe方法
new createAnotherInterface();
将只调用createAnotherInterface的默认构造函数
你必须在你的愚弄班上明确地给我打电话
或者为CreateAnotherInterface编写构造函数
class createAnotherInterface{
public createAnotherInterface(){
giveMe();
}
public class FoolingAround {
private static void createMyInterface(){
JFrame f = new JFrame("Frame from Swing but not from other class");
f.setSize(100,100);
f.setVisible(true);
new createAnotherInterface();
}
}
事实上,我已经复制了你的代码并进行了测试。文件名为createAnotherInterface.java
它工作了,JFrame就出来了。您已经将方法命名为giveMe,考虑重构到构造函数创建另一个接口,或者只是创建一个启动该方法的构造函数。 您只是为CealAdAutoDead类创建了一个新对象,默认情况下它调用它的默认构造函数,在默认构造函数中没有调用GiVEME方法。
new createAnotherInterface();
我不确定我是对还是错,但我要求您在createAnotherInterface类中创建一个构造函数,并在构造函数中调用giveMe方法。我希望这能解决你的问题
或者至少打个电话
new createAnotherInterface().giveMe();
在createMyInterface类中,您所说的未显示是什么意思?当您运行这两个程序中的哪一个时会出现这个问题,因为这两个程序都有主方法?只需调用新的createAnotherInterface;这并不意味着它将调用main方法,除非该类是main方法,否则将其命名为static main方法是没有意义的,它只是增加了更多的混乱。什么是不从方法命名?您的代码中的方法外没有一行代码。giveMe是静态的,因此应该静态调用它:createAnotherInterface.giveMe。