0

I have written code in java:

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ProstyApplet extends Applet
{
    Button b1 = new Button("BUTTON");
    @Override
    public void init()
    {
        System.out.println("START");
        b1.addActionListener(new B1());
        add(b1);
    }
    @Override
    public void paint(Graphics g)
    {
        g.setColor(Color.red);
        g.drawOval(150,150,100,100);
    }
    class B1 implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            //here I want to draw rectangle
        }
    }

}

I have created button B1 and I created ActionListener for B1. I want my program to draw rectangle when I click it but I have problem with using paint(), repaint() methods to do so. What is the way to draw rectangle after pressing the button?

Marcin Majewski
  • 1,007
  • 1
  • 15
  • 30
  • Could you explain what kind of problem you have? – joragupra Mar 07 '14 at 12:00
  • @joragupra I simply do not know the way how to draw rectangle after hitting the button. I searched the web but could not find any examples that may help me. – Marcin Majewski Mar 07 '14 at 12:02
  • 2
    First of all, use Swing, not AWT. Then next, read the tutorials on use of 1) [JButtons](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html), 2) [ActionListeners](http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html) and on 3) [painting with Swing](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html). Then give it a go! – Hovercraft Full Of Eels Mar 07 '14 at 12:02

1 Answers1

2

Here's how it goes. The paint() methods should paint a list of things to paint. The actionPerformed() method should simply add, remove or modify the things to paint, and then ask the applet to repaint. The paint() methods will then be called by AWT again, will iterate through the things to paint, and paint them.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thank you. I get it. But would you mind explaining how to modify paint() method ? – Marcin Majewski Mar 07 '14 at 12:08
  • 1
    The paint() should get the Rectangle(s) from the list of things to draw, and draw the rectangle(s). Read the javadoc of Graphics. – JB Nizet Mar 07 '14 at 12:15
  • 1
    @MarcinMajewski see [this answer](http://stackoverflow.com/a/22123304/2587435). You can add objects to a `List` in the `actionPerformed`, then `repaint()`. You _don't_ _"modify"_ the `paint`, you loop through the `List` in the `paint` method, as seen in example. – Paul Samsotha Mar 07 '14 at 12:30