長方形を描く drawRect(), drawRoundRect()

(蛇足) Rect は,Rectangle (長方形)の略

長方形を描くには,GraphicsdrawRect(), fillRect()メソッドを使います。
引数は,左上頂点のx, y座標,幅, 高さで,いずれも int型です。

※ drawRect(x1, y1, x2, y2) と fillRect(x1, y1, x2, y2) では,1画素分大きさが異なります。
  このことについては,こちらを参照のこと。

角を丸めた長方形は,drawRoundRect(), fillRoundRect() で描きます。
引数は,長方形の場合の4つに続き,角の楕円(1/4)の横方向の半径,縦方向 の半径を指定します。


DrawRect.java

テキストボックスに数値を記入し,Drawボタンをクリックすると,指定した数の窓を描きます。

// DrawRect.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class DrawRect extends Applet implements ActionListener {
    Dimension s;
    TextField txt;
    Button btn;
    int n=0;

    public void init() {
        setBackground(Color.pink);    // 背景色
        txt = new TextField(3);
        btn = new Button("Draw");
        add(txt);
        add(btn);
        btn.addActionListener(this);
    }

    public void paint(Graphics g) {
        float fd;
        int x;
        s=getSize();                          // Appletのサイズを取得
        g.setColor(Color.yellow);
        g.fillRect(0,30,s.width,s.height-60); // 上下30画素を除いて黄色に
        g.setColor(Color.cyan);
        fd = (s.width - 10f)/n;               // fd = 長方形の横幅 + 間隔(10画素)
        for(int i=0; i<n; i++) {
            x = (int)(10+i*fd);               // 各長方形の左端の座標
            g.fillRoundRect(x,40,(int)fd-10,s.height-80,10,10);
        }
    }

    public void actionPerformed(ActionEvent e) {
        n = Integer.parseInt(txt.getText());   // 長方形の数
        if(n>20) n=20;
        repaint();
    }
}

(補足説明)

ボタンをクリックするとテキストフィールドに入力された数 n を取得し,その数だけ角を丸めた長方形を描いています。

actionPerformed() の中に書かれている以下の行は,paint() の中に書くこともできます。

        n = Integer.parseInt(txt.getText());   // 長方形の数
        if(n>20) n=20;

練習 Applet の外周(内周?)に線を付けなさい。

ヒント: 次の行でいいでしょうか?

g.drawRect(0, 0, s.width, s.height);