Swing入門代碼示例

1.Swing的特點
原來的AWT組件來自於java.awt包,在不同的開發平臺上顯示的時候會表現出不同的風格,但是Swing開發的程序可以同一組件的風格,不依賴操作系統。

Swing是完全由Java編寫,是輕量級組件,不依賴操作系統

2.流動佈局管理器

package com.Adder;
 
import javax.swing.*;
import java.awt.*;
 
public class Flow_Layout  extends JFrame {
 
    public Flow_Layout(){
        setBounds(500,500,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setTitle("浮動佈局管理器窗體");
        Container container=getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));//給容器設置流佈局管理器,流佈局默認的是居中對齊,
        // 可以用參數LEFT\CENTER\RIGHT參數修改佈局
 
        for (int i=0;i<10;i++){
            container.add(new JButton("按鈕"+i));
            System.out.println("按鈕");
        }
 
        setVisible(true);
    }
 
    public static void main(String[] args) {
        new Flow_Layout();
    }
}

3.邊界佈局管理器

package com.Adder;
 
import javax.swing.*;
import java.awt.*;
 
/*
 *邊界佈局將容器分爲東西南北中五個部分
 * 注意:
 * 1.添加組件的時候要指定區域,否則默認添加在center區
 * 2.同一區域的組件會相互覆蓋
 *3.改變窗體的大小,窗體中的按鈕的大小隨之改變,佈滿整個窗體
 * */
public class Border_Layout extends JFrame {
 
    public Border_Layout(){
        this.setBounds(500,500,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
        Container container=getContentPane();
        container.setLayout(new BorderLayout());
 
        JButton button1=new JButton("按鈕1"),
                button2=new JButton("按鈕2"),
                button3=new JButton("按鈕3");
        button1.setBounds(100,100,100,100);
        container.add(button1,BorderLayout.CENTER);//設置按鈕額度佈局爲中部佈局
        container.add(button2,BorderLayout.EAST);
        container.add(button3,BorderLayout.WEST);
 
        this.setVisible(true);
    }
 
    public static void main(String[] args) {
        new Border_Layout();
    }
}

4.網格佈局管理器

package com.Adder;
 
 
import javax.swing.*;
import java.awt.*;
 
/*
* 兩種構造方式:1.new GridLayout(列、行);2.new GirdLayout(列,行,水平間距,垂直間距)
*組件的大小隨窗體大小改變
* 如果網格數小於組件數,就會自動優化佈局,將列擴大
* */
public class Grid_Layout  extends JFrame {
    public Grid_Layout(){
        this.setBounds(500,500,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container container=getContentPane();
        container.setLayout(new GridLayout(7,3,5,5));//設置爲網格佈局,7行3列,水平間距5像素,垂直間距5像素
 
        for (int i=0;i<20;i++){
            container.add(new JButton("按鈕"+i));
        }
 
 
        this.setVisible(true);
    }
 
    public static void main(String[] args) {
        new Grid_Layout();
    }
}

5.網格組佈局管理器

GridBagConstraints常用屬性:
在這裏插入圖片描述

package com.Adder;
import javax.swing.*;
import java.awt.*;
/*
 * 1.網格佈局管理器中的組件只能放在網格中
 * 2.網格組佈局管理器,組件擺放比較靈活,但是代碼量比較大
 *
 * 使用網格組佈局的方法
 * 1.創建對象網格組佈局
 * 2.容器對象採用網格組佈局G
 * 3.創建組件的約束對象
 * 4.將組件的約束對象添加到容器中
 * 網格組佈局存在一個抽象的網格,網格上的行與列都有對應的編號,
 * */
public class GridBdg_Layout {
    JFrame jFrame = new JFrame();//主窗體
    Container container;//主容器
 
