Report7



Wikiに戻る

課題

  1. 偶数奇数判定プログラム(GUIaa)をタイプし、その動作を考察せよ。
  2. 例外処理について、考察せよ。
  3. 上述のサンプルプログラムに出てきたGUI部品を、全て使ったプログラムを作成せよ。
  4. 摂氏から華氏、華氏から摂氏への温度換算ができるプログラムを作成せよ。
  5. 「電卓」プログラム。中身は自分の思うように。

課題1 偶数奇数判定プログラム(GUIaa)をタイプし、その動作を考察せよ。


〜プログラム〜
import java.awt.*;             //GUIコンポーネントを使う為に必要
import java.awt.event.*;           // アクションリスナー(イベント処理)を使うのに必要

public class Report7_GUIaa extends Frame{               //Frameクラスを継承
    Button    b0 = new Button("Even/Odd?");          //Buttonの宣言と初期化
    Label     x0 = new Label("Type a number and press...");  //Labelの宣言と初期化   
    TextField t0 = new TextField();              //TextFieldの宣言と初期化

    public Report7_GUIaa() {                  //コンストラクタ
        setLayout(null);                  // コンポーネント配置方法を絶対位置指定
        add(t0); t0.setBounds(10, 40, 90, 30);             //t0の位置設定(x=10,y=40,幅=90,高さ=30)
        add(b0); b0.setBounds(110, 40, 100, 30);      //b0の位置設定(x=110,y=40,幅=100,高さ=30)
        add(x0); x0.setBounds(10, 80, 180, 30);      //x0の位置設定(x=10,y=80,幅=180,高さ=30)

        b0.addActionListener(new ActionListener() {                //b0(ボタン)のアクションリスナー
            public void actionPerformed(ActionEvent evt) {        //b0が押されたときに実行されるメソッド
                int i = (new Integer(t0.getText())).intValue();   //TextField [t0]から文字列を取得しint型iに代入
                t0.setText("");

                if(i % 2 == 0) {                 //偶数ならば
                    x0.setText(i + " is Even");
                } else {                              //奇数ならば
                    x0.setText(i + " is Odd");
                }
            }
        });
    }
    
    public static void main(String[] args) {
       Frame win = new Report7_GUIaa();            //windowの生成
       win.setSize(200, 150); win.setVisible(true);           //windowの大きさを幅200.高さ150にする
       win.addWindowListener(new WindowAdapter() {      //windowの表示
           public void windowClosing(WindowEvent evt) {    //windowを閉じたら
               System.exit(0);                //アプリケーションを終了させる
           }
       });
    }
}


〜実行結果〜

[考察]

