Java GUI

java GUI

Date: Feb. 15th, 2017
Author: xianghtml

依據畢向東老師的授課, 我組織了本文內容.java

Graphical User Interface
Java的GUI部件在java.awt(抽象窗口工具包,需調用本地系統方法實現功能,重量級組件,不一樣系統窗口的樣子不一樣)和javax.swing(基於awt,不一樣系統,組件的樣子都同樣,輕量級控件,移植性更強)兩個包中。
基本組件繼承關係:瀏覽器

Component (在awt裏)
    |--Button
    |--Label  
    |--Checkbox 複選框
    |--TextComponent 文本部件  
        |--TextArea  內容(文本區域)
        |--TextField 標題(文本框)
    |--Container  容器
        |--Panel  面板(窗體的一部分,不能獨立存在)
        |--Window 窗體(能獨立存在)
            |--Frame  框架
            |--Dialog 對話框(噹噹彈出來的)
                |--FileDialog(文件選取對話框)

Layout 佈局

容器中組件的排放方式,是佈局app

  • FlowLayout 流式佈局
    • 左到右
    • Panel的默認佈局
  • BorderLayout 邊界佈局
    • 東南西北中
    • Frame的默認佈局
  • GradeLayout 網格佈局
  • CardLayout 卡片佈局(選項卡)
  • GridBagLayout 網格包佈局

e.g.框架

public class FrameDemo {
    public static void main(String[] args) {
        // 1. 建立窗體 最初不可見的Frame對象
        Frame f = new Frame("My frame");

        //f.setSize(500, 400);  //橫軸,縱軸     
        //f.setLocation(400, 150); // 窗體出現的位置

        // 2. 設置各類邊界,位置,佈局
        f.setBounds(400, 200, 500, 400); //表明上面兩句       

        f.setLayout(new FlowLayout()); //設置流式佈局

        // 3. 建立並添加組件
        Button but = new Button("一個按鈕");

        f.add(but); // 大按鈕,Frame對象默認"BorderLayout"

        // 4. 設置可見
        f.setVisible(true);
        System.out.println("over");
    }
}

事件監聽機制

  • 事件源(組件)
  • 事件(Event)
  • 監聽器(Listener)
  • 事件處理(引起事件後處理方式)

主人公: 小強 <-------------保鏢 保護小強,主管小強 拳打(被拳打){} 腳踢(被腳踢){踢回}
事兒: 被揍(拳打,腳踢)eclipse

拳頭(外力),打小強,被揍事發生在小強身上。ide

事件源: 小強
事件: 事情兒,有些事兒在小強身上沒法發生
監聽器: 保鏢, 可能保護多人, 發生了被打的事,應傳到保鏢這
處理方式: 拳打(被拳打){擋住} 腳踢(被腳踢){踢回}工具

窗體監聽

CAUSION: 窗體監聽 addWindowListener()佈局

public class FrameDemo {
    public static void main(String[] args) {
        Frame f = new Frame("My frame");
        f.setBounds(400, 200, 500, 400);
        f.setLayout(new FlowLayout());

        Button but = new Button("一個按鈕");
        f.add(but);

        //CAUSION: addWindowListener() 窗體監聽
        // 請個啥樣的保鏢?
        f.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                // 這很像異常處理,catch(e){}自動接收try{}中引起的異常對象
                System.out.println("closing......" + e);
                System.exit(0); // 關窗體
            }
        });

        f.setVisible(true);
        System.out.println("over");
    }
}

按鈕監聽

CAUSION: 按鈕監聽 addActionListener()
在上述代碼,窗體監聽器後,添加以下代碼:
一般addXxxListener(new XxxListener(){{要覆蓋的方法}})ui

// 按鈕上加一個監聽。
but.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
});

鼠標監聽

CAUSION: 鼠標監聽 addMouseListener()

鼠標事件:按下,釋放,單擊,進入 或 離開
下面代碼提到的:

  • 按鈕同時有action和click兩種監聽,誰先被觸發? 答:click先觸發
  • 雙擊按鈕,這事件,代碼咋寫?
/**
 * 鼠標鍵盤監聽示例
 */
public class MouseAndKeyboardDemo {

    private Frame f;
    private TextField tf;
    private Button but;

    // alt shift s
    public MouseAndKeyboardDemo() {
        init();
    }

    private void init() {
        f = new Frame("演示鼠標和鍵盤監聽");
        f.setBounds(400, 200, 500, 400);
        f.setLayout(new FlowLayout());

        tf = new TextField(35);
        but = new Button("一個按鈕");
        f.add(tf);
        f.add(but);

        myEvent(); // 添加事件監聽

        f.setVisible(true);
    }

    private void myEvent() {

        // 給Frame對象添加 「關窗體監聽」
        f.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        // 實驗: 按鈕同時有action和click兩種監聽,誰先被觸發?
        // 答: click先被觸發
        // but.addActionListener(new ActionListener() {
        //
        // @Override
        // public void actionPerformed(ActionEvent e) {
        // System.out.println("action done");
        // }
        // });

        // 鼠標事件:按下,釋放,單擊,進入 或 離開
        // 要在 按鈕上添加一個鼠標監聽
        but.addMouseListener(new MouseAdapter() {

            private int count = 1;

            @Override
            public void mouseEntered(MouseEvent e) {
                // System.out.println("我進");
                // tf.setText("我進..." + this.count++);
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                // 雙擊按鈕, 這種事件,代碼咋寫
                if (e.getClickCount() == 2)
                    tf.setText("我點..." + this.count++);
                // System.out.println("click done"+count++);
            }

        });
    }

