簡體   English   中英

將JFrame添加到JApplet

[英]Adding JFrame to JApplet

我可以在JApplet中添加基於JFrame的程序嗎? 當我嘗試這樣做時,我該怎么做:

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

嘗試使用appletviewer時出現錯誤。 誰能幫我 ?

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

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

為了完成您的切換,需要用JApplet實例替換JFrame! 而已。 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);
  }
}

使用JInternalFrame而不是JFrame。 這樣可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM