簡體   English   中英

用戶輸入的Java Applet繪圖形狀

[英]Java Applet Drawing Shapes by User Input

這是我想做的。 有一個文本字段,用戶輸入他想要的內容。 例如“矩形”或“矩形”,“圓形”或“圓形”。 然后用戶按下按鈕。 該程序繪制完用戶下面記下的形狀之后。 我不能使用“繪畫”功能本身。 不知何故變得更糟。 因此我使用了“ 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);
}
}

問題就在這里:

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
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM