java – 将JApplet添加到JFrame中
作者:互联网
我试图在JFrame中查看JApplet.
Class: Paint
public void paint(Graphics g) {
g.drawString("hi", 50, 50);
}
public static void main(String args[]) {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(methodThatReturnsJMenuBar());
JPanel panel = new JPanel(new BorderLayout());
frame.add(panel);
JApplet applet = new Paint();
panel.add(applet, BorderLayout.CENTER);
applet.init();
frame.pack();
frame.setVisible(true);
}
小程序显示在窗口中,但没有背景(它是透明的),当我单击菜单时,列表被覆盖.如何制作以便菜单列表不被覆盖,并且有背景?
编辑:当我绘制一个白色矩形时,它修复了背景问题,但菜单列表仍然被覆盖.
解决方法:
我会将我的GUI创建用于制作JPanel,然后在JApplet或JFrame中使用JPanel.例如,
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel {
private static final Dimension PREF_SIZE = new Dimension(400, 300);
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("hi", 50, 50);
}
@Override
public Dimension getPreferredSize() {
return PREF_SIZE;
}
public JMenuBar methodThatReturnsJMenuBar() {
JMenu menu = new JMenu("Menu");
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
}
然后在applet中使用:
import javax.swing.JApplet;
public class MyApplet extends JApplet {
public void init() {
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
}
private void createGUI() {
getContentPane().add(new MyPanel());
}
}
或者在JFrame中:
import javax.swing.JFrame;
public class MyStandAlone {
private static void createAndShowUI() {
MyPanel myPanel = new MyPanel();
JFrame frame = new JFrame("MyPanel");
frame.getContentPane().add(myPanel);
frame.setJMenuBar(myPanel.methodThatReturnsJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
标签:java,swing,jframe,japplet 来源: https://codeday.me/bug/20190518/1128160.html