JAVA GUI

摘要:JAVA GUI

GUI
GUI:  Graphical User Interface(圖形使用者介面)。
用圖形的方式,來顯示電腦操作的介面
 
CLI:  Command line User Interface (命令列使用者介面)
就是常見的Dos命令列操作。
 
GUI提供的物件都存在java.Awt和javax.Swing兩個包中。
java.Awt:
Abstract Window ToolKit,需要調用本地系統(跨平台性差)方法實現功能。屬重量級控制項。
 
javax.Swing:
在AWT的基礎上,建立的一套圖形介面系統,其中提供了更多的元件,而且完全由Java實現。增強了移植性,屬輕量級控制項。
 
常見的佈局管理器:
FlowLayout流式佈局: 從左到右的順序排列,Panel默認的佈局管理器
BorderLayout邊界佈局: 東,南,西,北,中Frame默認的佈局管理器
GridLayout網格佈局: 規則的矩陣
CardLayout片佈局: 選項卡
GridBagLayout網格包佈局: 非規則的矩陣
 
Container常用子類:Window Panel(面板,不能單獨存在。)
Window常用子類:Frame Dialog
 
 
簡單的表單創建過程:
Frame f = new Frame(“my window”);
f.setLayout(new FlowLayout());
f.setSize(500,400);//設置表單大小
f.setLocation(300,200);//設置表單出現在螢幕的位置
f.setVisible(true);
 

public class Main {
    public static void main(String[] args) throws Exception{
        Frame f = new Frame("my awt");
        f.setLayout(new FlowLayout());
        f.setSize(500, 400);
        f.setLocation(300, 200);
        f.setVisible(true);
       
        Button btn = new Button("Buttib");
        f.add(btn);
    }
}
 
事件監聽機制組成
事件源(組件)awt或swing包中的圖形介面組件
事件(Event) 每一個事件都有自己特有的對應事件和共性事件
監聽器(Listener)將可以觸發某一個事件的動作都封裝到監聽器中
事件處理(引發事件後處理方式)
 
事件監聽機制
確定事件源(容器或元件)
通過事件源物件的addXXXListener()方法將偵聽器註冊到該事件源上。
該方法中接收XXXListener的子類物件,或者XXXListener的子類XXXAdapter的子類物件。
一般用匿名內部類來表示。
在覆蓋方法的時候,方法的參數一般是XXXEvent類型的變數接收。
事件觸發後會把事件打包成物件傳遞給該變數。(其中包括事件源對象。通過getSource()或者,getComponent()獲取。)
 
監聽關閉視窗採用windowAdapter

class MyWin extends WindowAdapter{
    public void windowClosing(WindowEvent e){
        System.exit(0);
    }
}
public class Main {
    public static void main(String[] args) throws Exception{
        Frame f = new Frame("my awt");
        f.setLayout(new FlowLayout());
        f.setSize(500, 400);
        f.setLocation(300, 200);
        f.setVisible(true);
       
        Button btn = new Button("Button");
        f.add(btn);
        f.addWindowListener(new MyWin());
    }
}

匿名改寫


public class Main {
    public static void main(String[] args) throws Exception{
        Frame f = new Frame("my awt");
        f.setLayout(new FlowLayout());
        f.setSize(500, 400);
        f.setLocation(300, 200);
        f.setVisible(true);
       
        Button btn = new Button("Button");
        f.add(btn);
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }
}

使用button關閉視窗


class FramDemo {
    private Frame f;
    private Button btn;
       
    FramDemo(){
        init();
    }
    public void init(){
        f = new Frame("my frame");
        f.setBounds(300, 100, 600, 500);
        f.setLayout(new FlowLayout());
       
        btn = new Button("my button");
        f.add(btn);
        myEvent();
        f.setVisible(true);//顯示視窗
    }
    private void myEvent(){
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        //加入按鈕具備退出功能,查閱button api了解其監聽,因其只有一個方法直接覆寫匿名方法
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }
}

滑鼠監聽


class MouseAndKeyEvent {
    private Frame f;
    private Button btn;
       
    MouseAndKeyEvent(){
        init();
    }
    public void init(){
        f = new Frame("my frame");
        f.setBounds(300, 100, 600, 500);
        f.setLayout(new FlowLayout());
       
        btn = new Button("my button");
        f.add(btn);
        myEvent();
        f.setVisible(true);//顯示視窗
    }
    private void myEvent(){
        //加入按鈕具備退出功能,查閱button api了解其監聽,因其只有一個方法直接覆寫匿名方法
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        btn.addMouseListener(new MouseAdapter(){
            private int clickCounter = 1;
            private int counter = 1;
            public void mouseEntered(MouseEvent e){
                System.out.println("滑鼠進入" + counter++);
            }
            public void mouseClicked(MouseEvent e){
                if(e.getClickCount() == 2)
                    System.out.println("雙擊動作" + clickCounter++);
            }
        });
    }
}

 

