Java基礎 GUI圖形用戶界面 佈局 事件 簡易記事本 雙擊運行jar

GUI

繼承關係圖
- GUI
- Graphical User Interface(圖形用戶接口).
- 用圖形的方式,來顯示計算機操作的界面,這樣更方便更只管
- CLI
- Command line User Interface (命令行用戶接口)
- 就是常見的Dos命令行操作
- 需要記憶一些常用的命令,操作不只管
- 舉例:
- 比如:創建文件夾,或者刪除文件夾等
- Java爲GUI提供的對象都存在java.Awt 和 javax.Swing兩個包中

Awt 與 Swing
java.Awt:Abstract Window ToolKit(抽象窗口工具包),需要調用本地系統方法實現功能。屬重量級空間。
javax.Swing:在AWT的基礎上,建立的一套圖形界面系統,其中提供了更多的組建,而且完全由Java實現。增強了移植性,屬輕量級控件。

佈局管理器

  • 容器中的組建的排放方式,就是佈局
  • 常見的佈局管理器
    • FlowLayout(流式佈局管理器)
      • 從左到右的順序排列
      • Panel默認的佈局管理器
    • BorderLayout(邊界佈局管理器)
      • 東,南,西,北,中
      • Frame默認的佈局管理器。
    • GridLayout(網格佈局管理器)
      • 規則的矩陣
    • CardLayout(卡片佈局管理器)
      • 選項卡
    • GridBagLayout(網格包佈局管理器)
      • 非規則的矩陣

Frame

import java.awt.*;
class GuiDemo
{
    public static void main(String[] args)
    {
        Frame fm=new Frame("Title");
        fm.setSize(400,300);
        fm.setLocation(200,200);

        Button b1=new Button("登錄");
        Button b2=new Button("註冊");


        fm.setLayout(new FlowLayout());
        fm.add(b1);
        fm.add(b2);
        fm.setVisible(true);

    }
}

事件監聽機制

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

窗體事件

fm.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
            public void windowActivated(WindowEvent e)
            {
                System.out.println("windowActivated");
            }
            public void windowOpened(WindowEvent e)
            {
                System.out.println("windowOpened");
            }
        });

Action事件

import java.awt.*;
import java.awt.event.*;


class GuiDemo2
{
    private Frame f;
    private Button but;
    GuiDemo2()
    {
        init();
    }
    public void init()
    {
        f=new Frame("Frame");
        f.setBounds(300,100,600,500);
        f.setLayout(new FlowLayout());
        but=new Button("button");
        f.add(but);
        myEvent();
        f.setVisible(true);
    }
    private void myEvent()
    {
        f.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
        //給這個窗體添加一個退出按鈕
        but.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                System.out.println(e.toString());
            }
        });
    }
    public static void main(String[] args)
    {
        new GuiDemo2();
    }
}

鼠標事件

import java.awt.*;
import java.awt.event.*;
class GuiDemo3
{
    public static void main(String[] args)
    {
        Frame fm=new Frame("Frame");
        fm.setBounds(300,300,400,300);

        fm.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });

        Button bt1=new Button("hello");
        bt1.addMouseMotionListener(new MouseMotionAdapter()
        {
            public void mouseMoved(MouseEvent e)
            {
                Point pt1=e.getPoint();
                Point pt2=e.getLocationOnScreen();
                System.out.println("控件內部座標X:"+pt1.x+",Y:"+pt1.y);
                System.out.println("屏幕座標    X:"+pt2.x+",Y:"+pt2.y);
                //System.out.println(e.toString());
            }
            public void mouseDragged(MouseEvent e)
            {
                System.out.println("MouseDragged");
            }
        });
        bt1.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent e)
            {
                bt1.setLabel("mouseClicked");
                System.out.println("mouseClicked");
            }


            public void mouseEntered(MouseEvent e)
            {
                System.out.println("mouseEntered");
            }

            public void mouseExited(MouseEvent e)
            {
                System.out.println("mouseExited");
            }


            public void mousePressed(MouseEvent e)
            {
                System.out.println("mousePressed");
            }

            public void mouseReleased(MouseEvent e)
            {
                System.out.println("mouseReleased");
            }

        });

        fm.setLayout(new FlowLayout());
        fm.add(bt1);
        fm.setVisible(true);
    }
}

鍵盤事件

