您好我正在尝试从我的Java应用程序创建一个applet。
我的应用程序从一个扩展JPanel的Testpan.java类开始。 我创建了一个AppletLauncher.java类来在applet中使用它。我用Eclipse将这个AppletLauncher编译成applet,或者是一个应用程序。在这两种情况下我的程序都有效但是,当我尝试使用html文件在我的Web浏览器中加载它时,包含的Testpan JPanel根本不会显示。我首先怀疑它与我的applet类中使用的paint()方法有关,但它适用于Eclipse。我不明白为什么它在我的网络浏览器(Firefox)中不起作用。我想我正确地使用了JApplet的方法,不是吗?
这是我的AppletLauncher.java代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AppletLauncher extends JApplet {
public static Dimension dimWindow = new Dimension(500,300) ;
protected Testpan tp;
public AppletLauncher() {
}
// Common initialization for either JApplet or JFrame
private void initContainer(Container container) {
System.out.println("initCOntainer");
//container.setLocation(10, 10);
container.setPreferredSize(dimWindow);
tp = new Testpan();
tp.setVisible(true);
container.add(tp);
//container.add(new Testpan(), BorderLayout.SOUTH);
//setBackground(Color.red);
}
@Override
public void init() {
System.out.println("Initializing...");
EventQueue.invokeLater(new Runnable() {
public void run() {
initContainer(AppletLauncher.this);
}
});
}
@Override
public void destroy() {
System.out.println("Destroying applet...");
}
public void paint(Graphics g) {
System.out.println("paint AppletLauncher");
g.drawString("Hello wor\nld!", 100, 50);
setBackground(Color.red);
tp.paint(g);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println("inside main method");
JFrame frame = new JFrame("myApplet!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(dimWindow) ;
frame.setResizable(false);
AppletLauncher applet = new AppletLauncher();
applet.initContainer(frame);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true) ;
}
});
}
}
这是我的Testpan代码:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Testpan extends JPanel {
public Testpan() {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("inside testpan paintComponent");
String str = "BioSnake";
g.setColor(Color.RED);
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 50));
FontMetrics fm = g.getFontMetrics();
int x = (g.getClipBounds().width - fm.stringWidth(str)) / 2;
int y = (g.getClipBounds().height / 2) + fm.getMaxDescent();
g.drawString(str, x, y);
}
}
在这里你找到我的HTML代码:
<HTML>
<HEAD>
<TITLE>My first applet!</TITLE>
</HEAD>
<BODY>
<APPLET code="AppletLauncher.class" width="500" height ="400">
You should see the applet here..
</APPLET>
</BODY>
</HTML>
怎么了?