< 筆記 > Java SE - 07 Java SE GUI

07 Java SE GUI

By Kevin Song

  • 07-01 GUI概述
  • 07-02 事件監聽

07-01 GUI概述

GUI

  • Graphical User Interface(圖形用戶接口)
  • 特點:
    • 更直觀

CLI

  • Command Line User Interface(命令行用戶接口)
  • 特點
    • 不直觀

Java爲GUI提供對象的兩個包

  • java.awt
    • Abstract Window Toolkit:抽象窗口工具包,調用本地系統方法實現功能
    • 重量級控件
  • javax.swing
    • 完全由Java實現,提供更多組件,移植性強
    • 輕量級控件

繼承關係

  • Component:組件
    • Container:容器
      • Window:窗體,可以獨立存在
        • Frame:框架
        • Dialog:對話框
          • FileDialog:文件對話框
      • Panel:面板,窗體中的一部分,不可以獨立存在
    • Button:按鈕
    • Label:標籤
    • Checkbox:複選框
    • TextComponent:文本組件
      • TextArea:文本區域
      • TextField:文本框

Container:爲容器,一個特殊組件,通過add方法添加其他組件

佈局

  • FlowLayout(流式佈局)
    • 從左到右順序排列
    • Panel默認的佈局
  • BorderLayout(邊界佈局)
    • 東南西北中
    • Frame默認的佈局
  • GridLayout(網格佈局)
    • 規則的矩陣
  • CardLayout(卡片佈局)
    • 選項卡
  • GridBagLayout(網絡包佈局)
    • 非規則的矩陣

Frame演示

public class FrameDemo {
    public static void main(String[] args) {
        Frame f = new Frame("my frame");

        //f.setSize(500, 400);
        //f.setLocation(400, 200);
        f.setBounds(400, 200, 500, 400);

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

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

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

07-02 事件監聽

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

監聽器

  • WindowListener
    • windowClosing() 關閉窗口
  • ActionListener
    • actionPerformed()
  • MouseListener
    • mouseEntered() 鼠標移到按鈕就觸發,不需要點擊
    • mouseClicked() 鼠標單擊觸發
  • KeyListener
    • keyPressed()

AWT

public class FrameDemo {
    public static void main(String[] args) {
        Frame f = new Frame("my frame");

        //f.setSize(500, 400);
        //f.setLocation(400, 200);
        f.setBounds(400, 200, 500, 400);
        f.setLayout(new FlowLayout());//設置流式佈局

        TextFiled tf = new TextField(35);
        Button but = new Button("一個按鈕");
        f.add(tf);
        f.add(but);
        //窗口上加一個監聽
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);//處理方式
                System.exit(0);
            }
        });
        //按鈕上加一個監聽
        buf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(Action e) {
                System.out.println("Run");
            }
        })
        //按鈕上加一個鼠標監聽
        buf.addMouseListener(new MouseListener() {
            /*
            @Override
            public void MouseEntered(MouseEvent e) {
               System.out.println("Run");//鼠標移到按鈕上就會觸發
            }
            */
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount()==2) {
                    tf.setText("double click"+count++);
                }
            }
        })
        //文本框添加鍵盤監聽
        tf.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                System.out.println("key run");

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

SWING

public class MySwing extends javax.swing.JFrame {
    private JButton jButton1;

    /**
    * Auto-generated main method to display this JFrame
    */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MySwing inst = new MySwing();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }

    public MySwing() {
        super();
        initGUI();
    }

    private void initGUI() {
        try {
            getContentPane().setLayout(null);
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            {
                jButton1 = new JButton();
                getContentPane().add(jButton1);
                jButton1.setText("\u9000\u51fa");
                jButton1.setBounds(142, 26, 103, 48);
                jButton1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jButton1ActionPerformed(evt);
                    }
                });
            }
            pack();
            setSize(400, 300);
        } catch (Exception e) {
            //add your error handling code here
            e.printStackTrace();
        }
    }

    private void jButton1ActionPerformed(ActionEvent evt) {
//      System.out.println("jButton1.actionPerformed, event="+evt);
        //TODO add your code for jButton1.actionPerformed

        System.exit(0);
    }

}

菜單練習

public class MyMenu extends javax.swing.JFrame {
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");
    private JMenuBar jMenuBar1;
    private JScrollPane jScrollPane1;
    private JMenuItem jMenuItem2;
    private JTextArea jTextArea1;
    private JMenuItem jMenuItem1;
    private JMenu jMenu1;
    private JFileChooser chooser;
    private JDialog dialog;

    /**
    * Auto-generated main method to display this JFrame
    */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyMenu inst = new MyMenu();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }

    public MyMenu() {
        super();
        initGUI();
    }

    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            {
                jScrollPane1 = new JScrollPane();
                getContentPane().add(jScrollPane1, BorderLayout.CENTER);
                {
                    jTextArea1 = new JTextArea();
                    jScrollPane1.setViewportView(jTextArea1);
                }
            }
            {
                jMenuBar1 = new JMenuBar();
                setJMenuBar(jMenuBar1);
                {
                    jMenu1 = new JMenu();
                    jMenuBar1.add(jMenu1);
                    jMenu1.setText("\u6587\u4ef6");
                    {
                        jMenuItem1 = new JMenuItem();
                        jMenu1.add(jMenuItem1);
                        jMenuItem1.setText("\u6253\u5f00");
                        jMenuItem1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    jMenuItem1ActionPerformed(evt);
                                } catch (IOException e) {

                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    {
                        jMenuItem2 = new JMenuItem();
                        jMenu1.add(jMenuItem2);
                        jMenuItem2.setText("\u4fdd\u5b58");
                        jMenuItem2.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    jMenuItem2ActionPerformed(evt);
                                } catch (IOException e) {

                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }
            pack();
            this.setSize(610, 402);
        } catch (Exception e) {
            //add your error handling code here
            e.printStackTrace();
        }
    }

    private void jMenuItem1ActionPerformed(ActionEvent evt) throws IOException {


        chooser = new JFileChooser();

//          FileNameExtensionFilter filter = new FileNameExtensionFilter(
//              "JPG & GIF Images", "jpg", "gif");
//          chooser.setFileFilter(filter);


        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == JFileChooser.CANCEL_OPTION){
            System.out.println("沒有選取文件,取消了");
            return;
        }

        File file = chooser.getSelectedFile();



        BufferedReader bufr = new BufferedReader(new FileReader(file));

        String line = null;
        while((line=bufr.readLine())!=null){
            jTextArea1.append(line+LINE_SEPARATOR);
        }

        bufr.close();

    }

    private void jMenuItem2ActionPerformed(ActionEvent evt) throws IOException {

        chooser = new JFileChooser();
        int returnVal = chooser.showSaveDialog(this);
        if(returnVal == JFileChooser.CANCEL_OPTION){
            System.out.println("沒有指定文件,取消了");
            return;
        }

        File file = chooser.getSelectedFile();

        String text = jTextArea1.getText();

        BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
        bufw.write(text);
        bufw.close();

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章