Search code examples
javaswingappletpaintjcreator

How to repaint paint methods in java applet?


I would like to use applet to switch between 2 "frames".

I want to use an applet to paint something and then remove it and paint something else. Is there any way to do this?

Example:

if(true){
    public void paint1(Graphics g) {
        g.setColor(Color.black);
        g.fillRect( 80,400, 20, 10 );
    }
}else
    public void paint2(Graphics g) {
        g.setColor(Color.green);
        g.fillRect( 50,440, 70, 60 );
    }
}

All attempts I've tried on this crashed the applet.

My project: Me and my friend are writing a simple code where we need to use some kind applet graphics. We made the idea to make a program where 2 characters jump up and down. problem is that we are going to have an "AI" that jumps whenever he feels like it. So a CardLayout wont work because then we are in control of everything.


Solution

  • I will suggest using a CardLayout if you intend to "switch" between 2 drawings.

    However, if you want to continue with what you currently have by drawing based on a condition, you may do something like this:

    class DrawingSpace extends JPanel{
    
        private BufferedImage display;
        //Other variables, initializations, constructors not shown
    
        private void init(){
            display = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        }
    
        public void draw(){
            if(whatever){    //if whatever == true
                Graphics2D g2 = display.createGraphics();
                g2.setColor(Color.BLACK);
                g2.fillRect( 80, 400, 20, 10 );
                repaint();
            }else{
                Graphics2D g2 = display.createGraphics();
                g2.setColor(Color.GREEN);
                g2.fillRect( 50, 440, 70, 60 );
                repaint();
            }
        }
    
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(display, 0, 0, width, height, null);
        }
    }