2011年7月15日 星期五

~Java GUI~ AWT vs Swing

Frame、Panel、Dialog、InterFrame、Window、Applet 都是容器

通常有J開頭的,如JFrame、JDialog、JPanel、JInterFrame、JWindow、JApplet...等元件都是屬於 swing 類別
而沒有J開頭的,如Frame、Panel、Dialog、InterFrame、Window、Applet...等元件都是屬於 awt 類別


其中Applet、JApplet、swing與awt的繼承關係為:
java.awt.Panel <-- java.applet.Applet <-- javax.swing.JApple


通常一個GUI分為兩個部分:Container + Component

以swing為例,swing可以被實體化出來的:

容器(Container):
JFrame :General window
JDialog :Dialog window
JWindow :General window but dosen't have title and other basic component
JInterFrame :用來建立子視窗
JPanel :用來建立視窗中的面板
JApplet :瀏覽器使用的視窗化容器


元件(Component):
JButton
JMenuItem
JCheckbox
JRadioButton
JComboBox
JLabel
JList
JMenuBar
JPopupMenu
JScrollBar
JEditorPane
JTextArea
JTextField
JToolBar




*建立一個視窗最基本的幾行指令:
1. 實體化一個容器: JFrame myFrame = new JFrame("Title");
2. 設定視窗大小: myFrame.setSize(a,b);
3. 設定視窗是否顯示:myFrame.setVisible(true);
4. 設定當使用者關閉視窗,即結束程式:myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-------------至此可以建立一個什麼功用都沒有的視窗-------------
5. 加入元件到視窗中:
(1) JButton myButton = new JButton("Click");
(2) myFrame.getContentPane().add(myButton);
^^^^^^^^^^^^^^^^
swing 的物件需要先以這個方法得到一個物件,才能加入元件
awt 的物件則可以直接加入, myFrame.add(myButton);



*首先以AWT的陽春視窗做示範:

import java.awt.*;

import java.awt.event.*;  

public class testAWT 
{
    public static void main(String[] args)
    {
        Frame myFrame = new Frame("Title");
        
        myFrame.addWindowListener(new WindowAdapter()    
            { public void windowClosing(WindowEvent e)
              {    System.exit(0);    }    
            }
                                  );
                                 
        Button myButton = new Button("Click");
        
        myFrame.add(myButton);
        
        myFrame.setSize(250,250);
        myFrame.setVisible(true);
        


        
        
    }
}


/*
Because AWT does not have "setDefaultCloseOperation();" or such functions to exit the program when user click the exit button, you have to include the class "java.awt.event.*;" to implement windowListener to achieve the function.
*/

編譯出來會有兩個class,一個是 testAWT.class 和 testAWT$1.class
使用 java 執行的時候,不能夠只有其中一個class 這樣子會找不到main


執行結果如下:


(接下來是 Swing....continue)

2 則留言:

  1. The breaking of the financial institution does not deprive the banker of the best to proceed, provided that they've funds with which to replenish it, a lot as} the agreed minimum. We've sent you an e-mail with the information needed to 메리트카지노 reset your password. The e-mail may take a few minutes to succeed in your account. On that note, staying disciplined and never betting emotionally is what separates those who win consistently from those who win solely now and then.

    回覆刪除
  2. We have the Scientists at Wake Forest Institute for Regenerative Medicine Electric Can Openers to thank for that. After that, they coated it with precise cells taken from real patients. Surgeons have been capable of to} implant the newly fashioned tissue into patients.

    回覆刪除