javaswingawt

Is there a way to embed a JPanel (Java Swing) into a Panel (Java AWT)?


I have got a Java Swing application (vocabulary trainer) and want to embed its main JPanel into a Java AWT application. Can this be done at all?

I googled for hours but could not find anything about the issue.


Solution

  • So yes. java.awt.Panel extends from java.awt.Component. javax.swing.JPanel extends from java.awt.Container which extends from java.awt.Component. Therefore, the java.awt.Panel.add(Component,Object) method accepts anything that extends java.awt.Component. Since javax.swing.JPanel extends java.awt.Component through several levels of other base classes (i.e. JPanel -> JComponent -> Container -> Component) it can be passed to the panel. For example:

    Panel awtPanel = new Panel(new BordreLayout());
    JPanel topPanel = new VocabularyTrainerPanel();
    awtPanel.add( topPanel, BorderLayout.CENTER );
    

    Now just because you can do that doesn't mean you should. AWT is beyond ancient. Swing at this point is pretty old too, but AWT has been left for dead. I can only say I wouldn't do this.