1

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!
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Apr 09 '15 at 08:32
  • Yes, actually it is an assignment, and i totally agree cuz im studying html & JavaScript and i find applets useless compared to other PLs in creating web-based apps. – Maha Al-Zahrani Apr 13 '15 at 20:36
  • Anyways, Thank you! – Maha Al-Zahrani Apr 13 '15 at 20:37

1 Answers1

1
  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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366