0

So I need to display images when the button is clicked upon. When I click on the button it displays nothing. Is it possible to pass a parameter into void paint method so that I can check the condition using if condition? If square button is clicked it should print square and if circle button is clicked it should print circle

import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Jungle extends Applet implements ActionListener{
    Button n;
    Button o;
    public void init()

    {
        n=new Button("Square");
        add(n);
        n.addActionListener(this);
         o = new Button("circle");
        add(o);
        o.addActionListener(this);



    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==n)
        {
            repaint();
        };


    }
    class Delta
    {
        void graphics(Graphics g)
        {
            g.drawRect(40, 40, 20, 20);
            g.fillRect(40, 40, 20, 20);
        }
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Hobbit
  • 11
  • 4
  • 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 29 '15 at 03:57

1 Answers1

1

..so that I can check the condition using if condition..

Declare an image as a class attribute and set its value to null:

Image img = null;

When the button is clicked, set the image to equal the image to display.

In the paint(Graphics) method, check for null before painting the image. E.G.:

if (img!=null) {
    g.drawImage(img, 0, 0, this);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    I like this; while `null` is the [_default value_](http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5) for the attribute, the explicit initialization clarifies its use as a [_sentinel value_](http://en.wikipedia.org/wiki/Sentinel_value). – trashgod Apr 30 '15 at 09:27