Maha Al-Zahrani
Maha Al-Zahrani

Reputation: 11

How to make graphics disappear?

I want to create an applet with a face-drawing game with buttons to change the parts of the face, but I don't know how to use the setVisible(false) to make e.g. an Oval to disappear inside the action listener while it is declared inside the paint method block.

//import necessary packages
public class applet1 extends Applet implements ActionListener
{
    Button b;
init()
{
    b=new Button("Oval face");
    b.addActionListener(this);
    add(b);
}
public void paint(Graphics g)
{
    g.drawOval(50,50,50,50);
}
public void actionPerformed(ActionEvent ae)
{
    g.setVisible(false); //I know this line cannot be executed but I jast want to show the idea!
}
}

Upvotes: 1

Views: 485

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

  1. Call super.paint before doing any custom painting
  2. Use a state flag to change what paint actually does
  3. Consider using Swing over AWT and wrap you core application around a JPanel and add this to your top level container

Maybe something more like...

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;

public class Content extends JPanel implements ActionListener {

    private JButton b;
    private boolean paintOval = false;

    public Content() {
        b = new JButton("Oval face");
        b.addActionListener(this);
        add(b);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
        if (paintOval) {
            g.drawOval(50, 50, 50, 50);
        }
    }

    public void actionPerformed(ActionEvent ae) {
        paintOval = false;
        repaint();
    }
}

Then add this to you top level container...

public class Applet1 extends JApplet {
    public void init() {
        add(new Content());
    }
}

But if you're just stating out, I'd avoid applets, they have there own set of issues which can make life difficult when you're just learning

Upvotes: 1

Related Questions