在使用窗口边框调整applet大小之前,不会显示Java绘制的drawRect

时间:2012-04-25 22:20:52

标签: java applet resize paint

我搜索了线程并尝试了每个解决方案,但将drawRect放入面板中。这是最好的解决方案还是我错过了一些简单的东西?我已经使用了set可见但是我不相信这是必要的,我也尝试过重绘。

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);

  }
}}

1 个答案:

答案 0 :(得分:1)

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