import java.awt.*;0
import java.awt.event.*;

  • 「import」とは既存のパッケージに含まれるクラスを利用する時に使うもの。
  • 「import」の構文は import パッケージ名.クラス名 である。
  • AWTのコンポーネントとイベント処理を行う為に必要なパッケージをインポー トしています。こうすることで短い名前(ButtonやLabalだけ)でクラスやメソッ ド等を扱うことができるようになります。

    public class Report7_GUIaa extends Frame{……}

  • 「extends」とは2つのクラス間に継承関係を形成するときに使う。
  • 「extends」の構文は class clsName2 extends clsName1{} となり clsName1はclsName2のスーパークラスと言う意味になる。
  • Frameクラスを継承してウインドウを作成出来るようにしています。

    Button b0 = new Button("Even/Odd?");
    Label x0 = new Label("Type a number and press...");
    TextField t0 = new TextField();

  • ボタン、ラベル、テキストフィールドの生成
  • Button Label TextFieldはコンポーネントと呼ばれるGUI部品

    setLayout(null);
    add(t0); t0.setBounds(10, 40, 90, 30);
    add(b0); b0.setBounds(110, 40, 80, 30);
    add(x0); x0.setBounds(10, 80, 180, 30);

    ウインドウを生成したときに呼び出されるコンストラクタ内にあるため、この記 述でウインドウにコンポーネントを配置することになります。 add()はコンポーネントを追加、setLayout()はレイアウトモードの指定、 setBounds()はコンポーネントの配置場所を指定するメソッドです。 レイアウトモードとは、コンポーネントの配置方法を指定するものでいくつもあ りますが、今回は「null」を使います。 これはコンポーネントを絶対位置で指定する方法で、setBoundsでコンポーネン トの配置場所を指定します。

    cName.setBounds(x , y , width , height)

    cName → コンポーネント名
    x → x座標
    y → y座標
    width → コンポーネントの幅
    height → コンポーネントの高さ
  • これはsetLayout(null)の時にしか使えません。他のレイアウトモードではこ の記述をしても無効になります。

    b0.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    int i = (new Integer(t0.getText())).intValue();
    x0.setText("");
    if(i % 2 == 0) {
    x0.setText(i + " is Even");
    } else {
    x0.setText(i + " is Odd");
    }
    } });

  • ボタン(b0)を押したときテキストフィールドの文字列を読み取り、数字に変換し て、偶数か奇数かを判定、その後ラベルに文字列を表示
  • ボタンが押されたときに発生するイベントを受け取るためのリスナ ActionListenerにボタンを登録(addActionListener)。
  • ActionPerformedメソッドは、リスナに登録されたボタンが押されたときに呼び 出されるメソッドです。ここにボタンが押された際の処理を記述する。
  • この書き方は「無名内部クラス方式」と呼ばれています。

    public static void main(String[] args) {
    Frame win = new GUIaa();
    win.setSize(200, 150);
    win.setVisible(true);
    win.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    System.exit(0);
    }
    });
    }


    mainメソッドです。ウインドウを作成し、大きさを指定(setSize(200,150))、画 面にウインドウを表示(setVisible(true))しています。
  • WindowAdapterはWindowListenerの抽象メソッドをすべて空の内容で実装した クラスです。アダプタクラスと呼ばれます。
  • WindowListenerはインターフェースであり、複数の抽象メソッドがある。
  • すべての抽象メソッドをオーバーライド(上書き記述)しないといけない。
    System.exit(0)はプログラムを終了させるメソッドです。正常に終了をした ことを示す場合は引数に0を、異常終了したことを示す場合には0以外の数値を引 数に渡すことが通例となっている。

    2.例外処理について考察せよ


    例外処理とは、Javaが実行時のエラーを処理するための手段です。Javaは このような時、「例外処理」という機能で対処します。
    例外処理の基本構文として
    throw   → 例外を発生させる
    throws  → 例外の可能性があることを宣言する
    try     → 例外を検査する
    catch   →  例外を細かくする
    finally →  必ず実行させる文を記述する
    
    があります。Javaのクラスライブラリが備えるメソッドには、例外を発生させる ものが多くあります。それらのメソッドを使用する際は、try,catch,finally文 を適切に記述しなければいけません。例外処理の構文を以下に示します。
    try {
         (例外を発生する可能性のある文をここに書く)
    }
    catch (例外のタイプ2 変数名){
        (例外のタイプ2が発生した時に処理する文をここに書く)
    }
    catch (例外のタイプ2 変数名){
         (例外のタイプ2発生した時に処理する文をここに書く)
    }
                 :
             :
    catch (例外のタイプn 変数名){
         (例外のタイプnが発生した時に処理する文をここに書く)
    }
    finally {
         (例外発生の有無にかかあらず必ず実行する文をここに書く)
    }
    


    3.上述のサンプルプログラムに出てきたGUI部 品を、全て使ったプログラムを作成せよ。


    import java.awt.*;
    import java.awt.event.*;
    
    public class report7 extends Frame{
    
        Button bt1 = new Button("計算開始");
        Button bt2 = new Button("CLEAR");
        Label l1 = new Label("縦の長さ");
        Label l2 = new Label("横の長さ");
        Label l3 = new Label("高さ");
        Label l4 = new Label("結果");
        TextField t1 = new TextField();
        TextField t2 = new TextField();
        TextField t3 = new TextField();
        TextField t4 = new TextField();
    
        public report7(){
            setLayout(null);
            add(l1); l1.setBounds(20, 50,  60, 30);
            add(l2); l2.setBounds(20, 100, 60, 30);
            add(l3); l3.setBounds(20, 150, 60, 30);
            add(l4); l4.setBounds(20, 250, 60, 30);
            add(t1); t1.setBounds(150, 50, 100, 30);
            add(t2); t2.setBounds(150, 100, 100, 30);
            add(t3); t3.setBounds(150, 150, 100, 30);
            add(t4); t4.setBounds(150, 250, 150, 30);
            add(bt1);bt1.setBounds(  20, 200, 100, 40);
            add(bt2);bt2.setBounds( 140, 200, 100, 40);
    
            bt1.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent evt){
                        try{
                            double length1 =  (new Double(t1.getText())).doubleValue();
                            double length2 = (new Double(t2.getText())).doubleValue();
                            double length3 = (new Double(t3.getText())).doubleValue();
                            double answer = (length1 * length2 * length3);
                            t4.setText(Double.toString(answer));
                        }catch(Exception ex){
                            t4.setText("整数を入れて下さい");
                        }
    
                    }
                });
    
            bt2.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent evt){
                        t1.setText("");
                        t2.setText("");
                        t3.setText("");
                        t4.setText("");
                    }
                });
        }
        public static void main(String[] args) {
            Frame win = new report7();
            win.setTitle("立体の体積");
            win.setSize(350, 300);
            win.setVisible(true);
            win.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent evt) {
                        System.exit(0);
                    }
                });
        }
    }
    

    〜実行結果〜
    [考察]
    このプログラムはサンプルプログラムで使用したButton,Label,TextFieldのコンポーネントを使用している。
    まずmainメソッドから説明する。まずreport7クラスをインスタンス化しコンストラクタを呼び出す。
    そして、Frameコンテナを表示する。ウィンドウを閉じる動作をそのFrameコンテナに登録している。
    importしているものはGUI関係のパッケージをimportしている。
    report7クラスについて説明する。
    まず、2つのButtonと4つのLabel,TextFieldのオブジェクトを作成。
    コンストラクタ内部でFrameコンテナに作成した全てのコンポーネントを追加。
    そして、レイアウトマネージャを使わず配置。
    この部分はtryブロックで囲まれていてもし、整数以外のものを入力するcatchブロックにより例外がcatchされ処理される。
    bt2 Buttonは初期化するButtonなのでTextFieldに何も表示しないようにする。

    (new Double(t1.getText())).doubleValue()


    というメソッドがある。これは引数をDoubleクラスのオブジェクトとし、そのオブジェクトを静的メソッドdoubleValueでdouble型に変換するというもの。
    引数はdouble型でここで型変換できなかったもの(文字列等)は例外を発生する。


    4.摂氏から華氏、華氏から摂氏への温度換算ができるプログラムを作成せよ。


    import java.awt.*;
    import java.awt.event.*;
    
    public class report7_henkan extends Frame{
    
        Button     b0 = new Button("華氏に変換する");
        Button     b1 = new Button("摂氏に変換する");
        Label     x0 = new Label("変換前");
        Label     x1 = new Label("変換後");
        Label     x2 = new Label("数字をいれて下さい");
        TextField  t0 = new TextField();
        TextField  t1 = new TextField();
    
        public henkan(){
             setLayout(null);
             add(t0); t0.setBounds(90,60,50,20);
             add(b0); b0.setBounds(65,85,150,20);
             add(x0); x0.setBounds(40,60,50,20);
             add(b1); b1.setBounds(220,85,150,20);
             add(t1); t1.setBounds(40,110,50,20);
             add(x1); x1.setBounds(40,145,160,20);
            add(x2); x2.setBounds(160,145,160,20);
    
             b0.addActionListener(new ActionListener() {
                     public void actionPerformed(ActionEvent evt) {
                        try{
                             int i = (new Integer(t0.getText())).intValue();
                             i = (int)Math.rint(1.8*i+32);
                             t1.setText("" + i);
                             x2.setText("摂氏" + t0.getText() + "は華氏" + i
                     );
                        }catch(Exception ex){
                             t1.setText("error");
                        }
                     }
             });
    
             b1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                       try{
                           int i = (new Integer(t0.getText())).intValue();
                           i = (int)Math.rint((i-32)/1.8);
                           t1.setText("" + i);
                           x2.setText("華氏"+ t0.getText() +"は摂氏"+ i);
                        }catch(Exception ex){
                        t1.setText("error");
                        }
                    }
             });
         }
    
         public static void main(String[] args) {
             Frame win = new report7_henkan();
             win.setSize(300, 270); 
             win.setVisible(true);
             win.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent evt) {
             System.exit(0);
                     }
                 });
         }
    }
    
    
    〜実行結果〜
    [考察]
    まずmainメソッドから考察する。まずreport7_henkanのコンストラクタを呼び出す。
    そして、Frameにタイトル付けてウィンドウサイズを設定してFrameコンテナを表示する。
    そして、ウィンドウを閉じる動作を記述している。
    次に上から順に説明していく。まず使用するコンポーネントのオブジェクトを作成。
    それをコンストラクタ内部でFrameコンテナに追加しレイアウトマネージャを使わずに配置。
    次にボタンの処理を記述。温度変換ボタンを押した時の処理を考える。

  • [華氏に変換する]のボタンを押した時

    b0.addActionListener(new ActionListener(){}

    が呼び出されて(入力された数字)×1.8+32計算された数字が表示されます。

  • [摂氏に変換する]のボタンを押した時

    b1.addActionListener(new ActionListener(){}

    が呼び出されて{(入力された数字)−32}÷ 1.8計算された数字が表示されます。


    5.「電卓」プログラム。中身は自分の思うよ うに。


    import java.awt.*;
    import java.awt.event.*;
    
    public class Dentaku extends Frame implements ActionListener{
    
        Button button00 = new Button("00");
        Button button0  = new Button("0");
        Button button1  = new Button("1");
        Button button2  = new Button("2");
        Button button3  = new Button("3");
        Button button4  = new Button("4");
        Button button5  = new Button("5");
        Button button6  = new Button("6");
        Button button7  = new Button("7");
        Button button8  = new Button("8");
        Button button9  = new Button("9");
        Button btn_AC   = new Button("AC");
        Button btn_tasu = new Button("+");
        Button btn_hiku = new Button("―");
        Button btn_kake = new Button("×");
        Button btn_waru = new Button("÷");
        Button btn_wa   = new Button("=");
        
        Label l_display = new Label("", Label.RIGHT); 
        
        long num1 = 0;
        long num2 = 0;
        int enzansi = 0;
        
        // コンストラクタ
        public Dentaku() {
            
            final int BW = 80;  // ボタンの幅
            final int BH = 50;  // ボタンの高さ
            final int M = 10;   // マージン
            
            setLayout(null);
            
            add(l_display); 
              l_display.setBounds(M, M+20, 400, 52);
              l_display.setBackground(Color.gray);
              l_display.setFont(new Font("Monospaced",Font.BOLD,42));
            add(button0);  
              button0.setBounds(M+BW*0, M+BH*6, BW,BH);
              button0.addActionListener(this);
            add(button00); 
              button00.setBounds(M+BW*1, M+BH*6, BW, BH);
              button00.addActionListener(this);
            add(button1);
              button1.setBounds(M+BW*0, M+BH*5, BW, BH);
              button1.addActionListener(this);
            add(button2);
              button2.setBounds(M+BW*1, M+BH*5, BW, BH);
              button2.addActionListener(this);
            add(button3);
              button3.setBounds(M+BW*2, M+BH*5, BW, BH);
              button3.addActionListener(this);
            add(button4); 
              button4.setBounds(M+BW*0, M+BH*4, BW, BH);
              button4.addActionListener(this);
            add(button5);
              button5.setBounds(M+BW*1, M+BH*4, BW, BH);
              button5.addActionListener(this);
            add(button6);
              button6.setBounds(M+BW*2, M+BH*4, BW, BH);
              button6.addActionListener(this);
            add(button7);
              button7.setBounds(M+BW*0, M+BH*3, BW, BH);
              button7.addActionListener(this);
            add(button8);
              button8.setBounds(M+BW*1, M+BH*3, BW, BH);
              button8.addActionListener(this);
            add(button9);  
              button9.setBounds(M+BW*2, M+BH*3, BW, BH);
              button9.addActionListener(this);
            add(btn_back);
              btn_back.setBounds(M+BW*0, M+BH*2, BW*2, BH);
              btn_back.addActionListener(this);
            add(btn_AC);
              btn_AC.setBounds(M+BW*2, M+BH*2, BW, BH);
              btn_AC.addActionListener(this);
            add(btn_tasu); 
              btn_tasu.setBounds(M+BW*3, M+BH*4, BW, BH*2);
              btn_tasu.addActionListener(this);
            add(btn_hiku); 
              btn_hiku.setBounds(M+BW*3, M+BH*2, BW, BH*2);
              btn_hiku.addActionListener(this);
            add(btn_kake); 
              btn_kake.setBounds(M+BW*4, M+BH*4, BW, BH*2);
              btn_kake.addActionListener(this);
            add(btn_waru);
              btn_waru.setBounds(M+BW*4, M+BH*2, BW, BH*2);
              btn_waru.addActionListener(this);
            add(btn_wa);
              btn_wa.setBounds(M+BW*3, M+BH*6, BW*2, BH);
              btn_wa.addActionListener(this);
        }
    
        // ActionListener インタフェースの実装
        public void actionPerformed(ActionEvent e) {
    
            if (num1 >= 100000000000000L) { num1 /= 10; }  // 限界値の設定
                
            if (e.getSource() == button0)  { num1 *= 10; }  
            if (e.getSource() == button00) { num1 *= 100; }
            if (e.getSource() == button1)  { num1 = num1 * 10 + 1; }
            if (e.getSource() == button2)  { num1 = num1 * 10 + 2; }
            if (e.getSource() == button3)  { num1 = num1 * 10 + 3; }
            if (e.getSource() == button4)  { num1 = num1 * 10 + 4; }
            if (e.getSource() == button5)  { num1 = num1 * 10 + 5; }
            if (e.getSource() == button6)  { num1 = num1 * 10 + 6; }   
            if (e.getSource() == button7)  { num1 = num1 * 10 + 7; }
            if (e.getSource() == button8)  { num1 = num1 * 10 + 8; }
            if (e.getSource() == button9)  { num1 = num1 * 10 + 9; }
            if (e.getSource() == btn_back) { num1 /= 10; }
            if (e.getSource() == btn_AC)   { num1 = 0; num2 = 0; enzansi =
                0;}
            
            l_display.setText("" + num1);        // 入力途中の数字を画面に出
                力
            
            if (e.getSource() == btn_tasu) { keisan(); enzansi = 1; } 
            if (e.getSource() == btn_hiku) { keisan(); enzansi = 2; } 
            if (e.getSource() == btn_kake) { keisan(); enzansi = 3; } 
            if (e.getSource() == btn_waru) { keisan(); enzansi = 4; } 
            if (e.getSource() == btn_wa)   { keisan(); enzansi = 0; }
    
        }
        
        // 演算子の種類を判別して計算をするメソッド
        public void keisan() {
            if (enzansi == 1) { num1 = num2 + num1; }
            else if (enzansi == 2) { num1 = num2 - num1; }
            else if (enzansi == 3) { num1 = num2 * num1; }
            else if (enzansi == 4) { num1 = num2 / num1; }
            l_display.setText("" + num1);
            num2 = num1;
            num1 = 0;
        }
    
        // mainメソッド
        public static void main(String[] args) {
            Frame win = new Dentaku();
            win.setSize(420,360);
            win.setBackground(Color.black);
            win.setVisible(true);
            
            win.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent ev) {
                    System.exit(0);
                }
            });
        }
    }