1

我搜索了线程并尝试了所有解决方案,但将 drawRect 放入面板中。这是最好的解决方案还是我错过了一些简单的东西?我使用了 set visible 但我不认为这是必要的,我也尝试过重新绘制。

import java.applet.*;
import java.awt.*;
import java.awt.event.*;


public class HW5_drawRec extends Applet implements ActionListener

 {
   int width, height;
  int y = 150;
  int x = 75;

 //construct Components
Label appletLabel = new Label("Homework 5, Draw a Rectangle");
Label widthLabel = new Label("Enter the desired width:");
TextField widthField = new TextField(10);
Label heightLabel = new Label("Enter the desired height:");
    TextField heightField = new TextField(10);
 Button drawButton = new Button("Draw");
 Label outputLabel = new Label("Click to draw the rectangle.");

 public void init(){
    setForeground(Color.gray);
    add(appletLabel);
    add(widthLabel);
    add(widthField);
    add(heightLabel);
    add(heightField);
    add(drawButton);
    drawButton.addActionListener(this);
    add(outputLabel);
 }

 public void actionPerformed(ActionEvent e){

    width = Integer.parseInt(widthField.getText());
    height = Integer.parseInt(heightField.getText());

}

  public void paint(Graphics g){

if (width  >= 401){
    if (height >= 401){
    g.drawString("Please input dimensions greater than zero and/or less than 400",x,y);
  }}else{
     g.setColor(Color.RED);
     g.fillRect(x,y,width,height);
     g.setColor(Color.BLACK);
     g.drawRect(x,y,width,height);
     setVisible(true);

  }
}}
4

1 回答 1

1

放在repaint()actionPerformed 事件的末尾。

于 2012-04-25T23:18:34.773 回答