Canvas painting in applet

I currently have a small Java program that I would like to run both on the desktop (like a JFrame) and in an applet. Currently, all drawings and logic are handled by a class that extends Canvas. This gives me a very nice main method for a desktop application:

public static void main(String[] args) {
    MyCanvas canvas = new MyCanvas();
    JFrame frame = MyCanvas.frameCanvas(canvas);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    canvas.loop();
}

      

Is it possible to do something like this for an applet? Ideally, MyCanvas will remain the same for both cases.

Not sure if this matters, but I am drawing with BufferStrategy with setIgnoreRepaint(true)

.

Edit . To clarify, my problem seems to be painting the canvas - since the whole painting is done from a call canvas.loop()

.

+1


source to share


3 answers


Applet is a Container , just add your canvas.



+2


source


Typically, you will have an application that is also an applet for your entry point class to extend the applet, and setting it up adds a Canvas to itself, etc. etc.

Then, in the main method version, you simply instantiate the Applet class and add it to the new frame (or JApplet / JFrame, etc.).



See here and here for examples of a technique that essentially boils down to (from the first example):

  public static void main(String args[])
  {
    Applet applet = new AppletApplication();
    Frame frame = new Frame();
    frame.addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        System.exit(0);
      }
    });

    frame.add(applet);
    frame.setSize(IDEAL_WIDTH,IDEAL_HEIGHT);
    frame.show();
  }

      

+1


source


Canvas

not suitable for adding Swing components. Use JComponent

(and setOpaque(true)

) instead .

Swing components should always be managed in the AWT Event Dispatch Thread (EDT). Use java.awt.EventQueue.invokeLater

( invokeAndWait

for applets). You shouldn't be doing any blocking operations from the EDT, so create your own threads for that. By default, you are running on the main thread (or the applet thread for applets), which is completely separate from the EDT.

I suggest removing any dependency on your MyCanvas

do JFrame

. I also suggest keeping the code for your applications using a framework separate from it using applets. Adding a component JApplet

is the same as for JFrame

(in both cases, there shenigany, where in fact there is that add

actually causes getContentPane().add

that may cause some unnecessary confusion). The main difference is that you cannot pack

applet.

0


source







All Articles