主頁 > 後端開發 > Java GUI編程

Java GUI編程

2020-10-28 06:06:31 後端開發

簡介

是什么?怎么玩?如何運用?

組件

  • 視窗

  • 彈窗

  • 面板

  • 文本框

  • 串列框

  • 圖片

  • 按鈕

  • 監聽事件

  • 滑鼠

  • 鍵盤

GUI核心技術:AWT 、Swing

缺點:界面不美觀,需要jre環境!

優點:MVC架構,了解監聽

目標:計網課設需要弄個Web服務器小工具

軟體測驗課設需要弄個正交表生成小工具

曾經為了方便,上學期用了pygame和pyqt5,如今又回來補Java的GUI了

AWT

介紹

awt: 抽象視窗工具包 (Abstract Window Toolkit )

提供很多類和介面,GUI

元素:視窗、按鈕、文本框等

java.awt

image-20200413110932111

兩個思路,

  1. ctrl + 左鍵 看原始碼,提高英語能力
  2. 物件加點 慢慢看方法

組件和容器

Frame

實體
import java.awt.*;

public class Main {

    public static void main(String[] args) {
        Frame frame = new Frame("第一個視窗");
        frame.setSize(300,300);//視窗大小
        frame.setBackground(Color.blue);//背景顏色
        frame.setLocation(300,100);//出現時左上角在螢屏上的坐標
        //new Color(180, 167,0); //顏色點進去看原始碼
        frame.setResizable(true);//是否可改變表單大小

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

image-20200413114654988

出現問題:視窗關不掉!得回到IDE手動停止程式

封裝

將上面的簡單視窗封裝成自己的類

封裝類

import java.awt.*;

public class MyFrame extends Frame {
    private static int id = 0; //用于統計視窗
    public  MyFrame(int x, int y, int w, int h,Color color){
        super("Frame"+(++id));
        setBackground(color);
        setBounds(x,y,w,h);
        setVisible(true);
    }

}

主方法呼叫

import java.awt.*;

public class TestFrame {
    public static void main(String[] args) {
        MyFrame myFrame1 = new MyFrame(300,100,300,300,Color.red);
        MyFrame myFrame2 = new MyFrame(600,100,300,300,Color.yellow);
        MyFrame myFrame3 = new MyFrame(300,400,300,300,Color.blue);
        MyFrame myFrame4 = new MyFrame(600,400,300,300,Color.green);

    }
}

image-20200413120107256

面板Panel

package com.ljh;

import javafx.scene.layout.Pane;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame();
        Panel panel = new Panel();
        //設定布局
        frame.setLayout(null); //少了這行frame就會置頂,覆寫其他元素
        frame.setBounds(300,100,300,300);
        frame.setBackground(Color.red);

        //設定面板
        panel.setBackground(Color.cyan);
        panel.setBounds(100,100,200,200);

        //視窗添加面板
        frame.add(panel);

        frame.setVisible(true);

        //監聽關閉事件,通過視窗監聽配接器重寫關閉方法
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

image-20200413141810897

布局管理器

流式布局
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestFlowLayout {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setSize(400,400);

        //設定流式布局
        //frame.setLayout(new FlowLayout());//默認居中
        //frame.setLayout(new FlowLayout(FlowLayout.LEFT));//靠左
        frame.setLayout(new FlowLayout(FlowLayout.RIGHT));//靠右

        //組件 按鈕
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");

        //添加按鈕
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);

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

image-20200413143256299

東西南北中(邊界布局)

image-20200413143234547

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestBorderLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("東西南北中");
        frame.setBounds(300,200,400,400);
        //按鈕組
        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.setVisible(true);

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

image-20200413144140737

表格布局
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestGridLayout {
    public static void main(String[] args) {
        Frame frame = new Frame("東西南北中");
        frame.setBounds(300,200,400,400);

        //設定表格布局
        frame.setLayout(new GridLayout(2,2));

        //組件 按鈕
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");

        //添加按鈕
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);

        frame.setVisible(true);

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

image-20200413144745980

作業Demo

通過前面學習的知識,實作下圖布局

image-20200413152003983

分析:

首先Frame用表格布局(GridLayout)分成上半部panel1和下半部panel2,

上下兩半分別用左中右布局(BorderLayout),

上部分的中央panel3用表格布局(GridLayout)兩行一列

下部分的中央panel4用表格布局(GridLayout)兩行兩列

代碼

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class LayoutWork {
    public static void main(String[] args) {
        Frame frame = new Frame("作業1");
        frame.setBounds(300,200,600,400);

        Panel panel1 = new Panel();//上半邊
        Panel panel2 = new Panel();//下半邊
        Panel panel3 = new Panel();//上中央
        Panel panel4 = new Panel();//下中央

        //設定表格布局
        frame.setLayout(new GridLayout(2,1));
        panel1.setLayout(new BorderLayout());
        panel2.setLayout(new BorderLayout());
        panel3.setLayout(new GridLayout(2,1));
        panel4.setLayout(new GridLayout(2,2));

        //組件 按鈕
        Button button0 = new Button("button0");
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");
        Button button7 = new Button("button7");
        Button button8 = new Button("button8");
        Button button9 = new Button("button9");

        //自頂向下添加
        frame.add(panel1);
        frame.add(panel2);
        panel1.add(button1,BorderLayout.WEST);
        panel1.add(panel3,BorderLayout.CENTER);
        panel1.add(button4,BorderLayout.EAST);
        panel3.add(button2);
        panel3.add(button3);
        panel2.add(button5,BorderLayout.WEST);
        panel2.add(panel4,BorderLayout.CENTER);
        panel4.add(button6);
        panel4.add(button7);
        panel4.add(button8);
        panel4.add(button9);
        panel2.add(button0,BorderLayout.EAST);


        frame.setVisible(true);

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

布局總結:

  1. Frame是頂級視窗
  2. Panel無法單獨顯示,必須加到某容器中
  3. 布局管理器:流式 邊界 表格
  4. 大小,定位,背景顏色,可見性,監聽關閉事件

事件監聽

當某件事情發生的時候,干什么?

addActionListener(事件);

package com.action;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestButton {
    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setBounds(300,200,300,200);
        frame.setVisible(true);
        Button button1 = new Button("button");
        button1.addActionListener(new myActionListener());

        frame.add(button1);
        windowClose(frame);

    }

    //關閉視窗事件
    private static void windowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                System.exit(0);
            }
        });
    }

}
// 事件監聽實作類
class myActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("點擊");
    }
}