    public void createFrame() {
        jFrame.setSize(800, 800);//設置窗體大小
        jFrame.setLocationRelativeTo(null);//設置窗體在屏幕居中顯示
 
        container = jFrame.getContentPane();//獲取容器
        container.setLayout(new GridBagLayout());//獲取窗體容器,設置網格組佈局管理器
 
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//設置關閉方式
    }
 
    public void init() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        g1.gridx = 0;//設置在網格的第一行第一列
        g1.gridy = 0;
        container.add(new JButton("組件1"), g1);
 
        GridBagConstraints g2 = new GridBagConstraints();//創建約束條件的類
        g2.gridx = 1;//設置在網格的第2行第2列
        g2.gridy = 1;
        container.add(new JButton("組件2"), g2);
 
        GridBagConstraints g3 = new GridBagConstraints();//創建約束條件的類
        g3.gridx = 2;//設置在網格的第3行第3列
        g3.gridy = 2;
        container.add(new JButton("組件3"), g3);
        /*
         * 注意:如果從第三行第三列直接到第五行第五列,第四行第四列由於沒有組件,第五行第五列的組件會填充到第四行第四列
         * */
    }
 
    public void createButton() {
        for (int i = 0; i < 10; i++) {
            GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
            g1.gridx = i;//設置在網格的第3行第3列
            g1.gridy = 0;
            container.add(new JButton("組件x"), g1);
 
            GridBagConstraints g2 = new GridBagConstraints();//創建約束條件的類
            g2.gridx = 0;//設置在網格的第3行第3列
            g2.gridy = i;
            container.add(new JButton("組件y"), g2);
        }
    }
 
    public void init1() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        container.add(new JButton("組件1"), g1);
        g1.gridx = 1;//設置在網格的第一行第一列
        g1.gridy = 1;
        container.add(new JButton("組件1"), g1);
 
        GridBagConstraints g2 = new GridBagConstraints();//創建約束條件的類
        g2.gridx = 2;//設置組件在在網格中的位置是的第2行第2列
        g2.gridy = 2;
        g2.gridwidth = 2;//設置組件在網格中佔幾行幾列
        g2.gridheight = 1;
        container.add(new JButton("組件2"), g2);
 
        GridBagConstraints g3 = new GridBagConstraints();//創建約束條件的類
        g3.gridx = 4;//設置在網格的第3行第3列
        g3.gridy = 3;
        g3.gridwidth = 2;
        g3.gridheight = 2;
        container.add(new JButton("組件3"), g3);
    }
 
    public void init2() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        container.add(new JButton("組件1"), g1);
        g1.gridx = 1;//設置在網格的第一行第一列
        g1.gridy = 1;
        container.add(new JButton("組件1"), g1);
 
        GridBagConstraints g2 = new GridBagConstraints();//創建約束條件的類
        g2.gridx = 2;//設置組件在在網格中的位置是的第2行第2列
        g2.gridy = 1;
        g2.gridwidth = 2;//設置組件在網格中佔幾行幾列
        g2.gridheight = 2;
        g2.fill = GridBagConstraints.HORIZONTAL;
        container.add(new JButton("組件2 HORIZONAL"), g2);
 
