我想将一个java文件包含到另一个文件中。两者都有其主要功能。其中一个文件类似于以下内容:
public class FileShow
{
public static void main(String args[])
{
JFrame guiFrame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("RTL Parser GUI");
guiFrame.setSize(500,500);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
JPanel comboPanel = new JPanel();
JTextField handle = new JTextField(30);
comboPanel.add(handle);
guiFrame.add(comboPanel);
guiFrame.setVisible(true);
}
}
而我的其他Java文件是:
public class AnotherFile{
public static void main(String[] args) {
new AnotherFile();
}
public AnotherFile()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Assertion-Based GUI");
guiFrame.setSize(500,500);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
JPanel comboPanel = new JPanel();
JTextField handle = new JTextField(30);
comboPanel.add(handle);
guiFrame.add(comboPanel);
guiFrame.setVisible(true);
}
}
是否有办法将这两个文件合并在一起运行,因为它们都有主要功能?我如何将这两个文件合并在同一个java文件中,并同时运行它们?
你不能这么做。每个Java文件应该只有一个main
方法。
但你可以更好地组织你的文件做你想做的:
public class FileShow{
public void doSomething(){
//...
}
}
public class AnotherFile{
public void doSomething(){
//...
}
}
public class mainClass(){
public static void main(String args[])
new FileShow().doFileShow();
new AnotherFile().doAnotherFile();
}
}
我会在Fileshow的主方法中添加'AnotherFile'对象。你只能有一个主方法。
所以在fileshow。java中,在main方法中添加
Anotherfile a = new Anotherfile()
从你写的内容来看,我完全不清楚你想要实现什么。在一个.java文件中包含两个Java类?放到一个.jar文件中?你说的"一起跑"是什么意思?
在一个源文件中组合两个顶级Java类是可能的(根据JLS),而其中只有一个可能是公共的。但我认为,这不是最佳实践,因为您的类的生命周期相当混乱。但是如果你仍然想这样做,你必须将其中一个设置为包私有或嵌套。
把两个放到一个罐子里是微不足道的。只要呼叫jar cf jarname <classes>
。也可以通过在java命令行中显式提及它们来单独调用主方法,如java -cp jarname <package>.FileShow
。
不过,我还是不太明白你的问题。
在Java中,每个Java文件可以包含一个公共类,默认情况下JDK将调用它的main方法。如果你有两个类都有一个main方法,你想把它保存在一个Java文件中,这两个类不能是公共的,一个必须是内部/嵌套类。我在下面给出了一个例子。
public class FileShow
{
public static void main(String args[])
{
AnotherFile.main(args);;
// Your code
}
static class AnotherFile
{ // as it contains a static method
public static void main(String[] args) //or any static class
{
new AnotherFile();
}
public AnotherFile(){
// Your code
}
}
}
逻辑上是可行的。但是我强烈反对这样做。