< 笔记 > Java SE

来源:互联网 发布:学乐器的软件 编辑:程序博客网 时间:2024/05/29 09:39

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();    }}
原创粉丝点击