鍵盤監聽  組合鍵


class Hello{
    public static void main(String[] args){
        new MouseAndKeyEvent();
    }
}


class MouseAndKeyEvent {
    private Frame f;
    private Button btn;
           
    MouseAndKeyEvent(){
            init();
    }
    public void init(){
        f = new Frame("my frame");
        f.setBounds(300, 100, 600, 500);
        f.setLayout(new FlowLayout());
           
        btn = new Button("my button");
        f.add(btn);
        myEvent();
        f.setVisible(true);//顯示視窗
    }
    private void myEvent(){
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });    

        btn.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e){
                if(e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER){
                    System.out.println("ctrl + enter is run");
                }
                if(e.getKeyCode() == 27){
                    System.exit(0);
                }
                System.out.println(KeyEvent.getKeyText(e.getKeyChar()) + e.getKeyCode());
            }
        });
    }
}

加入點選按紐後填寫路徑 顯示目錄檔案


class MyWindowDemo{
    private Frame f;
    private TextField tf;
    private Button but;
    private TextArea ta;
   
    public MyWindowDemo() {
        init();
    }
    public void init(){
        f = new Frame("my window");
        f.setBounds(300, 100, 600, 500);
        f.setLayout(new FlowLayout());
       
        tf = new TextField(60);
        but = new Button("轉");
       
        ta = new TextArea(23, 70);
       
        f.add(tf);
        f.add(but);
        f.add(ta);
       
        myEvent();
        f.setVisible(true);
    }
    private void myEvent(){
        but.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String dirPath = tf.getText();
                File dir = new File(dirPath);
                if(dir.exists() && dir.isDirectory()){
                    ta.setText("");
                    String[] names = dir.list();
                    for(String name: names){
                        ta.append(name + "\r\n");
                    }
                }else{
                    ta.setText("");
                }
            }
        });
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }
}


class Hello{
    public static void main(String[] args){
        new MyWindowDemo();
    }
}

 

再修改


class MyWindowDemo{
    private Frame f;
    private TextField tf;
    private Button but;
    private TextArea ta;
    private Dialog d;
    private Label lab;
    private Button okBtu;
   
    public MyWindowDemo() {
        init();
    }
    public void init(){
        f = new Frame("my window");
        f.setBounds(300, 100, 600, 500);
        f.setLayout(new FlowLayout());
       
        tf = new TextField(60);
        but = new Button("轉");
        ta = new TextArea(23, 70);
        d = new Dialog(f, "提示訊息", true);
        d.setBounds(400, 200, 240, 150);
        d.setLayout(new FlowLayout());
        lab = new Label();
        okBtu = new Button("確定");
       
        d.add(lab);
        d.add(okBtu);
       
       
        f.add(tf);
        f.add(but);
        f.add(ta);
       
        myEvent();
        f.setVisible(true);
    }
    private void myEvent(){
        okBtu.addActionListener(new ActionListener (){
            public void actionPerformed(ActionEvent e){
                d.setVisible(false);
            }
        });
       
        but.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String dirPath = tf.getText();
                File dir = new File(dirPath);
                if(dir.exists() && dir.isDirectory()){
                    ta.setText("");
                    String[] names = dir.list();
                    for(String name: names){
                        ta.append(name + "\r\n");
                    }
                }else{
                    String info = "路徑錯誤: " +  dirPath + "請重新輸入";
                    lab.setText(info);
                    d.setVisible(true);
                }
            }
        });
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }
}


class Hello{
    public static void main(String[] args){
        new MyWindowDemo();
    }
}

 

選單功能 子選單


class MyMenuTest{
    private Frame f;
    private MenuBar mb;
    private Menu m, subMenu;
    private MenuItem closeItem, subItem;
   
    MyMenuTest(){
        init();
    }
    public void init(){
        f = new Frame("my window");
        f.setBounds(300, 100, 500, 600);
        f.setLayout(new FlowLayout());
       
        mb = new MenuBar();
        m = new Menu("文件");
       
        closeItem = new MenuItem("退出");
        subMenu = new Menu("子選單");
        subItem = new MenuItem("子條目");
       
        m.add(closeItem);
        m.add(subMenu);
        subMenu.add(subItem);
       
        mb.add(m);
        f.setMenuBar(mb);
        myEvent();
        f.setVisible(true);
    }
    private void myEvent(){
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        closeItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                System.exit(0);
            }
        });
    }
}
class Main{
    public static void main(String[] args){
        new MyMenuTest();
    }
}

 

