简体   繁体   中英

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.

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

Well the first question is: When do you want to switch? On a button klick? After some milliseconds?

With a button it´s pretty simple: You just have to draw 2 panels and show the first one per default. After the button is klicked you can use the methods repaint() and revalidate() to refresh the JFrame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM