0
//create and display a label containing icon and a string
//JLabel and ImageIcon

import java.awt.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.JLabel.*;  

public class JLabelDemo extends JApplet {

    public void init() {
        try {
            SwingUtilities.invoke(
                new Runnable() {
                    public void run() {
                        makeGUI();
                    }
                }
            );
        }
        catch(Exception e) {
            System.out.println("Cannot happen due to exception " + e);
        }
    }

    private void makeGUI() {
        //create an icon
        ImageIcon ii=new ImageIcon("The Big Trip.png");
        //create a label
        JLabel jl=new JLabel("India",ii,JLabel.CENTER);
        add(jl);//add label to content pane
    }

}
/*<applet code="JLabelDemo" height=250 width=150>*/

此代码使用以下代码编译:

javac JLabelDemo.java 

但是使用以下命令通过 cmd 运行是行不通的(不显示任何小程序)!!

appletviewer JLabelDemo.java 
4

2 回答 2

0

Use SwingUtilities.invokeAndWait(runnable obj) instead of SwingUtilities.invoke(runnable obj)

于 2016-04-22T20:39:39.130 回答
0

您需要改为调用 SwingUtilities.invokeAndWait。而且你还需要关闭你的applet标签,让它在appletviewer中工作。而且您需要将内容添加到内容窗格,而不是使用添加,因为这只会添加到容器中。

JLabelDemo.java

//create and display a label containing icon and a string
//JLabel and ImageIcon

import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class JLabelDemo extends JApplet {
    public void init() {
        try {
            SwingUtilities.invokeAndWait(
                new Runnable() {
                    public void run() {
                         this.makeGUI();
                    }
                }
            );
        } catch (Exception e) {
            System.out.println("Cannot happen due to exception "+e);
        }
    }

    private void makeGUI(){
        //create an icon
        ImageIcon ii = new ImageIcon("The Big Trip.png");

        //create a label
        JLabel jl = new JLabel("India", ii, JLabel.CENTER);
        //add label to content pane
        this.getContentPane().add(jl);
    }
}

HTML:

<applet code="JLabelDemo" width="150" height="250"></applet>
于 2016-04-22T20:54:35.080 回答