这是我想要做的。有一个文本域,用户输入他想要的内容。例如“矩形”或“矩形”,“圆圈”或“圆圈”之类的。然后用户按下按钮。在该程序绘制用户在下面写下的形状之后。我无法使用“绘画”功能本身。它以某种方式变得更糟。所以我使用了“paintRec”等。但是根据OOP,我认为这不是真的。所以请告诉我解决这个问题的合法方法。那里有很多错误的编码。这是肯定的。告诉我怎么做这个。我在哪里做错了。感谢。
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);
}
}
答案 0 :(得分:1)
问题出在这里:
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
}
}
更好的方法是始终使用paint()方法并调用repaint()方法。使用以下代码:
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
}
}
}