GUI程式設計

Xiang6371發表於2020-12-28

GUI程式設計

GUI程式設計:圖形使用者介面程式設計

元件
  • 視窗
  • 彈窗
  • 皮膚
  • 文字框
  • 列表框
  • 按鈕
  • 圖片
  • 監聽事件
  • 滑鼠事件
  • 鍵盤事件
  • 外掛
  • 破解工具

1.簡介

GUI的核心開發技術:Swing(封裝過的,好看一些)、AWT (底層,難看)

GUI不流行的原因:1.介面不美觀

​ 2.需要jre環境 、

學習GUI的意義:是MVC的基礎,有助於瞭解MVC,瞭解監聽;可以寫一些自己的小工具;工作可能需要維護到swing介面(機率較小)

2.AWT

2.1AWT介紹

  1. 抽象的視窗工具,包含了很多的類和介面,用於GUI程式設計
  2. 元素:視窗,Annie,文字框
  3. java.awt包

在這裡插入圖片描述

2.2元件和容器

2.2.1 Frame

//GUI的第一個介面
public class TestFrame {
    public static void main(String[] args) {
        //Frame
        Frame frame = new Frame("我的第一個ava圖形介面視窗");

        //需要設定可見性
        frame.setVisible(true);
        //設定視窗大小
        frame.setSize(400,400);
        //設定背景顏色    需要color類
        frame.setBackground(Color.green);
        //彈出的初始位置,座標0,0點在框的左上角
        frame.setLocation(600,300);
        //設定大小固定,不可手動調節
        frame.setResizable(false);
        //此時出來的視窗,只有最小化按鈕有實際功能
    }
}

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-hYLkNsad-1609102299169)(C:\Xiang\圖片\1608988924(1)].jpg)

存在問題:視窗點右上角X關閉不了,只能停止程式執行或者工作管理員才能關閉

public class TestFrame2 {
    public static void main(String[] args) {
        //展示多個視窗 new
        MyFrame myFrame = new MyFrame(600, 300, 600, 400, Color.yellow);
        MyFrame myFrame2 = new MyFrame(700, 350, 600, 400, Color.green);
        MyFrame myFrame3 = new MyFrame(800, 400, 600, 400, Color.red);
        MyFrame myFrame4 = new MyFrame(900, 450, 600, 400, Color.darkGray);

    }
}

class MyFrame extends Frame{
    static int id=0;    //可能存在多個視窗,需要一個計數器

    //構造器
    public MyFrame(int x,int y,int w,int h,Color color){
        super("Myframe"+(++id));
        setVisible(true);
        setBackground(color);
        setBounds(x,y,w,h);//x,y是初始位置座標,w,h是視窗寬高

    }
}

2.2.2 皮膚

程式碼末尾加入監聽事件,解決了視窗關閉問題

//Panel 可以看成是一個空間,但不能單獨存在
public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        //佈局的概念
        Panel panel = new Panel();

        //設定佈局null,關掉預設的佈局
        frame.setLayout(null);

        //座標
        frame.setBounds(600,400,400,300);
        frame.setBackground(new Color(179,206,105));
        //此處不知道顏色怎麼選是,先隨便寫一組三個數字,然後左邊會出來一個顏色框,點進去手動調顏色即可

        //panel設定座標,相對於frame(皮膚座標是相對座標)            在frame的核心視窗裡面設定皮膚區域
        panel.setBounds(50,50,300,200);
        panel.setBackground(new Color(206,106,122));

        //frame.add(panel)  往視窗裡面新增皮膚
        frame.add(panel);

        frame.setVisible(true);     //設定可見性

        //監聽事件:監聽視窗關閉事件     System.exit(0)  -----------------------設定關閉功能,點選X可以關掉視窗--------------
        //介面卡模式:
        frame.addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
}

2.2.3 佈局管理器

  • 流式佈局(從左到右)(預設)
  • 東西南北中(上下佈局)
  • 表格佈局