import java.awt.*;
import java.awt.event.*;
class GuiDemo4
{
    public static void main(String[] args)
    {
        Frame fm=new Frame("Frame");
        fm.setBounds(300,300,400,300);

        fm.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
        fm.setLayout(new FlowLayout());
        TextField tf1=new TextField(20);
        tf1.addKeyListener(new KeyAdapter()
        {
            public void keyPressed(KeyEvent e)//屏蔽按鍵,只允許使用數字和退格鍵
            {
                int code=e.getKeyCode();
                if(!((code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)||code==KeyEvent.VK_BACK_SPACE))
                {
                    //System.out.println(code);
                    e.consume();
                    //System.out.println("非法的");
                }
            }
        });
        Button bt1=new Button("登錄");
        bt1.addKeyListener(new KeyAdapter()
        {
            public void keyPressed(KeyEvent e)
            {
                //System.out.println(e.getKeyText(e.getKeyCode()));
                //System.out.println(e.getKeyChar()+" "+e.getKeyCode());
            }
        });
        fm.add(tf1);
        fm.add(bt1);

        fm.setVisible(true);
    }
}

文件查看器1.0

簡易文件查看器1.0

import java.awt.*;
import java.awt.event.*;
import java.io.File;
//
class FileMan
{
    private Frame fm;
    private TextField tf;
    private Button btn;
    private TextArea ta;
    private List fileList;
    private Choice rootCh;
    private File root;
    private Dialog dlg;
    FileMan()
    {
        init();
    }
    public void init()
    {
        fm=new Frame("Frame");

        fileList=new List();
        rootCh=new Choice();
        tf=new TextField();
        dlg=new Dialog(fm,"Error");

        fm.setBounds(300,100,400,600);
        dlg.setBounds(350,350,200,100);
        fm.setLayout(new BorderLayout());
        //fm.setLayout(null);


        //rootCh.setPreferredSize(new Dimension(100,40));
        //fileList.setPreferredSize(new Dimension(300,300));
        fm.add(rootCh,BorderLayout.NORTH);
        fm.add(fileList,BorderLayout.CENTER);
        fm.add(tf,BorderLayout.SOUTH);

        dlg.add(new Label("盤符打開失敗!"));
        for(File f:File.listRoots())
        {
            rootCh.add(f.getPath());
        }
        tf.setText(rootCh.getSelectedItem());
        showList(new File(tf.getText()).listFiles());
        myEvent();
        fm.setVisible(true);
    }
    public void showList(File[] flist)
    {
        if(flist==null)
            dlg.setVisible(true);
        for(int i=0;(flist!=null)&&(i<flist.length);i++)
        {

            fileList.add(flist[i].getName());

        }
    }
    public void myEvent()
    {
        fm.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
        });
        dlg.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e)
        {
            dlg.setVisible(false);
        }
        });
        rootCh.addItemListener(new ItemListener()
        {
            public void itemStateChanged(ItemEvent e)
            {

                String rootName=rootCh.getSelectedItem();
                tf.setText(rootName);
                fileList.removeAll();
                File[] flist=new File(rootName).listFiles();
                showList(flist);
            }
        });
        fileList.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent e)
            {
                String fileName=fileList.getSelectedItem();
                File dFile=new File(tf.getText()+File.separator+fileName);
                if(dFile.isDirectory())
                {
                    tf.setText(dFile.getPath());
                    fileList.removeAll();
                    showList(dFile.listFiles());
                }
            }
        });
    }

    public static void main(String[] args)
    {

        new FileMan();
        //gd.init();

    }
}

菜單

MenuBar 菜單欄
Menu 菜單
MenuItem 菜單項
菜單欄 包含 菜單
菜單 包含 菜單 或 菜單項

import java.awt.*;
import java.awt.event.*;
class MenuDemo
{
    private Frame f;
    private MenuBar mb;
    private Menu m,subMenu;
    private MenuItem closeItem,subItem;
    MenuDemo()
    {
        init();
    }

    public void init()
    {
        f=new Frame("Menu");
        f.setBounds(300,100,500,600);
        f.setLayout(new FlowLayout());

        mb=new MenuBar();
        m=new Menu("文件");
        subMenu=new Menu("子菜單");

        subItem=new MenuItem("子條目");
        closeItem=new MenuItem("退出");

        subMenu.add(subItem);
        m.add(subMenu);
        m.add(closeItem);

        //mb.add(subMenu);
        mb.add(m);

        f.setMenuBar(mb);

        myEvent();
        f.setVisible(true);

    }
    public void myEvent()
    {
        closeItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                //System.out.println(e.toString());
                System.exit(0);

            }
        });
        f.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
        });
    }
    public static void main(String[] args)
    {
        new MenuDemo();
    }
}