監聽輸入框

新思想,在main函式里面只有呼叫啟動的陳述句,不寫其他東西,

package com.action;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestActionEvet {
    public static void main(String[] args) {
        new MyFrame();
    }
}

class MyFrame extends Frame{
    public MyFrame(){
        TextField textField = new TextField(5);
        textField.setEchoChar('*');//密碼型別隱藏顯示
        this.add(textField);
        textField.addActionListener(new MyActionListener());
        this.setVisible(true);
        this.pack();
        WindowClose(this);
    }

    //  關閉表單事件
    public static void WindowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

//事件監聽類
class MyActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField textField = (TextField) e.getSource();//e.getSource是個Object物件
        System.out.println(textField.getText());
        textField.setText("");//獲取文本框內容并設定為空
    }
}


簡易計算器

用過傳參的代碼

package com.action;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 計算器類1 開始是通過傳參是形式,傳給事件監聽類操控文本框,
 */
public class Calculate1 extends Frame {
    TextField num1, num2, num3;

    public Calculate1() {
        //創建自己,一個表單
        //3個文本框
        num1 = new TextField();
        num2 = new TextField();
        num3 = new TextField();
        Button button = new Button("=");

        setLayout(new FlowLayout());
        add(num1);
        add(new Label("+"));
        add(num2);
        add(button);
        add(num3);

        button.addActionListener(new MyCalculate1Listener(num1, num2, num3));
        pack();
        setVisible(true);
        WindowClose(this);

    }