//流式佈局
public class TestFlowLayout {
    public static void main(String[] args) {
        Frame frame = new Frame();
        //Panel panel = new Panel();

        //元件-按鈕元件
        Button button1 = new Button("按鈕1");
        Button button2 = new Button("按鈕2");
        Button button3 = new Button("按鈕3");

        //設定為流式佈局
        frame.setLayout(new FlowLayout());//預設為中
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));     //靠左佈置
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));     //靠右佈置
        frame.setSize(400,200);
        //frame.add(panel.add(button1));
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);

        frame.setVisible(true);
    }
}
//東西南北中(上下佈局)
public class TestBorderLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestBorderLayout");

        Button east = new Button("East");
        Button west = new Button("West");
        Button south = new Button("South");
        Button north = new Button("North");
        Button center = new Button("Center");

        frame.add(east,BorderLayout.EAST);
        frame.add(west,BorderLayout.WEST);
        frame.add(south,BorderLayout.SOUTH);
        frame.add(north,BorderLayout.NORTH);
        frame.add(center,BorderLayout.CENTER);

        frame.setSize(400,300);
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
}
//表格佈局
public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("TestGridLayout");

        Button btn1 = new Button("btn1");
        Button btn2 = new Button("btn2");
        Button btn3 = new Button("btn3");
        Button btn4 = new Button("btn4");
        Button btn5 = new Button("btn5");
        Button btn6 = new Button("btn6");

        frame.setLayout(new GridLayout(3,2));

        frame.add(btn1);
        frame.add(btn2);
        frame.add(btn3);
        frame.add(btn4);
        frame.add(btn5);
        frame.add(btn6);

        //frame.pack();//Java函式,會自動選擇一個最優的位置佈局,自動調整視窗大小,可自己選擇是否使用
        frame.setSize(400,300);
        frame.setVisible(true); //設定可見

        frame.addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
}

在這裡插入圖片描述

//聯絡,建立如下視窗
//思路:橙色p1,綠色p2,藍色p3,紅色p4;p1,p2以2行1列表格佈局加進視窗(整個框);p1,p3分別以東西南北中佈局包含p3,p4在中間(CENTER)位置
//p1,p3再分別東西插倆按鈕;p3表格佈局2行1列插倆按鈕;p4表格佈局2行2列插倆按鈕
//視窗含p1,p2;p1含p3;p2含p4;各自再含按鈕
public class MyTest {
    public static void main(String[] args) {
        //總視窗frame
        Frame frame = new Frame();
        frame.setVisible(true); //設定可見
        frame.setSize(400,400);
        frame.setLocation(600,400);
        frame.setBackground(new Color(147,176,86));
        frame.setLayout(new GridLayout(2,1));       
        //setLayout 設定佈局,此處設定為表格佈局,兩行一列;  //不指定時預設為流式佈局  FlowLayout  
                                                        
        //四個皮膚
        Panel p1 = new Panel(new BorderLayout());           //BorderLayout 東西南北中佈局
        Panel p2 = new Panel(new GridLayout(2,1));      //GridLayout  表格佈局
        Panel p3 = new Panel(new BorderLayout());
        Panel p4 = new Panel(new GridLayout(2,2));

        p1.add(new Button("East-1"),BorderLayout.EAST);				
        p1.add(new Button("West-1"),BorderLayout.WEST);

        p2.add(new Button("p2-btn-1"));
        p2.add(new Button("p2-btn-2"));

        p1.add(p2,BorderLayout.CENTER);

        p3.add(new Button("East-2"),BorderLayout.EAST);
        p3.add(new Button("West-2"),BorderLayout.WEST);

        p4.add(new Button("p4-btn-1"));
        p4.add(new Button("p4-btn-2"));
        p4.add(new Button("p4-btn-3"));
        p4.add(new Button("p4-btn-4"));

        p3.add(p4,BorderLayout.CENTER);

        frame.add(p1);
        frame.add(p3);
        
        frame.addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
}

總結:

  • Frame是一個頂級視窗
  • Panel(皮膚)無法單獨顯示,必須新增到某個容器中(frame中或其他panel中)
  • 佈局管理器
    • 流式
    • 東西南北中
    • 表格
  • 大小,定位,背景顏色,可見性,監聽

2.2.4 事件監聽

事件監聽:當某個事情發生的時候,做出什麼相應的操作,一般會跟按鈕配合使用

//案例,按下一個按鈕會自動做出某些操作    事件監聽
public class TestActionEvent {
    public static void main(String[] args) {
        //按下按鈕,觸發一些事件
        Frame frame = new Frame();
        Button button = new Button();
        Button button2 = new Button();
        frame.setLocation(300,500);
        frame.setLayout(new GridLayout(2,1));
        //因為addActionListener()需要一個ActionListener-事件監聽器,所以我們需要構造一個ActionListener
        MyActionListener myActionListener = new MyActionListener();
        button.addActionListener(myActionListener);         //給按鈕新增事件

        button2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                System.out.println("這還是一個沒鳥用的按鈕");        //自己建立的事件,輸出一段話
            }
        });

        frame.add(button);
        frame.add(button2);

        frame.setVisible(true);
        frame.pack();
        windowClose(frame);				//關閉視窗
    }
    //將關閉窗體的事件抽成一個方法
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
}

