我对 Java 很陌生,正在开发一个简单的小程序作为家庭作业项目...我编译它时没有任何语法错误,但它在 Main 中除了空白屏幕和“”字样之外没有显示任何内容小程序已启动”。我能否就如何修复它提供一些校对/建议?谢谢
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class Module6Project extends JApplet
{
public static void main (String[] args) {
JFrame f=new JFrame("Module6Project");
f.setBackground(Color.blue);
f.getContentPane().setLayout(null);
f.setSize(500,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField first = new JTextField("First name", 150);
JTextField second = new JTextField("Last name", 200);
JTextField third = new JTextField("DoB", 75);
JTextField fourth = new JTextField("Address", 350);
JTextField fifth = new JTextField("Additional comments", 250);
JButton OK = new JButton("OK");
JButton Cancel = new JButton("Cancel");
}}
最佳答案
你看起来很困惑。 Applet 在 Web 浏览器中运行,而不是通过 main()
运行。接下来,您有一个 Applet(您不需要 JFrame)。最后,您需要将组件添加到容器中。我通常使用 JPanel
,但您可以使用 JApplet
或 JFrame
。
class Module6Project extends JApplet {
@Override
public void init() {
// Not a new Frame, "this" applet.
this.setBackground(Color.blue);
this.getContentPane().setLayout(null);
// this.setSize(500, 500);
JTextField first = new JTextField("First name",
150);
JTextField second = new JTextField("Last name",
200);
JTextField third = new JTextField("DoB", 75);
JTextField fourth = new JTextField("Address", 350);
JTextField fifth = new JTextField(
"Additional comments", 250);
JButton OK = new JButton("OK");
JButton Cancel = new JButton("Cancel");
// add everything to the container (or it won't be visible)
this.add(first);
this.add(second);
this.add(third);
this.add(fourth);
this.add(fifth);
this.add(OK);
this.add(Cancel);
}
}
关于java - 运行Applet后没有任何显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24934267/