    public static void main(String[] args) {
        new MouseAndKeyboardDemo();
    }
}

鍵盤監聽

CAUSION: 鍵盤監聽 addKeyListener()
在上述代碼的myEvent()裏添加以下代碼:
下面代碼展現了:

  • 記錄鍵盤按鍵
  • 只識別鍵盤的數字,不認別的鍵,咋辦?
  • ctrl + enter 咋辦?
// 給文本框添加鍵盤監聽
// 1.肯定事件源
// 2.肯定事件和監聽器
// 3.肯定具體動做,並把要設定的內容寫入該動做所示的方法體

tf.addKeyListener(new KeyAdapter() {

  @Override
  public void keyPressed(KeyEvent e) {
    // 1. 記錄鍵盤按鍵
    // System.out.println("keyboard..."+e.getKeyChar()+"..."+e.getKeyCode());
    // 展現shift ^^
    // System.out.println("keyboard..." +
    // KeyEvent.getKeyText(e.getKeyCode()) + "..." +
    // e.getKeyCode());
    //
    // 2. 只認數字,不認別的鍵,咋辦?
    // int code = e.getKeyCode();
    // if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)){
    // System.out.println("必須是數字");
    // e.consume(); //不起做用
    // }

    // 3. ctrl + enter 咋辦??
    if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER) {
      System.out.println("enter run...");
    }
  }
});

向Eclipse安裝swing插件

http://jingyan.baidu.com/album/4853e1e57194641909f7269f.html?picindex=1
步驟:

  1. 查看本身的Eclipse版本: 點擊elcipse界面下拉菜單的 help->about eclipse
  2. 百度搜索 "windowbuilder", 進入第一個搜索結果
  3. 進入界面,點 "Download"
  4. 選對應版本,點"Link"
  5. 進入界面,複製瀏覽器地址欄中的地址
  6. 打開Eclipse-Help-Install new Software
  7. 將剛纔複製的地址粘貼到work with中。並選中下面的多個選項(不一樣Eclipse版本,選項個數不一樣,都選上)
  8. 點擊各類next, 「贊成」, finish (中間大約7分鐘安裝下載時間)
  9. 重啓動Eclipse
  10. 重啓以後在新建裏出現「WindowBuilder」說明安裝成功

小例子

e.g.:

public class JFrameDemo extends JFrame {
    private JPanel contentPane;
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrameDemo frame = new JFrameDemo();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public JFrameDemo() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        JButton button = new JButton("退出");
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.exit(0);
            }
        });
        contentPane.add(button);
    }
}

再來一個例子,實現c:\一回車

public class MyWindow extends JFrame {

    protected static final String LINE_SEPARATOR = System.getProperty("line.separator");
    private JPanel contentPane;
    private JTextField textField;
    private JTextArea textArea;
    private JButton btnNewButton;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyWindow frame = new MyWindow();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyWindow() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 597, 461);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(12, 23, 392, 21);
        contentPane.add(textField);
        textField.setColumns(10);
        textArea = new JTextArea();
        textArea.setBounds(12, 95, 573, 297);
        contentPane.add(textArea);

        btnNewButton = new JButton("轉到");
        btnNewButton.setBounds(439, 20, 107, 27);
        contentPane.add(btnNewButton);

        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {

                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    showDir();
                }
            }
        });

        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showDir();
            }
        });
    }

    protected void showDir() {
        /*
         * 經過點擊按鈕,獲取文本框中目錄, 將目錄中的內容顯示在文本區域中。
         */
        String dir_str = textField.getText();
        File dir = new File(dir_str);

        if (dir.exists() && dir.isDirectory()) {
            // textArea.setText("is directory");
            textArea.setText("");
            String[] names = dir.list();
            for (String name : names) {
                textArea.append(name + LINE_SEPARATOR);
            }
        }
    }
}

添加滾動條

針對上面代碼,刪掉Jpanl容器,取而代之的添加JScrollPane容器,在它上面添加JTextArea組件。以下:

public class MyWindow extends JFrame {

    protected static final String LINE_SEPARATOR = System.getProperty("line.separator");
    private JPanel contentPane;
    private JTextField textField;
    private JButton btnNewButton;
    private JTextArea textArea;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyWindow frame = new MyWindow();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public MyWindow() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 597, 461);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(12, 23, 392, 21);
        contentPane.add(textField);
        textField.setColumns(10);

        btnNewButton = new JButton("轉到");
        btnNewButton.setBounds(439, 20, 107, 27);
        contentPane.add(btnNewButton);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(12, 80, 534, 309);
        contentPane.add(scrollPane);

        textArea = new JTextArea();
        scrollPane.setViewportView(textArea);

        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {

                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    showDir();
                }
            }
        });

        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showDir();
            }
        });
    }

    protected void showDir() {
        /*
         * 經過點擊按鈕,獲取文本框中目錄, 將目錄中的內容顯示在文本區域中。
         */
        String dir_str = textField.getText();
        File dir = new File(dir_str);

        if (dir.exists() && dir.isDirectory()) {
            // textArea.setText("is directory");
            textArea.setText("");
            String[] names = dir.list();
            for (String name : names) {
                textArea.append(name + LINE_SEPARATOR);
            }
        }
    }
}

添加下拉菜單 Menu

  • JMenuBar
  • JMenuBar上添加JMenu
  • JMenu上添加JMenuItem

06 gui 14:04

相關文章
相關標籤/搜索