JAVA GUI表單及控制項

來源:互聯網
上載者:User

標籤:表單顯示   swing   一個   private   catch   print   jframe   rac   ble   

Swing基本操作:

JAVA顯示一個帶按鈕的視窗:

 1 import java.awt.*; 2 import javax.swing.*; 3 import javax.swing.border.EmptyBorder; 4  5 public class FrameDemo extends JFrame { 6  7     /** 8      * 在這裡定義表單中需要用到的組件 9      */10     private JPanel contentPane;        //面板11     private JButton button;            //按鈕12 13     /**14      * 在主函數中建立Frame類執行個體15      * 啟動該應用。16      */17     public static void main(String[] args) {18         EventQueue.invokeLater(new Runnable() {19             public void run() {                           //啟動視窗20                 try {21                     FrameDemo frame = new FrameDemo();    //表單22                     frame.setVisible(true);               //設定表單可見23                 } catch (Exception e) {24                     e.printStackTrace();25                 }26             }27         });28     }29 30     /**31      * 在本類建構函式中對組件進行初始化32      * 建立表單。33      */34     public FrameDemo() {35         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  //關閉表單時結束本進程36         this.setBounds(100, 100, 450, 300);                    //設定表單大小位置37         contentPane = new JPanel();                            //建立面板38         contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));    //設定邊框39         contentPane.setLayout(new BorderLayout(0, 0));         //設定布局40         this.setContentPane(contentPane);                      //將面板添加到表單中41         42         button = new JButton("按鈕");                          //按鈕43         contentPane.add(button, BorderLayout.CENTER);          //將按鈕添加到面板contentPane中44     }45 46 }

 

執行結果:

其中,FrameDemo類繼承了Frame(表單)類,在主函數中被執行個體化為Frame對象frame,此時,預設的表單是不可見的,須對其進行如下操作:

frame.setVisible(true);                //設定表單可見

 (設定Visible屬性為true)

才能將表單顯示出來

另外,這段代碼很關鍵:

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//關閉表單時結束本進程

 如果沒有這行代碼,會出現點擊關閉按鈕後,表單雖然被銷毀,但是程式進程依然存在,浪費資源的問題。

JAVA GUI表單及控制項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.