JAVAでGUIプログラム
JAVAでGUIアプリを作ってみる。
GUIを作るにはAWTというライブラリ?を使用してみるようだ。他にもSwingというのがあるみたいだけどザウルスの環境だと使えないみたい。全くわからないのあちこちググってボタンを押したイベントを取得するプログラムを作成。
ウィジェットの配置に東西南北を指定するのは面白いです。2つのボタンの処理を一つの関数?の中で処理しなければいけないのはちょっとアレだなぁ、多分他に記述方法があると思うけど。
参考にさせていただいたサイト:
- とほほのJAVA入門(http://www.tohoho-web.com/java/index.htm)
- Deep Side of Java〜Java 言語再入門(http://www.nurs.or.jp/~sug/soft/java/)
- JavaTM 2 Platform Standard Edition 5.0 API 仕様(http://java.sun.com/j2se/1.5.0/ja/docs/ja/api/)
// Test.java // JAVA GUIプログラムのサンプル // 日本語はUTF-8で記述すること import java.awt.*; import java.awt.event.*; public class Test extends Frame // Frameクラスから継承 implements ActionListener, WindowListener { // Event監視を行う public static void main(String[] args) { Test test = new Test("サンプル"); test.setSize(320, 360); test.setVisible(true); // これが無いと表示しない } TextArea tarea = new TextArea("Hello\nWorld\n"); public Test(String title) { super(title); Label label = new Label("テストプログラム"); add(label, "North"); // 上に配置 // TextArea tarea = new TextArea("Hello\nWorld\n"); add(tarea, "Center"); // 中央に配置 Panel vbox = new Panel(); // ボタンを2個縦に並べる vbox.setLayout( new BorderLayout() ); add(vbox, "South"); // 下に配置 Button button1 = new Button("btn01"); vbox.add(button1, "North"); // vboxの上に配置 button1.addActionListener(this);// 押下を検出 Button button2 = new Button("close"); vbox.add(button2, "South"); // vboxの下に配置 button2.addActionListener(this);// 押下を検出 addWindowListener(this); //ウィンドウ関係のイベント検出 } // ActionListner関係のイベント public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); // イベント発生元が if( obj instanceof Button ) { // ボタンであれば Button btn = (Button)obj; String bname = btn.getLabel(); // 名前を取得 if(bname == "btn01"){ // tareaに追加 tarea.append( "Button Label is " + bname + "\n" ); } else { // 終了 System.exit(0); } } // System.exit(0); } // WindowListener関係のイベント // 使用しないイベントも記述しないとダメ public void windowClosing(WindowEvent e) { System.exit(0); } public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} }