class MyActionListener implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        System.out.println("你按下了一個沒有屁用的按鈕");        //自己建立的事件,輸出一段話
    }
}

多個按鈕,共享一個事件

public class TestActionTwo {
    public static void main(String[] args) {
        //兩個按鈕實現同一個監聽
        Frame frame = new Frame("開始-停止");
        Button button1 = new Button("start");
        Button button2 = new Button("stop");
        frame.setLocation(240,600);

        MyMonitor myMonitor = new MyMonitor();

        //可以顯式地定義觸發事件會返回的命令,如果不定義,會走預設的值
        //可以多個按鈕只寫一個監聽類
        button1.setActionCommand("button1-start");

        button1.addActionListener(myMonitor);
        button2.addActionListener(myMonitor);

        frame.add(button1,BorderLayout.NORTH);
        frame.add(button2,BorderLayout.SOUTH);

        windowClose(frame);
        frame.pack();
        frame.setVisible(true);

    }
    //將關閉窗體的事件抽成一個方法
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
}

class MyMonitor implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        //e.getActionCommand()獲得按鈕資訊
        System.out.println("按鈕被點選了:+msg---"+e.getActionCommand());
    }
}

2.2.5 輸入框TextField 監聽事件

public class TestText01 {
    public static void main(String[] args) {
        //在main方法裡面不放其他,只放啟動程式的功能
        new MyFrame();
    }
}

class MyFrame extends Frame{
     public MyFrame(){
         TextField textField = new TextField();
         add(textField);

         //監聽這個文字框輸入的文字
         MyActionListener2 myActionListener2 = new MyActionListener2();
         //按下enter 就會觸發這個輸入框的時間
         textField.addActionListener(myActionListener2);

         //設定替換字元編碼
         textField.setEchoChar('*');//此時就是在文字框輸入一些文字,在文字框中會輸出*,但列印在控制檯的依然是輸入的內容
         setVisible(true);
         addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                 System.exit(0);
             }
         });
     }
}

class MyActionListener2 implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        //e.getSource();      //獲得一些資源,返回的是一個物件Object,可以向下轉型
        TextField field = (TextField)e.getSource();
        System.out.println(field.getText());    //獲得輸入框中的文字
        field.setText("");  //設定回車以後,輸入的文字會清空(設定為""空字串)
    }
}

2.2.6 簡易計算器(包含組合,內部類相關知識)

oop原則:組合大於繼承

內部類:更好的包裝;內部類最大的好處,就是可以暢通無阻地訪問外部類的屬性與方法

//寫一個簡易計算器  未調優
public class TestCalc {
    public static void main(String[] args) {
        new Calculator();
    }
}

