同じ動作の違うプログラム

Since 2003.04.15  

背景色の設定

前回まで作った「Sunflag」は、実は1ヶ所変更したいところがあります。
次のように変更します。

上部略

public class Sunflag extends Applet {

    public void paint(Graphics g) {
        Dimension dim = this.getSize();
        int x = dim.width * 28 / 100;
        int y = dim.width * 14 / 100;
        int dist = dim.width * 42 / 100;
        // ここの2行を削除
        g.setColor(new Color(255, 0, 0));
        g.fillOval(x, y, dist, dist);
    }

    public void init() {
        this.setBackground(new Color(255, 255, 255));
    }
}

これで完成形とします。
setBackground(new Color(255, 255, 255));は、Sunflag の背景を指示した色(この文の場合は白色)にする Appletクラスの関数です。
このプログラムの場合は、アプレット全体が旗ですので、こちらのほうがシンプルな動作になります。

機能に従い文を分割

次回以降の解説のためにさらに変更した「Sunflag」を作成したいと思います。
完成形を壊したくありませんので、ファイルのコピーをします。

  1. 「Sunflag.java」を保存していなければ、まず上書き保存します。
  2. /net/sys5jp/ の下に「basic」フォルダを新たに作り、そこに「Sunflag.java」をコピーします。
  3. /net/sys5jp/basic/Sunflag.java を次のように書き換えます。
    次回での解説の便宜のため、行番号も表示しました。プログラム自体には行番号は入れないでください。

1 /*<applet code="net/sys5jp/basic/Sunflag.class"
2     codebase="../../../"
3     width=400 height=280>>
4 </applet>*/
5
6 package net.sys5jp.basic;
7
8 import java.applet.*;
9 import java.awt.*;
10
11 public class Sunflag extends Applet {
12     Dimension dim;
13     Color suncolor;
14     Color backcolor;
15
16     public void paint(Graphics g) {
17         int x, y, dist;
18
19         dim = this.getSize();  // ここのDimensionを削除
20         x = dim.width * 28 / 100;  // ここの int を削除
21         y = dim.width * 14 / 100;  // ここの int を削除
22         dist = dim.width * 42 / 100;  // ここの int を削除
23         suncolor = new Color(255, 0, 0);
24         g.setColor(suncolor);
25         g.fillOval(x, y, dist, dist);
26     }
27
28     public void init() {
29         backcolor = new Color(255, 255, 255);
30         this.setBackground(backcolor);
31     }
32 }

大幅に変更しましたが、同じように動作します。

両方のプログラムをコンパイルしてください。
さらに、/net/sys5jp/Sunflag.html を次のように書き換えて、開いてみましょう。

<html>
<head>
<style>
<!--
body {background-color:rgb(255,255,128)}
p {text-align:center}
-->
</style>
</head>
<body>
<p>
<applet code="net/sys5jp/Sunflag.class"
    codebase="../../"
    width=200 height=140>
</applet>
<applet code="net/sys5jp/basic/Sunflag.class"
    codebase="../../"
    width=200 height=140>
</applet>
</p>
</body>
</html>

次のように表示されるはずです。

トップヘ 目次ヘ 前ヘ 次ヘ