        GridBagConstraints g3 = new GridBagConstraints();//創建約束條件的類
        g3.gridx = 5;//設置在網格的第3行第3列
        g3.gridy = 1;
        g3.gridwidth = 2;
        g3.gridheight = 2;
        g3.fill = GridBagConstraints.VERTICAL;
        container.add(new JButton("組件3 VERTIAL"), g3);
 
 
        GridBagConstraints g4 = new GridBagConstraints();//創建約束條件的類
        g4.gridx = 8;//設置在網格的第3行第3列
        g4.gridy = 1;
        g4.gridwidth = 2;
        g4.gridheight = 2;
        g4.fill = GridBagConstraints.BOTH;
        container.add(new JButton("組件3 BOTH"), g4);
    }
 
    public void init3() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        /*container.add(new JButton("組件1"),g1);*/
        g1.gridx = 1;//設置在網格的第一行第一列
        g1.gridy = 1;
        g1.gridwidth = 2;//設置組件在網格中佔幾行幾列
        g1.gridheight = 2;
        g1.anchor = GridBagConstraints.NORTH;//設置組件所在的方位爲北
        container.add(new JButton("組件1"), g1);
 
        g1.fill = GridBagConstraints.BOTH;//填充方式爲全部填充
        JPanel jp = new JPanel();
        jp.setBackground(Color.green);
        container.add(jp, g1);
 
 
        GridBagConstraints g2 = new GridBagConstraints();//創建約束條件的類
        g2.gridx = 3;//設置組件在在網格中的位置是的第2行第2列
        g2.gridy = 1;
        g2.gridwidth = 2;//設置組件在網格中佔幾行幾列
        g2.gridheight = 2;
        g2.anchor = GridBagConstraints.SOUTH;//設置組件所在的方位爲南
        g2.fill = GridBagConstraints.HORIZONTAL;//左右填充
        container.add(new JButton("組件2"), g2);
 
        g2.fill = GridBagConstraints.BOTH;//填充方式爲全部填充
        /*g2.anchor=GridBagConstraints.HORIZONTAL;*/
        JPanel jp2 = new JPanel();
        jp2.setBackground(Color.red);
        container.add(jp2, g2);
 
        GridBagConstraints g3 = new GridBagConstraints();//創建約束條件的類
        g3.gridx = 5;//設置在網格的第3行第3列
        g3.gridy = 1;
        g3.gridwidth = 2;
        g3.gridheight = 2;
        g3.fill = GridBagConstraints.VERTICAL;//上下填充
        container.add(new JButton("組件3"), g3);
 
        g3.fill = GridBagConstraints.BOTH;
        JPanel jp3 = new JPanel();
        jp3.setBackground(Color.BLUE);
        container.add(jp3, g3);
    }
 
    /*
     * 可以使用inserts屬性來自定義組件在單元格中的位置
     *inserts是一個類,使用四個值來設置組件在單元格中的屬性,這四個值是inserts構造方法的四個參數
     * inserts(top,left,bottom,right),四個參數的單位是像素,類型爲int
     * */
    public void init5() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        /*container.add(new JButton("組件1"),g1);*/
        g1.gridx = 1;//設置在網格的第一行第一列
        g1.gridy = 1;
        /*g1.gridwidth=2;//設置組件在網格中佔幾行幾列
        g1.gridheight=2;*/
        g1.insets = new Insets(10, 5, 10, 10);
 
        container.add(new JButton("組件1"), g1);
    }
 
    /*
     * ipadx和ipady屬性定義組件的首選大小
     * */
    public void init6() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        /*container.add(new JButton("組件1"),g1);*/
        g1.gridx = 1;//設置在網格的第一行第一列
        g1.gridy = 1;
        g1.ipadx = 10;
        g1.ipady = 10;
        g1.gridwidth = 2;//設置組件在網格中佔幾行幾列
        g1.gridheight = 2;
        g1.insets = new Insets(10, 5, 10, 10);
        container.add(new JButton("組件1"), g1);
 
        g1.fill = GridBagConstraints.BOTH;//填充方式爲全部填充
        JPanel jp = new JPanel();
        jp.setBackground(Color.green);
        container.add(jp, g1);
 
 
        GridBagConstraints g2 = new GridBagConstraints();//創建約束條件的類
        /*container.add(new JButton("組件1"),g1);*/
        g2.gridx = 3;//設置在網格的第一行第一列
        g2.gridy = 1;
        g2.ipadx = -5;
        g2.ipady = -5;
        g2.gridwidth = 2;//設置組件在網格中佔幾行幾列
        g2.gridheight = 2;
        g2.insets = new Insets(10, 5, 10, 10);
        container.add(new JButton("組件1"), g2);
 
        g2.fill = GridBagConstraints.BOTH;//填充方式爲全部填充
        /*g2.anchor=GridBagConstraints.HORIZONTAL;*/
        JPanel jp2 = new JPanel();
        jp2.setBackground(Color.red);
        container.add(jp2, g2);
    }
 
    /*
     * weightx和weighty,設置一個單元個的最大寬和高
     * 默認情況下,一個組件如果正好填滿一個單元格,但是當拉大窗體的時候,單元格會變大,但是組件並不會變大
     * 當設置了weightx和weighty之後,組件的大小就會隨着單元格的大小的改變而改變
     * */
    public void init7() {
        GridBagConstraints g1 = new GridBagConstraints();//創建約束條件的類
        g1.gridx = 1;
        g1.gridy = 1;
        g1.weightx=2;
        g1.weighty=2;
        container.add(new JButton("組件1"), g1);
    }
 
 
    public static void main(String[] args) {
        GridBdg_Layout bdg_layout = new GridBdg_Layout();
        bdg_layout.createFrame();
        bdg_layout.createButton();
        bdg_layout.init7();
        bdg_layout.jFrame.setVisible(true);
    }
}