    //  關閉表單事件
    public static void WindowClose(Frame frame) {
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyCalculate1Listener implements ActionListener {
    private TextField num1, num2, num3;

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

    @Override
    public void actionPerformed(ActionEvent e) {
        int n1 = Integer.parseInt(num1.getText());
        int n2 = Integer.parseInt(num2.getText());
        num3.setText("" + (n1 + n2));
    }
}


通過組合的方式 (面向物件)

package com.action;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 計算器類2 通過組合的方式,傳給事件監聽類一個實體化的圖形類,可以直接操作它的屬性
 */
public class Calculate2 extends Frame { 
    public TextField num1,num2,num3;

    public void loadFrame(){
        //3個文本框
        num1 = new TextField();
        num2 = new TextField();
        num3 = new TextField();
        Button button = new Button("=");

        setLayout(new FlowLayout());
        add(num1);
        add( new Label("+")) ;
        add(num2);
        add(button);
        add(num3);

        button.addActionListener(new MyCalculate2Listener1(this));
        pack();
        setVisible(true);
        WindowClose(this);

    }
    //  關閉表單事件
    public static void WindowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

class MyCalculate2Listener1 implements ActionListener {
    private Calculate2 cal;//組合!!把別的類丟進來用
    public MyCalculate2Listener1(Calculate2 cal){
        this.cal = cal;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int n1 = Integer.parseInt(cal.num1.getText());
        int n2 = Integer.parseInt(cal.num2.getText());
        cal.num3.setText(""+(n1+n2));
    }
}

內部類的方式

  • 更好的封裝
  • 最大的好處,可以取到外部類的屬性和方法!
package com.action;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Calculate3  extends Frame {
    public TextField num1,num2,num3;

    public void loadFrame(){
        //3個文本框
        num1 = new TextField();
        num2 = new TextField();
        num3 = new TextField();
        Button button = new Button("=");

        setLayout(new FlowLayout());
        add(num1);
        add( new Label("+")) ;
        add(num2);
        add(button);
        add(num3);

        button.addActionListener(new MyCalculate3Listener());
        pack();
        setVisible(true);
        WindowClose(this);

    }
    //  關閉表單事件
    public static void WindowClose(Frame frame){
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    //內部類可以隨便對外部類的屬性進行操作
    class MyCalculate3Listener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            num3.setText(""+(n1+n2));
        }
    }
}


畫筆paint

滑鼠監聽

image-20200426190258357

package com.paint;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

//實作滑鼠畫點
public class TestPaint {
    public static void main(String[] args) {
        new MyPaint("畫點");
    }

}
//我的畫筆類
class MyPaint extends Frame{
    private ArrayList points;
    public MyPaint(String title){
        super(title);
        this.setBounds(200,200,300,300);


        points = new ArrayList<>(); //存點集合
        //在視窗上監聽滑鼠事件
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                Frame frame = (Frame)e.getSource();
                points.add(new Point(e.getX(), e.getY())) ;
                frame.repaint();
            }
        });
        
        
        this.setVisible(true);
    }
    public void paint (Graphics g){
        Iterator iterator = points.iterator();
        while(iterator.hasNext())
        {
            Point drawPoint = (Point)iterator.next();
            //getGraphics().setColor(Color.black);
            g.fillOval(drawPoint.x,drawPoint.y,5,5);

        }
    }
}

視窗監聽

package com.action;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestWindow {
    public static void main(String[] args) {
    new WindowFrame();
    }
}
class WindowFrame extends Frame{
    public WindowFrame(){
        this.setBounds(200,200,500,500);
        this.addWindowListener(
            //匿名內部類
            new WindowAdapter() {
                @Override
                public void windowOpened(WindowEvent e) {
                    System.out.println("視窗打開");
                }

                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("視窗正在關閉");
                    System.exit(0);
                }

                @Override
                public void windowClosed(WindowEvent e) {
                    System.out.println("視窗已經關閉");
                }

                @Override
                public void windowIconified(WindowEvent e) {
                    System.out.println("最小化");
                }

                @Override
                public void windowDeiconified(WindowEvent e) {
                    System.out.println("從最小化出現");
                }

                @Override
                public void windowActivated(WindowEvent e) {
                    System.out.println("視窗激活");
                    WindowFrame frame = (WindowFrame) e.getSource();
                    frame.setTitle("您回來啦");
                }

                @Override
                public void windowDeactivated(WindowEvent e) {
                    System.out.println("視窗離開");
                    WindowFrame frame = (WindowFrame) e.getSource();
                    frame.setTitle("你快回來!");
                }

                @Override
                public void windowStateChanged(WindowEvent e) {
                    System.out.println("狀態改變");
                }

                @Override
                public void windowGainedFocus(WindowEvent e) {
                    super.windowGainedFocus(e);
                }

                @Override
                public void windowLostFocus(WindowEvent e) {
                    System.out.println("視窗失去焦點");
                }
            });
        setVisible(true);
    }
}

