【问题标题】:Nothing showing up after I run Applet运行 Applet 后没有任何显示
【发布时间】:2014-09-16 00:59:30
【问题描述】:

我对 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");
}}

【问题讨论】:

  • 1) JTextField third = new JTextField("DoB", 75); 75 代表列/字符,不是像素。 2) f.getContentPane().setLayout(null); Swing GUI 可能必须在不同的平台上工作,使用不同的 PLAF,在不同的屏幕尺寸和分辨率上使用不同的字体大小默认设置。因此,它们不利于组件的精确放置。而是使用布局管理器,或 combinations of layout managers 以及 layout padding and borders 用于空白。
  • 3) 为什么要编写小程序?如果是由于您的讲师的规范,请参考Why CS teachers should stop teaching Java applets

标签: java xcode applet japplet bluej


【解决方案1】:

你似乎很困惑。小程序在网络浏览器中运行,而不是 main()。接下来,您有一个 Applet(您不需要 JFrame)。最后,您需要将组件添加到容器中。我通常会使用JPanel,但您可以使用JAppletJFrame

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);
  }
}

【讨论】:

  • this.setSize(500, 500); 小程序大小在 HTML 中设置。小程序本身不应试图改变这一点。
猜你喜欢
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多