6.下拉列表

package com.Adder;
 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
/*
* 下拉框
* */
public class JCombo_Box extends JFrame {
 
    public JCombo_Box(){
        this.setBounds(500,400,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
        Container container=this.getContentPane();//獲取容器
        container.setLayout(null);//設置絕對佈局
 
        /*JComboBox可以保存泛型
        * 如添加String表示下拉列表中的元素都是字符串
        * */
       /* JComboBox<String> comboBox=new JComboBox<>();
       *//* comboBox.addItem("身份證");
        comboBox.addItem("學生證");
        comboBox.addItem("軍人證");*/
 
        /*
        * 第二種方式創建下拉列表->構架一個字符串數組,並將這個字符串數組當作參數傳入下拉框
        * */
        /*String[] items = {"數組元素1", "數組元素1", "數組元素1"};
        JComboBox<String> comboBox=new JComboBox<>(items);*/
 
        /*
        * 第三種創建架下拉列表的方法,實現一個下拉列表模型接口
        * ComboBoxModel是一個接口
        * */
        String[] items = {"數組元素1", "數組元素2", "數組元素3"};
        JComboBox<String> comboBox=new JComboBox<>();
        ComboBoxModel<String> comboBoxModel=new DefaultComboBoxModel<>(items);//牀架一個下拉列表的模型
        comboBox.setModel(comboBoxModel);//向列表中添加數據模型
 
        /*獲取選中的值*/
        JButton button=new JButton("打印");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("選中的元素的索引:"+comboBox.getSelectedIndex());//獲取選中的索引
                System.out.println("選中的元素的值:"+comboBox.getSelectedItem());//獲取選中的元素的值
            }
        });
        button.setBounds(240,20,70,30);//設置按鈕的位置和大小
        container.add(button);
        comboBox.setEditable(true);//設置下拉框中的內容是否可以編輯
        comboBox.setBounds(20,20,200,30);//設置下拉列表的座標和大小
        container.add(comboBox);//將下拉列表添加到容器中
        this.setVisible(true);
    }
 
    public static void main(String[] args) {
        new JCombo_Box();
    }
}

7.列表框

/*
 * 列表框
 * */