鍵盤監聽

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TestKeyListener {
    public static void main(String[] args) {
        new KeyFrame();
    }
}
class KeyFrame extends Frame{
    public KeyFrame(){
        this.setBounds(200,200,200,200);
        this.setVisible(true);

        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                // 獲取對應字符的ASCII值
                System.out.println(e.getKeyCode());
                if (e.getKeyCode() == KeyEvent.VK_UP){
                    System.out.println("按下了方向上鍵");
                }
            }
        });
    }
}

Swing

視窗

package Swing;

import javax.swing.*;
import java.awt.*;

public class JFrameDemo {

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

class MyJFrame extends JFrame {
    public void init() {
        this.setTitle("Swing");
        this.setLayout(new FlowLayout());
        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setBackground(Color.cyan);
//        Container contentPane = this.getContentPane();
//        contentPane.setBackground(Color.cyan);

        JPanel jPanel = new JPanel();
        // 流式布局時根據內容變化大小
        jPanel.setBounds(50, 50, 100, 100);
        jPanel.setBackground(Color.yellow);
        
       
        JLabel jLabel = new JLabel();
        jLabel.setText("hello world");
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        
        this.add(jPanel);
        jPanel.add(jLabel);

        // Swing已經寫好了默認關閉視窗的方法!
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

在swing中的容器和awt不一樣,導致這里的this.setBackground(Color.red);不生效,

image-20200514095909377

應該先獲取一個容器,再給容器設定背景顏色,

this.setBackground(Color.red);
改成:
Container contentPane = this.getContentPane();
contentPane.setBackground(Color.red);

image-20200514095945019

面板

package swing;

import javax.swing.*;
import java.awt.*;

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

    public void init() {
        Container container = this.getContentPane();
        // 大容器裝兩行兩列的面板,之間有間距,
        container.setLayout(new GridLayout(2,2,10,10));

        JPanel jPanel1 = new JPanel(new GridLayout(1,2));
        JPanel jPanel2 = new JPanel(new GridLayout(2,1));
        JPanel jPanel3 = new JPanel(new GridLayout(2,2));
        JPanel jPanel4 = new JPanel(new GridLayout(1,1));

        jPanel1.add(new Button("1"));
        jPanel1.add(new Button("1"));
        jPanel2.add(new Button("2"));
        jPanel2.add(new Button("2"));
        jPanel3.add(new Button("3"));
        jPanel3.add(new Button("3"));
        jPanel3.add(new Button("3"));
        jPanel3.add(new Button("3"));
        jPanel4.add(new Button("4"));

        container.add(jPanel1);
        container.add(jPanel2);
        container.add(jPanel3);
        container.add(jPanel4);

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

image-20200514153540599

JScroll面板

package swing;

import javax.swing.*;
import java.awt.*;

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

    public void init() {
        Container container = this.getContentPane();

        JTextArea textArea = new JTextArea(20,50);
        textArea.setText("當內容過多時會常出現滾動條");

        // JScroll
        JScrollPane scrollPane = new JScrollPane(textArea);
		// 調整區域
        // scrollPane.setSize(100,100);

        container.add(scrollPane);

        this.setTitle("滾動");
        this.setBounds(100, 100, 500, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}


image-20200514154816038

彈窗

默認就帶有關閉事件,

package Swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

    public DialogDemo() {
        this.setVisible(true);
        this.setBounds(200, 200, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        // JFrame容器,放東西
        Container container = this.getContentPane();
        // 絕對布局
        container.setLayout(null);
        JButton button = new JButton("點擊彈窗");
        // 用坐標定位組件的位置
        button.setBounds(30,30,100,100);

        container.add(button);

        // 點擊按鈕時彈出另個視窗
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 跳出彈窗
                new MyDialog("標題","列印訊息");
            }
        });
    }
}


class MyDialog extends JDialog {
    // 彈窗自帶關閉事件
    public MyDialog(String title, String msg) {
        this.setTitle(title);
        this.setVisible(true);
        this.setBounds(350,350,200,200);

        JLabel label = new JLabel(msg);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = this.getContentPane();
        container.add(label);
    }
}

image-20200514105113583

標簽

標簽中放圖示

package Swing;

import javax.swing.*;
import java.awt.*;

public class IconDemo extends JFrame implements Icon {
    private int width;
    private int height;