//計算器類
class Calculator extends Frame{
    public Calculator() {
        //3個文字框 兩個輸入值,一個輸出值
        TextField num1 = new TextField(10);//字元數最多為10
        TextField num2 = new TextField(10);
        TextField num3 = new TextField(11);
        //1個按鈕  =  按下去開始計算並輸出結果
        Button button = new Button("=");
        button.addActionListener(new MyCalculatorListener(num1,num2,num3));  //給button加監聽事件

        //一個標籤  +  沒有任何操作,僅表示一個符號(相當於做一些文字性的提示)
        Label label = new Label("+");

        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

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

//監聽器類
class MyCalculatorListener implements ActionListener{
    //獲取3個變數
    private TextField num1,num2,num3;

    public MyCalculatorListener(TextField num1,TextField num2,TextField num3) {
        this.num1=num1;
        this.num2=num2;
        this.num3=num3;
    }

    public void actionPerformed(ActionEvent e) {
        //1.獲得加數和被加數
        int n1=Integer.parseInt(num1.getText());
        int n2=Integer.parseInt(num2.getText());

        //2.將這個值加法運算後,放到第三個框
        num3.setText(""+(n1+n2));

        //3.清除前兩個框
        num1.setText("");
        num2.setText("");
    }
}
//寫一個簡易計算器  組合優化後的程式碼
public class TestCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

//計算器類
class Calculator extends Frame{
    //屬性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
        //元件
        num1 = new TextField(10);//字元數最多為10
        num2 = new TextField(10);
        num3 = new TextField(11);
        Button button = new Button("=");
        Label label = new Label("+");

        //監聽器
        button.addActionListener(new MyCalculatorListener(this));  //給button加監聽事件

        //佈局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

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

//監聽器類
class MyCalculatorListener implements ActionListener{
    //獲取計算器物件,在一個類中組合另外一個類
    Calculator calculator=null;

    public MyCalculatorListener(Calculator calculator) {
        this.calculator=calculator;
    }

    public void actionPerformed(ActionEvent e) {
        //1.獲得加數和被加數
        //2.將這個值加法運算後,放到第三個框
        //3.清除前兩個框
        int n1=Integer.parseInt(calculator.num1.getText());
        int n2=Integer.parseInt(calculator.num2.getText());
        calculator.num3.setText(""+(n1+n2));
        calculator.num1.setText("");
        calculator.num2.setText("");
    }
}
//寫一個簡易計算器			內部類優化   內部類最大的好處,就是可以暢通無阻地訪問外部類的方法與屬性
public class TestCalc {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

//計算器類
class Calculator extends Frame{
    //屬性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
        //元件
        num1 = new TextField(10);//字元數最多為10
        num2 = new TextField(10);
        num3 = new TextField(11);
        Button button = new Button("=");
        Label label = new Label("+");

        //監聽器
        button.addActionListener(new MyCalculatorListener());  //給button加監聽事件

        //佈局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    //監聽器類
    private class MyCalculatorListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //1.獲得加數和被加數
            //2.將這個值加法運算後,放到第三個框
            //3.清除前兩個框
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            num3.setText("" + (n1 + n2));
            num1.setText("");
            num2.setText("");
        }
    }
}

2.2.7 畫筆

public class TestPaint {
    public static void main(String[] args) {
        new MyPaint().loadFrame();
    }
}

class MyPaint extends Frame{
    public void loadFrame(){
        setBounds(600,400,600,500);
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    //畫筆
    @Override
    public void paint(Graphics g) {
        //畫筆需要顏色,可以畫畫
        //g.setColor(Color.red);
        //g.drawOval(200,200,100,200);//畫空心圓   前兩個數是圓心座標相對視窗,後兩個是橫向與縱向軸長
        g.fillOval(400,300,100,100);//畫實心圓

        //g.setColor(Color.green);
        g.fillRect(100,100,200,110); //畫矩形

        //養成習慣:畫筆用完,將它還原到最初的顏色
    }
}

2.2.8 滑鼠監聽MouseListener

目的:想要實現滑鼠畫畫

//測試滑鼠監聽事件
public class TestMouseListener {
    public static void main(String[] args) {
        new MyFrame("畫圖");
    }
}

class MyFrame extends Frame{
    //畫畫需要畫筆,需要監聽滑鼠當前的位置,需要集合來儲存這個點
    ArrayList points;
    public MyFrame(String title){
        super(title);
        setBounds(600,400,400,300);
        //存滑鼠點選的點
        points =new ArrayList<Object>();
        //滑鼠監聽器,針對這個視窗
        this.addMouseListener(new MyMouseListener());
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            //點選視窗關閉的時候需要做的事情
            public void windowClosing(WindowEvent e) {
                //結束程式
                System.exit(0);
            }
        });
    }
    @Override
    public void paint(Graphics g) {
        //畫畫需要監聽滑鼠事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point =(Point)iterator.next();
            g.setColor(Color.blue);
            g.fillOval(point.x,point.y,10,10);
        }
    }

    //新增一個點到介面上
    public void addPoint(Point point){
        points.add(point);
    }
    
