課題
1 偶数奇数判定プログラム(GUIaa)をタイプし、その動作を考察せよ。
2 例外処理について、考察せよ。
3 上述のサンプルプログラムに出てきたGUI部品を、全て使ったプログラムを作成せよ。
4 摂氏から華氏、華氏から摂氏への温度換算ができるプログラムを作成せよ。
5 「電卓」プログラム。中身は自分の思うように。
import java.awt.*; import java.awt.event.*; public class GUIaa extends Frame { Button b0 = new Button("Even/Odd?"); Label x0 = new Label("Type a number and press..."); TextField t0 = new TextField(); public GUIaa() { 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); b0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { int i = (new Integer(t0.getText())).intValue(); 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 GUIaa(); win.setSize(200, 150); win.setVisible(true); win.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); } }
●1、2行目の記述はGUIプログラムに必要なもの。 import java.awt.*; //GUI関係のパッケージクラス群をインポート import java.awt.event.*; //アクションリスナー(イベント処理)を使うのに必要 ●グラフィックの出力 Button b0 = new Button("Even/Odd?"); これでボタンを作成。ダブルクォートで囲まれた文字はそのままボタンの中に出力される。 Label x0 = new Label("Type a number and press..."); ラベルの作成。ダブルクォートで囲まれた文字をラベルとして出力。 TextField t0 = new TextField(); ウィンドウの作成。 ●グラフィックの配置 add(t0); t0.setBounds(10, 40, 90, 30); t0(ボタン)の配置。末尾の括弧内は順にウィンドウの左上を原点として(x座標、y座標、横幅、縦幅)以下同じ。 ●イベント b0.addActionListener(new ActionListener() { ボタンが押された時の動作クラス public void actionPerformed(ActionEvent evt) { int i = (new Integer(t0.getText())).intValue(); ここからは値の処理で入力された数値をint型で返し、その値をiに代入。 if(i % 2 == 0) { x0.setText(i + " is Even"); } else { x0.setText(i + " is Odd"); 数値判定。iが2で割り切れたら偶数(Even)それ以外は奇数(Odd)と判定。 それぞれ「… is Even/ is Odd」と出力。 Frame win = new GUIaa(); Frameをwinに変換し、winの作成。 win.setSize(200, 150); win.setVisible(true); ウィンドウのサイズを定義して、画面に出力。 win.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); プログラムコードから、当然普通に終わらすことの出来ないプログラムである。 割り込みキー(Control + x)等で強制終了させる。
import java.awt.*; import java.awt.event.*; public class GUIaa_2 extends Frame { Button b0 = new Button("判定!"); Label x0 = new Label("整数を入力してください"); TextField t0 = new TextField(); public GUIaa_2() { 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); b0.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try{ int i = (new Integer(t0.getText())).intValue(); t0.setText(""); if (i % 2 == 0) { x0.setText(i + " は偶数です"); } else { x0.setText(i + " は奇数です"); } } catch (NumberFormatException e) { x0.setText("エラー!!"); } } }); } public static void main(String[] args) { Frame win = new GUIaa_2(); win.setSize(200, 150); win.setVisible(true); win.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); } }