    public static void main(String[] args) {
        new IconDemo(15, 15);
    }

    public IconDemo() {}
    public IconDemo(int width,int height) {
        this.width = width;
        this.height = height;

        this.setTitle("圖示icon");
        this.setVisible(true);
        this.setBounds(100,100,300,300);
        // 圖示放在標簽上,也可以放到按鈕上~
        JLabel label = new JLabel("icon", this, SwingConstants.CENTER);
        JButton jButton = new JButton("icon", this);
        Container container = this.getContentPane();
        container.add(label);
        // container.add(jButton);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.fillOval(x,y,width,height);
    }

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

    @Override
    public int getIconHeight() {
        return this.height;
    }
}


image-20200514151416469

標簽中放圖片

package swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;

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

    public void init() {
        this.setTitle("圖片標簽");
        this.setVisible(true);
        this.setBounds(100, 100, 500, 500);

        JLabel jLabel = new JLabel();
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);

        // 先加入標簽再設定圖片圖示
        Container container = this.getContentPane();
        container.add(jLabel);

        // 通過源代碼檔案的目錄獲取路徑
        URL url = ImageIconTest.class.getResource("white.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        System.out.println(imageIcon);
        jLabel.setIcon(imageIcon);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        // 創建圖片物件做左上角圖示icon
        Image image = null;
        try {
            image = ImageIO.read(url);
            this.setIconImage(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


image-20200514151906698

按鈕

圖片按鈕

package swing;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class JbuttonDemo01 extends JFrame {
    public static void main(String[] args) {
        new JbuttonDemo01().init();

    }

    public void init() {
        Container container = this.getContentPane();
        // 將一張圖片轉成圖示
        URL url = JbuttonDemo01.class.getResource("white.jpg");
        Icon icon = new ImageIcon(url);

        // 把圖示放在按鈕上
        JButton jButton = new JButton(icon);
        container.add(jButton);
        jButton.setToolTipText("這里可以提示文字");


        this.setTitle("圖片按鈕");
        this.setBounds(100,100,500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}


image-20200514165350915

復選框

package swing;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

/**
 * 復選框,JCheckBox
 */
public class JbuttonDemo02 extends JFrame {
    public static void main(String[] args) {
        new JbuttonDemo02().init();

    }

    public void init() {
        Container container = this.getContentPane();
        container.setLayout(new FlowLayout());

        container.add(new JLabel("請選擇你喜歡的水果,可以選多個,"));
        JCheckBox checkBox1 = new JCheckBox("葡萄");
        JCheckBox checkBox2= new JCheckBox("草莓");
        JCheckBox checkBox3 = new JCheckBox("芒果");

        container.add(checkBox1);
        container.add(checkBox2);
        container.add(checkBox3);

        this.setTitle("復選框");
        this.setBounds(100,100,500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

image-20200514171936995

單選框

package swing;

import javax.swing.*;
import java.awt.*;

/**
 * 單選框,多選一
 * JRadioButton 圓點選區
 * 將多個復選加到一個組中ButtonGroup
 */
public class JbuttonDemo03 extends JFrame {
    public static void main(String[] args) {
        new JbuttonDemo03().init();

    }

    public void init() {
        Container container = this.getContentPane();
        container.setLayout(new FlowLayout());

        container.add(new JLabel("你所屬的年級是"));
        JRadioButton jRadioButton1 = new JRadioButton("大一");
        JRadioButton jRadioButton2 = new JRadioButton("大二");
        JRadioButton jRadioButton3 = new JRadioButton("大三");
        JRadioButton jRadioButton4 = new JRadioButton("大四");

        // 由于單選框只能選擇一個,分組
        // 一個組只能選一個
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(jRadioButton1);
        buttonGroup.add(jRadioButton2);
        buttonGroup.add(jRadioButton3);
        buttonGroup.add(jRadioButton4);

        container.add(jRadioButton1);
        container.add(jRadioButton2);
        container.add(jRadioButton3);
        container.add(jRadioButton4);

        this.setTitle("多選一");
        this.setBounds(100, 100, 500, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

}

image-20200514171848866

串列

下拉框

package swing;

import javax.swing.*;
import java.awt.*;

/**
 * 下拉框 JComboBox
 */
public class JcomboxDemo extends JFrame {
    public static void main(String[] args) {
        new JcomboxDemo().init();
    }
    public void init() {
        this.setTitle("下拉框");
        JPanel jPanel = new JPanel();
        jPanel.setBounds(50,50,100,100);


        JComboBox status = new JComboBox();
        status.addItem("大英");
        status.addItem("高數");
        status.addItem("大物");

        jPanel.add(status);
        Container container = this.getContentPane();
        container.add(jPanel);



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


image-20200515000556914

串列框

package swing;

import javax.swing.*;
import java.awt.*;

/**
 * 串列框可以自動遍歷陣列內容
 * JList
 */
public class JListDemo extends JFrame{
    public static void main(String[] args) {
        new JListDemo().init();
    }
    public void init() {
        this.setTitle("串列框");
        
        // 生成串列內容
        String[] contents = {"成員1", "成員2", "成員3"};
        // 將串列內容添加到串列框
        JList list = new JList(contents);
        
        Container container = this.getContentPane();
        container.add(list);
        this.setBounds(100,100,500,500);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}


image-20200515001215123

應用場景

  • 選擇地區,或一些單個選項
  • 串列展示資訊,一般是動態擴容~

文本框

package swing;

import javax.swing.*;
import java.awt.*;

/**
 * 文本框 JTextField
 * 密碼框 JPasswordField
 * 文本域 JTextArea
 */
public class TextDemo extends JFrame {
    public static void main(String[] args) {
        new TextDemo().init();
    }
    public void init(){
        this.setTitle("文本");
        Container container = this.getContentPane();
        container.setLayout(null);
        JTextField jTextField = new JTextField("文本框");
        jTextField.setBounds(50,50,100,20);
        // 密碼框
        JPasswordField jPasswordField = new JPasswordField();
        jPasswordField.setBounds(50, 200, 100, 20);
        // 也可以手動設定
        // jPasswordField.setEchoChar('+');

        JTextArea jTextArea = new JTextArea();
        jTextArea.setBounds(50, 300, 100, 80);

        container.add(jTextField);
        container.add(jPasswordField);
        container.add(jTextArea);

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


image-20200515100531281

表單自適應

package swing;

import javax.swing.*;
import java.awt.*;

/**
 * 通過當前螢屏顯示合適大小的表單
 */
public class WindowSize {
    public static void main(String[] args) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int screenWidth = (int) screenSize.getWidth();
        int screenHeight = (int) screenSize.getHeight();
        System.out.println("螢屏寬度:" + screenWidth + ",螢屏高度:" + screenHeight);

        // 表單與螢屏占比
        double percent = 0.5;
        int frameWidth = (int) (screenWidth * percent);
        int frameHeight = (int) (screenHeight * percent);
        System.out.println("表單寬度:" + frameWidth + ",表單高度:" + frameHeight);


        int x = (screenWidth - frameWidth) / 2;
        int y = (screenHeight - frameHeight) / 2;
        System.out.println("相對坐標x:" + x + ",y:" + y);

        JFrame jFrame = new JFrame();
        jFrame.setVisible(true);
        jFrame.setBounds(x,y,frameWidth,frameHeight);
    }


}


學習鏈接

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/194748.html

標籤:Java

上一篇:如何把7個集合劃分為2組有交集的集合?

下一篇:Spring Cloud認知學習(三):宣告式呼叫Feign的使用

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more