如何创建一个由jlayeredpane组成的jframe来绘制applet?

guicsvcw  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(412)

我正在尝试创建一个gui,在这个gui中,我可以根据applet中的内容在applet的“上方”绘制一个applet。为了测试这一点,我尝试通过使用jlayeredpane创建一个填充背景的面板来填充一个简单的矩形。不管我怎么试,我都不能让它工作。

import java.applet.Applet;
import java.awt.Color;
import java.awt.GridLayout;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class GUI {

private static JFrame frame;
private static JLayeredPane layers;
private static JPanel panel;
private static Applet applet;
private static final String JAR_PATH = "file:C:/Applet.jar";

public static void main(String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException{
    ClassLoader clientClassLoader = new URLClassLoader(new URL[]{new URL(JAR_PATH)});
    Class<?> client = clientClassLoader.loadClass("Loader");
    frame = new JFrame("JLayeredPane Testing");
    frame.setSize(400, 400);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout());
    applet = (Applet) client.newInstance();
    layers = new JLayeredPane();
    panel = new JPanel();
    panel.setSize(200, 200);
    panel.setOpaque(true);
    panel.setBackground(Color.BLACK);
    layers.add(panel, JLayeredPane.PALETTE_LAYER);
    layers.add(applet, JLayeredPane.DRAG_LAYER);
    frame.setContentPane(layers);
    frame.setVisible(true);
    applet.init();
}

}

运行程序时小程序不显示或初始化。

t9aqgxwy

t9aqgxwy1#

我认为您应该尝试将applet的内容绘制到bufferedimage。 BufferedImage buf=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 覆盖jframe中的绘画

public void paint(Graphics g){
   applet.paint(buf.getGraphics());
   g.drawImage(buf, 0, 0, this);
   super.paint(g);
}

然后可以在顶部添加swing组件。还要找出需要转发到applet的事件。使用 applet.get____Listeners() (例如getmouselisteners、getkeylisteners等)获取小程序的事件侦听器。然后将事件转发给听众。

相关问题