簡易記事本

這裏寫圖片描述

import java.awt.*;
import java.awt.event.*;
import java.io.*;
class MenuDemo
{
    private Frame fm;
    private MenuBar bar;
    private Menu fileMenu;
    private MenuItem openItem,closeItem,saveItem;
    private FileDialog openDialog,saveDialog;
    private TextArea ta;
    //打開的文件
    private File file;
    MenuDemo()
    {
        init();
    }
    //初始化
    public void init()
    {
        fm=new Frame("簡易文本編輯器");
        fm.setBounds(300,100,650,600);
        //創建文本編輯框
        ta=new TextArea();
        //創建菜單欄
        bar=new MenuBar();

        //創建菜單
        fileMenu=new Menu("文件");

        openItem=new MenuItem("打開");
        saveItem=new MenuItem("保存");
        closeItem=new MenuItem("退出");

        //添加菜單項
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(closeItem);

        //菜單欄添加菜單
        bar.add(fileMenu);
        //框架設置菜單欄
        fm.setMenuBar(bar);
        //框架添加文本框
        fm.add(ta);
        //創建文件對話框
        openDialog=new FileDialog(fm,"打開",FileDialog.LOAD);
        saveDialog=new FileDialog(fm,"保存",FileDialog.SAVE);
        //初始化事件監視器
        myEvent();
        //顯示框架
        fm.setVisible(true);

    }
    //打開文件顯示在文本框內
    public void openFile()
    {
        //System.out.println(path);

        String line=null;
        BufferedReader bufr=null;
        ta.setText("");
        try
        {
            bufr=new BufferedReader(new FileReader(file));
            line=bufr.readLine();
            while(line!=null)
            {
                ta.append(line+System.getProperty("line.separator"));
                line=bufr.readLine();
            }
        }
        catch(IOException e)
        {
            throw new RuntimeException("文件讀取失敗");
        }
        finally
        {
            if(bufr!=null)
            {
                try{
                    bufr.close();
                }
                catch(IOException e)
                {
                    throw new RuntimeException("文件關閉失敗");
                }
            }
        }
    }
    //保存文件到file對象
    public void saveFile()
    {


        String text=null;
        BufferedWriter bufw=null;
        try{
            bufw=new BufferedWriter(new FileWriter(file));
            text=ta.getText();
            bufw.write(text);
        }
        catch(IOException e)
        {
            throw new RuntimeException("寫入文件失敗");
        }
        finally
        {
            if(bufw!=null)
            {
                try{
                    bufw.close();
                }
                catch(IOException e)
                {
                    throw new RuntimeException("關閉文件失敗");
                }
            }
        }

    }
    //事件監聽器
    public void myEvent()
    {
        //打開菜單事件
        openItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                //System.out.println(e.toString());
                openDialog.setVisible(true);
                String dirPath=openDialog.getDirectory();
                String fileName=openDialog.getFile();


                if(dirPath!=null&&fileName!=null)
                {
                    file=new File(dirPath,fileName);
                    openFile();
                }
            }
        });
        //保存菜單事件
        saveItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                //System.out.println(e.toString());
                if(file==null)
                {
                    saveDialog.setVisible(true);
                    String dirPath=saveDialog.getDirectory();
                    String fileName=saveDialog.getFile();

                    if(dirPath!=null&&fileName!=null)
                        file=new File(dirPath,fileName);
                    else
                        return;
                }

                saveFile();
            }
        });
        //關閉菜單事件
        closeItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                //System.out.println(e.toString());
                System.exit(0);

            }
        });
        //窗口關閉事件
        fm.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
        });
    }
    public static void main(String[] args)
    {
        new MenuDemo();
    }
}

雙擊執行jar

1.java文件使用package指定包
2.主類使用 public 聲明
3.將java文件編譯
javac SimpleNotepad.java -d ./
4.編寫配置文件config.txt 內容爲

Main-Class: SimpleNotepad

注意,冒號’:’後必須加空格,行尾必須加回車!
5.使用jar -cvfm SimpleNotepad.jar config.txt ./包名 進行打包

6.雙擊執行jar包

jar格式在windows 7系統下執行配置方法
打開“控制面板\所有控制面板項\默認程序\設置關聯”
找到 .jar格式 點擊更改程序
選擇JDK中的 javaw.exe

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