无法运行JLabel程序

时间:2016-04-22 20:15:48

标签: java swing runtime swingutilities

//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无效(不显示任何applet)!!

appletviewer JLabelDemo.java 

2 个答案:

答案 0 :(得分:0)

使用SwingUtilities.invokeAndWait(runnable obj)代替SwingUtilities.invoke(runnable obj)

答案 1 :(得分: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>