让Applet Viewer与我的代码一起显示

时间:2015-07-09 23:28:46

标签: java applet

我现在正在学习Java课程,现在是Java Illuminate第3版的第4章。我们正在努力让Applet显示文本和/或设计和颜色。我正在使用一个macbook,我正在通过TextWrangler进行编码,并且我正在尝试在我的终端上运行,但由于某些原因我编译代码后无法显示Applet显示。请看下面看到本书给我们的代码,他们希望我们通过运行代码获得Applet Viewer,但我无法知道如何操作。

/* Drawing Text
   Anderson, Franceschi
*/


import javax.swing.JApplet;
import java.awt.Graphics;

public class DrawingTextApplet extends JApplet
{
  public void paint( Graphics g )
  {
    super.paint( g );
    g.drawString( "Programming is not", 140, 100 );
    g.drawString( "a spectator sport!", 140, 115 ); //for every new line you add 15 to the Y cord.
  }
}

2 个答案:

答案 0 :(得分:1)

直接来自代码info. page。请特别注意多行注释。

  

Applet' Hello World'实施例

     

此示例需要安装Java Development Kit。访问Java SE下载以获取最新的JDK。

/* <!-- Defines the applet element used by the appletviewer. -->
<applet code='HelloWorld' width='200' height='100'></applet> */
import javax.swing.*;

/** An 'Hello World' Swing based applet.

To compile and launch:
prompt> javac HelloWorld.java
prompt> appletviewer HelloWorld.java  */
public class HelloWorld extends JApplet {

    public void init() {
        // Swing operations need to be performed on the EDT.
        // The Runnable/invokeAndWait(..) ensures that happens.
        Runnable r = new Runnable() {
            public void run() {
                // the crux of this simple applet
                getContentPane().add( new JLabel("Hello World!") );
            }
        };
        SwingUtilities.invokeAndWait(r);
    }
}

答案 1 :(得分:0)

我认为使用其他Swing工具而不是applet更容易。如果你这样做,你不必经历寻找applet查看器或可能更改Java安全设置的麻烦;小程序也很过时。

如果您将程序更改为此类...

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Graphics;

public class DrawingTextPanel extends JPanel
{
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawString("Programming is not", 140, 100);
        g.drawString("a spectator sport!", 140, 115);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new DrawingTextPanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(500, 500);
                frame.setVisible(true);
            }
        });
    }
}

...你将获得与使用applet相同的显示。与使用applet在paint方法中进行绘画的方式类似,在这种情况下,您可以使用paintComponent方法进行绘制。

相关问题