我可以将基于JFrame的程序添加到JApplet吗?当我尝试这样做时,我怎么能这样做:
public class Test extends JApplet{
public void init(){
JFrame frame=new JFrame(300,400);
add(frame);
frame.setVisible(true);
}
我尝试使用appletviewer时遇到错误。任何人都可以帮助我吗?
答案 0 :(得分:3)
您无法向小程序添加框架,但您可以将小程序添加到框架中:
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();
}
}
答案 1 :(得分:1)
要完成,您的交换机需要通过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);
}
}
答案 2 :(得分:1)
使用JInternalFrame代替JFrame。这将解决您的问题。