    //介面卡模式
    private class MyMouseListener extends MouseAdapter{
        //滑鼠 按下,彈起,長按
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame = (MyFrame)e.getSource();
            //這裡我們點選的時候就會在介面上產生一個點
            //這個點就是滑鼠的點
            frame.addPoint(new Point(e.getX(),e.getY()));
            //每次點選滑鼠都需要重新畫一遍
            frame.repaint();//重新整理
        }
    }
}

2.2.9 視窗監聽 WindowListener

public class TestWindow {
    public static void main(String[] args) {
        new WindowFrame();
    }
}

class WindowFrame extends Frame {
    public WindowFrame() {
        setBackground(Color.BLUE);
        setBounds(600, 400, 200, 200);
        setVisible(true);
        //addWindowListener(new MyWindowListenter());

        this.addWindowListener(new WindowAdapter() {//使用匿名內部類
            @Override
            //關閉視窗
            public void windowClosing(WindowEvent e) {
                System.out.println("你點選了關閉");
                setVisible(false);//隱藏視窗,可以通過按鈕隱藏視窗
                System.exit(0);//正常退出  0變成1就是非正常退出          //現在這兩句就是先隱藏,然後再關閉
            }

            @Override
            //啟用視窗  滑鼠點到別的專案離開這個視窗以後,再次點進這個視窗,視窗變高亮時就是啟用
            public void windowActivated(WindowEvent e) {
                System.out.println("windowActivated");
            }
        });
    }
}

2.2.10 鍵盤監聽

public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame(){
        setBounds(600,400,300,400);
        setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            @Override//鍵盤按下
            public void keyPressed(KeyEvent e) {
                //獲得鍵盤按下的鍵是哪一個,當前鍵盤的碼
                int keyCode = e.getKeyCode();
                System.out.println(keyCode);    //數出按到的每個鍵對應的碼(對應的是不同的數字)
                //不用記這個值,直接使用其靜態屬性即可 VK_XXX
                if(keyCode==KeyEvent.VK_UP){        //鍵盤上的 ↑ 按鍵
                    System.out.println("你按下了上鍵");
                }
                //根據按下不同的操作,產生不同的結果
            }
        });
    }
}

## 3 Swing

3.1 視窗、皮膚

public class JFrameDemo {
    //Init() 初始化
    public void init(){
        //頂級視窗 JFrame
        JFrame jf = new JFrame("這是一個JFrame視窗");
        jf.setVisible(true);
        jf.setBounds(600,400,200,200);
        jf.setBackground(Color.blue);//此處設定藍色,並不會有任何顯示(設定的是視窗顏色,但之後展示的是標籤,標籤會把視窗填充滿,只能看到標籤的顏色

        //設定文字  JLable
        JLabel label = new JLabel("這是一個練手的標籤");
        jf.add(label);
        
        //關閉事件      JFrame中已經將關閉視窗寫成了方法,直接呼叫即可
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        //建立一個視窗
        new JFrameDemo().init();
    }
}

//讓標籤居中

public class JFrameDemo02 {
    public static void main(String[] args) {
        new MyJFrame2().init();
    }
}

class MyJFrame2 extends JFrame {
    public void init(){	//這個init方法相當於構造器方法
        this.setBounds(600,400,200,200);
        this.setVisible(true);

        JLabel label = new JLabel("這是一個練手的標籤");
        this.add(label);

        //讓標籤文字居中
        label.setHorizontalAlignment(SwingConstants.CENTER);

        //獲得一個容器   JFrame視窗放東西,需要容器,使用getContentPane()方法
        Container container = this.getContentPane();
        container.setBackground(Color.green);
    }
}

3.2 彈窗

JDialog 用來被彈出,預設就有關閉事件

//主視窗
public class DialogDemo extends JFrame {
    public static void main(String[] args) {
        new DialogDemo();
    }

        public DialogDemo(){		//此處是構造器,功能與前面示例中init()方法一樣
            this.setVisible(true);
            this.setSize(400,300);
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//關閉視窗   //繼承JFrame後,此三行程式碼可以認為是建視窗的預設程式碼

            //JFrame  放東西,需要容器,使用getContentPane()方法
            Container container = this.getContentPane();

            //絕對佈局   使用絕對不覺後,元件輸入座標,都是按頂級視窗的座標來定位的
            container.setLayout(null);

            //按鈕
            JButton button = new JButton("點選彈出對話方塊");    //建立物件
            button.setBounds(30,30,200,50);

            //點選這個按鈕的時候,彈出一個彈窗
            //監聽事件
            button.addActionListener(new ActionListener() {//監聽器
                public void actionPerformed(ActionEvent e) {
                    //彈窗
                     new MyDialogDemo();
                }
            });
            container.add(button);
        }
}

