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?


    public void paint1(Graphics g) {
        g.fillRect( 80,400, 20, 10 );
    public void paint2(Graphics g) {
        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.fillRect( 80, 400, 20, 10 );
            Graphics2D g2 = display.createGraphics();
            g2.fillRect( 50, 440, 70, 60 );

    public void paintComponent(Graphics 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.

Need Your Help

Creating a range from several ranges in excel vba

excel vba excel-vba range

I have a worksheet with a matrix, which is divided diagonally with a cell that is black. The matrix contains the same header, both vertically and horisontally.

PDF Document is only half in width when converted a png image to pdf using PDFBox

java pdf-generation document pdfbox

I have used PDFBox to convert a png image to pdf document and i am successfully able to do that.