Adding JApplet to JFrame

I am trying to view a japplet inside a jframe.

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

The applet appears in the window, but there is no background (it is transparent), and when I click on the Menu, the list closes. How to make the menu list not be closed, and there is a background?

Edit: when I draw a white rectangle, it fixes the background problem, but the menu list is still closed.

+4
source share
1 answer

I would like to create my graphical representation to create a JPanel, and then use the JPanel as I wish, either in a JApplet or in a JFrame. For instance,

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

Then for use in the 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()); } } 

Or in a 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(); } }); } } 
+6
source

All Articles