//彈窗的視窗
class MyDialogDemo extends JDialog{		//JDialog 彈窗類
    public MyDialogDemo() {
        this.setVisible(true);
        this.setBounds(100,100,300,240);

        //this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // 彈窗本身已包含關閉事件(彈窗本來就可以關閉),不用再手動新增,新增後會報異常

        Container container = this.getContentPane();
        container.setLayout(null);
        container.add(new Label("這是一個彈窗"));
    }
}

3.3 標籤

Jlabel

new Jlabel("xxx");

圖示 ICON ,是一個介面,是標籤的進階

//圖示是一個介面,需要實現類,實現類還需要繼承JFrame
public class IconDemo extends JFrame implements Icon {
    public static void main(String[] args) {
        new IconDemo().init();
    }
    
    private int width;
    private int heigth;
    public IconDemo(){ }    //無參構造
    public IconDemo(int width,int heigth){
        this.width=width;
        this.heigth=heigth;
    }

    public void init(){
        IconDemo iconDemo = new IconDemo(15, 15);
        //此處圖示放在標籤上,也可以放在按鈕上
        JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);

        Container container = getContentPane();
        container.add(label);

        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    //重寫介面中的方法
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,heigth);       //重寫方法話一個圓,xy圓心,後面寬高
    }

    public int getIconWidth() {
        return this.width;
    }

    public int getIconHeight() {
        return this.heigth;
    }
}
public class ImageIconDemo extends JFrame {
    public static void main(String[] args) {
        new ImageIconDemo();
    }

    public ImageIconDemo(){
        //獲取圖片的地址
        JLabel label = new JLabel("果果");
        URL url = ImageIconDemo.class.getResource("guoguo.jpg");
        //獲取該類統計資源中guoguo.jpg所在的路徑,返回一個url路徑地址  利用反射

        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(600,400,200,200);
    }
}

3.4 皮膚

Jpanel

public class JPanelDemo extends JFrame {
    public static void main(String[] args) {
        new JPanelDemo();
    }

