user1703554
user1703554

Reputation: 119

Embed JPanel in JApplet (always on top)

I have a hybrid swing application which can be run as applet or java application with the following structure:

public class Gui extends JApplet {

    public void init() {...}

    public void paint(Graphics g) {
       ...
       g.drawImage(image, 0, 0, this);
    }

    public static void main(String args[]) {

       JFrame frame = new JFrame();
       JDialog dialog = new JDialog(frame);

       Gui gui = new Gui();
       gui.init();
       gui.start();

       dialog.add("Center", gui);

       ...
    }

}

The whole gui consists of one drawing area which is continously updated. I would like to embed a panel which is always on top and independent of the underlying drawing process.

I tried using JLayeredPane and add it between JDialog and JApplet, but Japplet cant be added to the Pane because it is a top level container.

I also tried realising it with the glasspane but no success at all.

Is there a solution without refactoring to much since the structure should be kept as far as possible.

Upvotes: 0

Views: 400

Answers (1)

camickr
camickr

Reputation: 324108

Don't override paint() of a top level container, like JApplet or JFrame. Custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent). Then you add the panel to the frame.

dialog.add("Center", gui);

The is not the way to add a component to a panel. Read the Container API to find the proper add(...) method to use. Also don't hardcode string values. Every layout manager contains variables that can be used as the constraint values.

I would like to embed a panel which is always on top and independent of the underlying drawing process.

Not sure this makes sense. If the panel is always on top, then it would cover the painting.

I tried using JLayeredPane

That sounds like the proper approach. You add the layered pane to the frame or applet. Then you can have a background painting panel and another transparent panel on top. Read the Swing tutorial on Using Layered Panes for a working example.

Upvotes: 1

Related Questions