【问题标题】:Adding JFrame to JApplet将 JFrame 添加到 JApplet
【发布时间】:2014-05-02 15:42:11
【问题描述】:

我可以将基于 JFrame 的程序添加到 JApplet 吗?当我尝试这样做时,我该怎么做:

public class Test extends JApplet{
public void init(){
    JFrame frame=new JFrame(300,400);
    add(frame);
    frame.setVisible(true);
}

当我尝试使用 appletviewer 时出现错误。谁能帮帮我?

【问题讨论】:

  • catch 错误(正确:Exception)并打印其stack trace
  • “我在尝试使用 appletviewer 时遇到错误” 我很惊讶,因为这句话暗示可以编译。为什么要编写小程序?如果是由于规范。老师请转至Why CS teachers should stop teaching Java applets。使用Java Web Start 从链接启动框架会更有意义。

标签: java swing applet jframe japplet


【解决方案1】:

您不能将框架添加到小程序,但可以将小程序添加到框架:

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

public class AppletBasic extends JApplet
{
    /**
     * Create the GUI. For thread safety, this method should
     * be invoked from the event-dispatching thread.
     */
    private void createGUI()
    {
        JLabel appletLabel = new JLabel( "I'm a Swing Applet" );
        appletLabel.setHorizontalAlignment( JLabel.CENTER );
        appletLabel.setFont(new Font("Serif", Font.PLAIN, 36));
        add( appletLabel );
        setSize(400, 200);
    }

    @Override
    public void init()
    {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    createGUI();
                }
            });
        }
        catch (Exception e)
        {
            System.err.println("createGUI didn't successfully complete: " + e);
        }
    }

    public static void main(String[] args)
    {
        JApplet applet = new AppletBasic();
        applet.init();

        JFrame frame = new JFrame("Applet in Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( applet );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );

        applet.start();
    }
}

【讨论】:

    【解决方案2】:

    要完成您的切换,需要将 JFrame 替换为 JApplet 实例!而已。 JFrame 是普通运行时的顶层窗口,JApplet 是嵌入式运行时的顶层。所以你的代码应该是这样的:

    public class Test extends JApplet {
      public void init() {
       JButton b = new JButton("my button");
       this.add(b);
      }
    }
    

    对于像这样的原始代码:

    public class Test {
     public static void main(String []a) {
       JFrame f = new JFrame("my test");
       JButton b = new JButton("my button");
       f.add(b);
       f.setVisible(true);
      }
    }
    

    【讨论】:

      【解决方案3】:

      使用 JInternalFrame 代替 JFrame。这将解决您的问题。

      【讨论】:

        猜你喜欢
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        • 2013-06-28
        • 2013-08-08
        • 1970-01-01
        相关资源
        最近更新 更多