    public JPanelDemo(){
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,20));
        //GridLayout 表格佈局  ,2行1列,後面兩個引數10,20意思是間距			途中可以看到皮膚與皮膚間,行間距20,列間距10

        JPanel panel1 = new JPanel(new GridLayout(1,3));
        JPanel panel2 = new JPanel(new GridLayout(1,2));
        JPanel panel3 = new JPanel(new GridLayout(2,1));
        JPanel panel4 = new JPanel(new GridLayout(3,2));

        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));

        panel2.add(new JButton("2"));
        panel2.add(new JButton("2"));

        panel3.add(new JButton("3"));
        panel3.add(new JButton("3"));

        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        
        container.add(panel1);
        container.add(panel2);
        container.add(panel3);
        container.add(panel4);

        setVisible(true);
        this.setSize(500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

JScrollPanel 滾動皮膚

public class JScrollDemo extends JFrame {
    public static void main(String[] args) {
        new JScrollDemo();
    }
    public JScrollDemo(){
        Container container = this.getContentPane();

        //文字域  可以換行
        JTextArea textArea = new JTextArea(20,50); //最多20行,每行最多50個字元
        //噹噹前頁面總行列不超過設定的20,50時,不會出現滾動條;當前頁面較小時才會有滾動條出現
        textArea.setText("滾動皮膚示例");//設定預設文字

        //Scroll皮膚   文字域放在公洞皮膚中,滾動皮膚再放進容器裡
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

        this.setVisible(true);
        this.setBounds(600,400,400,300);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.5 按鈕

//圖片按鈕
public class JButtonDemo01 extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo01();
    }

    public JButtonDemo01(){
        Container container = this.getContentPane();
        URL url = JButtonDemo01.class.getResource("guoguo.jpg");
        Icon icon = new ImageIcon(url);     //以上這兩句程式碼,將一個圖片變成一個圖示

        //把這個圖示放在按鈕上
        JButton button = new JButton();
        button.setIcon(icon);
        button.setToolTipText("圖片按鈕");      //滑鼠懸浮上去的時候會有一個圖片按鈕提示
        //把按鈕加到容器中
        container.add(button);

        setVisible(true);
        setSize(500,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 單選按鈕
//單選按鈕
public class JButtonDemo02 extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo02();
    }

    public JButtonDemo02(){
        Container container = this.getContentPane();
        //單選框
        JRadioButton radioButton01 = new JRadioButton("iRadioButton01");
        JRadioButton radioButton02 = new JRadioButton("iRadioButton02");
        JRadioButton radioButton03 = new JRadioButton("iRadioButton03");
        //由於單選框只能選擇一個,所以將這3個單選框分成一個組;一個組中只能選擇一個
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton01);
        group.add(radioButton02);
        group.add(radioButton03);           //將此處分組的四句程式碼去掉,三個按鈕就能同時選上

        container.add(radioButton01,BorderLayout.NORTH);
        container.add(radioButton02,BorderLayout.CENTER);
        container.add(radioButton03,BorderLayout.SOUTH);

        setVisible(true);
        setSize(500,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 核取按鈕
//多選按鈕
public class JButtonDemo03 extends JFrame {
    public static void main(String[] args) {
        new JButtonDemo03();
    }

    public JButtonDemo03(){
        Container container = this.getContentPane();
        //單選框
        JRadioButton radioButton01 = new JRadioButton("iRadioButton01");
        JRadioButton radioButton02 = new JRadioButton("iRadioButton02");
        JRadioButton radioButton03 = new JRadioButton("iRadioButton03");

        //多選框        可以選擇多個選項,打鉤
        JCheckBox checkBox01 = new JCheckBox("checkBox01");
        JCheckBox checkBox02 = new JCheckBox("checkBox02");
        JCheckBox checkBox03 = new JCheckBox("checkBox03");
        
        container.add(checkBox01,BorderLayout.NORTH);
        container.add(checkBox02,BorderLayout.CENTER);
        container.add(checkBox03,BorderLayout.SOUTH);

        setVisible(true);
        setSize(500,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

3.6 列表

  • 下拉框
public class TestComboboxDemo01 extends JFrame {
    public static void main(String[] args) {
        new TestComboboxDemo01();
    }
    public TestComboboxDemo01(){
        Container container = this.getContentPane();

        JComboBox status = new JComboBox();

        status.addItem(null);
        status.addItem("正在熱映");
        status.addItem("已下架");
        status.addItem("即將上映");

        container.add(status);

        setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 列表框
public class TestComboboxDemo02 extends JFrame {
    public static void main(String[] args) {
        new TestComboboxDemo02();
    }
    public TestComboboxDemo02(){
        Container container = this.getContentPane();

        //生成列表的內容
        //String[] contents={"列表1","列表2","列表3"};		新增靜態的資料
        Vector contents = new Vector();			//新增動態的資料

        //列表中需要放入內容
        JList jList = new JList(contents);

        contents.add("列表1");
        contents.add("列表2");
        contents.add("列表3");

        container.add(jList);

        setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 應用場景
    • 下拉框:選擇地區或一些單個選項
    • 列表:展示資訊,一般是動態擴容的

3.8 文字框

  • 文字框
public class TestTextDemo01 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo01();
    }
    public TestTextDemo01(){
        Container container = this.getContentPane();

        JTextField textField = new JTextField("hello");
        JTextField textField2 = new JTextField("world",20);

        container.add(textField,BorderLayout.NORTH);
        container.add(textField2,BorderLayout.SOUTH);

        setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 密碼域
public class TestTextDemo02 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo02();
    }
    public TestTextDemo02(){
        Container container = this.getContentPane();

        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');

        container.add(passwordField);     //輸入的內容在皮膚裡面會自動顯示為***
        
        setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  • 文字域
//文字域,一般配合皮膚使用
public class TestTextDemo03 extends JFrame {
    public static void main(String[] args) {
        new TestTextDemo03();
    }
    public TestTextDemo03(){
        Container container = this.getContentPane();

        //文字域  可以換行
        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("文字框示例");
        //Scroll皮膚   文字域放在滾動皮膚中,滾動皮膚再放進容器裡
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);

        setVisible(true);
        this.setSize(500,350);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

相關文章