public class J_list extends JFrame {
    public J_list() {
        this.setBounds(500, 500, 500, 500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
        Container container = this.getContentPane();
        container.setLayout(null);
 
        String[] items1 = {"元素1", "元素1", "元素1", "元素1", "元素1", "元素1", "元素1"};
 
 
        DefaultListModel<String> dlm = new DefaultListModel<>();//創建列表框數據模型
        for (String temp : items1) {
            dlm.addElement(temp);//向數據模型中添加元素
        }
 
        dlm.addElement("新元素");//數據模型調用addElement方法就可以在數據模型中添加新的元素
        JList<String> jl = new JList<>();
        jl.setModel(dlm);
 
        /*
         * SINGLE_SELECTION:單選
         * SINGLE_INTERVAL_SELECTION:只能連續選擇相鄰的元素
         * MULTIPLE_INTERVAL_SELECTION:不限定選擇模式
         * */
        jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//設置選擇模式
 
        JScrollPane jsp = new JScrollPane(jl);//創建滾動面板,向滾動面板中添加列表框
        jsp.setBounds(10, 10, 100, 300);//設置滾動面板的座標和大小
        container.add(jsp);//將滾動面板添加到容器中
 
        /*獲取列表框中選中的數據*/
        JButton button = new JButton("確認");
        button.setBounds(130, 10, 80, 50);
        button.addActionListener(new ActionListener() {//爲按鈕添加時間監聽
            public void actionPerformed(ActionEvent e) {
                List<String> list = jl.getSelectedValuesList();
                for (String temp : list) {
                    System.out.println("選中的數據:"+temp);
                }
                System.out.println("-----end--------");
            }
        });
 
        container.add(button);
        this.setVisible(true);
    }
 
    public static void main(String[] args) {
        new J_list();
    }
}

8.文本框組件

package com.Adder;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class JText_Field extends JFrame {
    public JText_Field(){
        this.setBounds(500,500,500,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
        Container container=this.getContentPane();
        container.setLayout(new FlowLayout());
 
        JTextField textField =new JTextField();
        textField.setColumns(20);//設置文本框的長度,長度爲20個字符
        textField.setText("初始值1");//設置文本
        textField.setFont(new Font("楷體",Font.PLAIN,20));//設置字體格式:字體爲楷體、字體的樣式爲普通樣式、字號爲20
 
        container.add(textField);
 
 
        JButton button=new JButton("獲取文本框中的內容");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("文本框中的內容爲: "+textField.getText());//獲取文本框中的內容
                textField.setText("");//清空文本框中的內容
                textField.requestFocus();//獲取焦點(光標)
            }
        });
 
        container.add(button);
        this.setVisible(true);
    }
 
    public static void main(String[] args) {
        new JText_Field();
    }
}

9.密碼框組件

package com.Adder;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class JPassword_field extends JFrame {
    public JPassword_field(){
        this.setBounds(200,200,500,500);
 
        Container container=this.getContentPane();
        container.setLayout(new FlowLayout());
 
        JPasswordField passwordField=new JPasswordField();
        passwordField.setColumns(20);//設置密碼框可以顯示20個字符
        //passwordField.setFont(new Font("密碼",Font.BOLD,18));//設置字體
        passwordField.setEchoChar('#');//設置回顯字符
 
        passwordField.addActionListener(new ActionListener() {//單擊回車,獲取密碼
            public void actionPerformed(ActionEvent e) {
                char[] password=passwordField.getPassword();
                String str=new String(password);
                System.out.println(str);
            }
        });
 
        container.add(passwordField);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
 
    public static void main(String[] args) {
        new JPassword_field();
    }
}

10.文本域組件

package com.Adder;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class JText_Area extends JFrame {
    public JText_Area(){
        this.setBounds(200,200,500,500);
 
        Container container=this.getContentPane();
        container.setLayout(new FlowLayout());
 
        JTextArea area =new JTextArea();//獲取文本域對象
        area.setRows(5);//設置文本域行數(寬)
        area.setColumns(10);//設置文本域列數(長)
        area.setFont(new Font("楷體",Font.PLAIN,20));//設置文本域中文字的格式
        area.setText("文本域初始文本內容");
 
        JButton button=new JButton("文本框內容");
        button.addActionListener(new ActionListener() {
 
            public void actionPerformed(ActionEvent e) {//獲取文本域中的內容
                System.out.println("文本域中的內容: "+area.getText());
            }
        });
 
        container.add(button);
        JScrollPane jsp=new JScrollPane(area);//給文本域添加滾動條
        container.add(jsp);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);
 
    }
 
    public static void main(String[] args) {
        new JText_Area();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章