here is what I wanted to do. There is a textfield and user enters what he wants. For example "Rectangle" or "rectangle", "circle" or "CIRCLE" like that. And then the user presses the button. After that program draws the shape that user wrote down below. I couldn't use the "paint" function itself. It got worse somehow. So I used "paintRec" etc. But I think that's not true according to OOP. So please show me the legit way to solve this question. There are a lot of wrong coding down there. That's for sure. Show me how can I do this. Where am I doing wrong. Thanks.
public class extends Applet implements ActionListener{
TextField tf;
Button draw;
public void init(){
tf = new TextField(10);
draw = new Button("Draw");
draw.addActionListener(this);
add(tf);
add(draw);
}
public void actionPerformed(ActionEvent e) {
String shape = tf.getText();
if (shape.equals("rectangle") || shape.equals("RECTANGLE"))
{
paintRec(null);
}
if (shape.equals("circle") || shape.equals("CIRCLE"))
{
paintCirc(null);
}
}
public void paintRec(Graphics g){
g.drawRect(30,30,50,60);
}
public void paintCirc(Graphics g){
g.drawOval(30, 30, 50, 60);
}
}
The problem lies at here:
public void actionPerformed(ActionEvent e) {
String shape = tf.getText();
if (shape.equals("rectangle") || shape.equals("RECTANGLE"))
{
paintRec(null);//passing null value to a method which has Graphics class instance and using it for drawing
}
if (shape.equals("circle") || shape.equals("CIRCLE"))
{
paintCirc(null);//same here
}
}
The better way is always use paint() method and call repaint() method. Use the below code:
import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
/*
<applet code = "Demo.class" width = 400 height = 200> </applet>
*/
public class Demo extends Applet implements ActionListener{
TextField tf;
Button draw;
String shape = "rectangle";//drawing rectangle by default
public void init(){
tf = new TextField(10);
draw = new Button("Draw");
draw.addActionListener(this);
add(tf);
add(draw);
}
public void actionPerformed(ActionEvent e) {
shape = tf.getText();
repaint();
}
public void paint(Graphics g){
super.paint(g);
if (shape.equals("rectangle") || shape.equals("RECTANGLE"))
{
g.drawRect(30,30,50,60);
}
if (shape.equals("circle") || shape.equals("CIRCLE"))
{
g.drawOval(30, 30, 50, 60);
}
else
{
//notify to enter the correct input
}
}
}