在Java中设置一个框架
问题描述:
我是Java新手,我一直在尝试设置一个框架,但是我的代码无法工作,或者是因为代码错误,或者是因为我的软件有问题。我正在使用Eclipse。在Java中设置一个框架
所以这是我的代码:
package Frame;
import javax.swing.JFrame;
public class App {
class FrameApp extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("FirstFrame");
frame.setTitle("MFF");
frame.setSize(300, 700);
frame.setVisible(true);
}
}
}
返回
的方法主要不能被声明为静态的;静态方法只能是 在静态或*类型中声明
答
问题是您正在内部类中声明main方法。这就是抛出的异常意味着什么。 这将为你工作。
package Frame;
import javax.swing.JFrame;
class FrameApp extends JFrame{
public FrameApp(String name){
super(name);
}
}
public class App {
public static void main(String[] args) {
FrameApp frame = new FrameApp("FirstFrame");
frame.setTitle("MFF");
frame.setSize(300, 700);
frame.setVisible(true);
}
}
Enjoy! :)
答
你可以这样做,这不是扩展JFrame。
import javax.swing.JFrame;
public class App{
public App() {
JFrame frame = new JFrame("FirstFrame"); // This sets the title
frame.setTitle("MFF"); // Then you're resetting the title
frame.setSize(300, 700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new App();
}
}
或者你可以扩展它
import javax.swing.JFrame;
public class App extends JFrame{
public App() {
// When you extend JFrame you're essentially creating a JFrame
// This gets into OOP (which you of course need to learn)
// Since you've extended the JFrame you can directly access its methods
// like setTitle, setSize....
setTitle("MFF");
setSize(300, 700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new App();
}
}
我绝对不是很有经验的摇摆,但选择一种方法 比其他时候。我选择不扩展框架。为了回答你的 问题,当创建这个简单的
JFrame
时,没有理由在应用类 中放置另一个类,这就是为什么我改变为上面的 的原因。
[Java:何时使用静态方法]可能重复(http://*.com/questions/2671496/java-when-to-use-static-methods) –
尝试移动'main'函数直接到App类。 –
摆脱这一行:“类FrameApp扩展JFrame {”和底部的一个右括号。在这个例子中你不需要FrameApp类。你的框架对象是JFrame。 –