開檔顯示內容


class MyMenuTest{
     private Frame f;
     private MenuBar bar;
     private TextArea ta;
     private Menu fileMenu;
     private MenuItem openItem, saveItem, closeItem;
     private FileDialog openDia, saveDia;
    
    
     public MyMenuTest() {
         init();
     }
     public void init(){
         f = new Frame("my window");
         f.setBounds(300, 100, 650, 600);
        
         bar = new MenuBar();
         ta = new TextArea();
         fileMenu = new Menu("文件");
         openItem = new MenuItem("打開");
         saveItem = new MenuItem("保存");
         closeItem = new MenuItem("退出");
        
         fileMenu.add(openItem);
         fileMenu.add(saveItem);
         fileMenu.add(closeItem);
        
         f.add(ta);
         bar.add(fileMenu);
         f.setMenuBar(bar);
        
         openDia = new FileDialog(f, "打開", FileDialog.LOAD);
         saveDia = new FileDialog(f, "儲存", FileDialog.SAVE);
        
         myEvent();
         f.setVisible(true);
        
     }
     private void myEvent(){
         openItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  openDia.setVisible(true);
                  String dirPath = openDia.getDirectory();
                  String fileName = openDia.getFile();
                 
                   if(dirPath == null || fileName == null){
                       return ;
                  }
                  ta.setText("");
                 
                  File file = new File(dirPath, fileName);
                  try{
                       BufferedReader bufr = new BufferedReader(new FileReader(file));
                       String line = null;
                      
                       while((line = bufr.readLine()) != null){
                           ta.append(line + "\r\n");
                       }
                       bufr.close();
                  }catch(IOException ex){
                       throw new RuntimeException("讀取失敗");
                  }
              }
         });
        
         closeItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(0);
              }
         });
        
         f.addWindowListener(new WindowAdapter(){
              public void windowClosing(WindowEvent e){
                  System.exit(0);
              }
         });
     }
}

class Main{
     public static void main(String[] args){
         new MyMenuTest();
     }
}

 

存檔功能(尚修改)


class MyMenuTest{
    private Frame f;
    private MenuBar bar;
    private TextArea ta;
    private Menu fileMenu;
    private MenuItem openItem, saveItem, closeItem;
    private FileDialog openDia, saveDia;
    private File file;
   
   
    public MyMenuTest() {
        init();
    }
    public void init(){
        f = new Frame("my window");
        f.setBounds(300, 100, 650, 600);
       
        bar = new MenuBar();
        ta = new TextArea();
        fileMenu = new Menu("文件");
        openItem = new MenuItem("打開");
        saveItem = new MenuItem("保存");
        closeItem = new MenuItem("退出");
       
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(closeItem);
       
        f.add(ta);
        bar.add(fileMenu);
        f.setMenuBar(bar);
       
        openDia = new FileDialog(f, "打開", FileDialog.LOAD);
        saveDia = new FileDialog(f, "儲存", FileDialog.SAVE);
       
        myEvent();
        f.setVisible(true);
       
    }
    private void myEvent(){
        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                openDia.setVisible(true);
                String dirPath = openDia.getDirectory();
                String fileName = openDia.getFile();
               
                if(dirPath == null || fileName == null){
                    return ;
                }
                ta.setText("");
               
                File file = new File(dirPath, fileName);
                try{
                    BufferedReader bufr = new BufferedReader(new FileReader(file));
                    String line = null;
                   
                    while((line = bufr.readLine()) != null){
                        ta.append(line + "\r\n");
                    }
                    bufr.close();
                }catch(IOException ex){
                    throw new RuntimeException("讀取失敗");
                }
            }
        });
       
        closeItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
       
        saveItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(file == null){
                    saveDia.setVisible(true);
                    String dirPath = saveDia.getDirectory();
                    String fileName = saveDia.getFile();
                    if(dirPath == null || fileName == null){
                        return ;
                    }
                    file = new File(dirPath, fileName);
                }
                try{
                    BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
                        String text = ta.getText();
                        bufw.write(text);
                        bufw.close();
                }catch(IOException ex){
                    throw new RuntimeException();
                }
            }
        });
       
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
    }
}

class Main{
    public static void main(String[] args){
        new MyMenuTest();
    }
}

 

雙擊執行:
編譯打包
javac  –d  c:\Test MyMenu MyMenuTest.java
 
作成jar包
jar  -cvf  my.jar  mymenutest
 
設定執行 刪除包中的MANIFEST.MF,在同位置下編寫txt(自定義)
ex: 123.txt
Main-Class:  package名.class名
 
再打jar包一次
jar  -cvf  my.jar  123.txt  mymenutest
就可以雙擊執行jar檔