2018年7月26日 星期四

JAVA基礎必修課學習筆記 (3)

  因工作的緣故,閱讀蔡文龍、張志成編著的《JAVA SE 8基礎必修課》以學習Java程式基礎,目前最新的Java程式版本為Java SE 10,筆記中的程式撰寫習慣盡量仿照Python以增加可讀性。

一、Swing視窗應用程式

JFrame類別
l   範例:
package testPackage;
import javax.swing.*;
class testJFrame extends JFrame{
    testJFrame(){
        //
設定JFrame視窗按下"叉叉"按鈕即關閉視窗
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //
設定JFrame視窗x, y座標位置與寬高
        setBounds(100, 100, 450, 300);
        //
設定JFrame視窗標題
        setTitle("JFrame Title");
        //
顯示JFrame視窗
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        testJFrame obj = new testJFrame();
        //
傳回JFrame視窗標題
        System.out.println(obj.getTitle());
        //
JFrame視窗關閉,釋放資源
        obj.dispose();
    }
}

版面配置
l   絕對座標版面配置:
package testPackage;
import javax.swing.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        //
設定testJFrame視窗的容器為testJPanel
        setContentPane(testJPanel);
        //
設定testJPanel視窗版面配置,不使用版面配置管理者
        testJPanel.setLayout(null);
       
        JButton aBtn = new JButton("Button A");
        aBtn.setBounds(25, 25, 100, 25);
        testJPanel.add(aBtn);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}
l   邊緣式版面配置(BorderLayout)
package testPackage;
import javax.swing.*;
import java.awt.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        // BorderLayout()
引數為寬度與高度,單位為像素
        testJPanel.setLayout(new BorderLayout(5, 5));
       
        JButton eastBtn = new JButton("Button East");
        testJPanel.add(eastBtn, BorderLayout.EAST);
        JButton westBtn = new JButton("Button West");
        testJPanel.add(westBtn, BorderLayout.WEST);
        JButton southBtn = new JButton("Button South");
        testJPanel.add(southBtn, BorderLayout.SOUTH);
        JButton northBtn = new JButton("Button North");
        testJPanel.add(northBtn, BorderLayout.NORTH);
        JButton centerBtn = new JButton("Button Center");
        testJPanel.add(centerBtn, BorderLayout.CENTER);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}
l   流程式版面配置(FlowLayout)
package testPackage;
import javax.swing.*;
import java.awt.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    public testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        // FlowLayout()
引數為擺放元件位置方式,有FlowLayout.LEFTFlowLayout.CENTERFlowLayout.RIGHT三種,以及間距寬度與高度,單位為像素
        testJPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
       
        JButton aBtn = new JButton("Button A");
        testJPanel.add(aBtn);
        JButton bBtn = new JButton("Button B");
        testJPanel.add(bBtn);
        JButton cBtn = new JButton("Button C");
        testJPanel.add(cBtn);
        JButton dBtn = new JButton("Button D");
        testJPanel.add(dBtn);
        JButton eBtn = new JButton("Button E");
        testJPanel.add(eBtn);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}
l   格線式版面配置(GridLayout)
package testPackage;
import javax.swing.*;
import java.awt.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    public testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        // GridLayout()
引數為列數與行數,以及間距寬度與高度,單位為像素
        testJPanel.setLayout(new GridLayout(2, 3, 5, 5));
       
        JButton aBtn = new JButton("Button A");
        testJPanel.add(aBtn);
        JButton bBtn = new JButton("Button B");
        testJPanel.add(bBtn);
        JButton cBtn = new JButton("Button C");
        testJPanel.add(cBtn);
        JButton dBtn = new JButton("Button D");
        testJPanel.add(dBtn);
        JButton eBtn = new JButton("Button E");
        testJPanel.add(eBtn);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

事件來源、事件傾聽者、事件處理
l   事件來源任務一、對傾聽者進行註冊和取消註冊:
//
例如以按鈕物件aBtn對傾聽者進行註冊
aBtn.addActionListener(
傾聽者物件);
//
例如以按鈕物件bBtn對傾聽者取消註冊
bBtn.removeActionListener(
傾聽者物件);
l   事件來源任務二、產生事件:
例如事件來源Button對應事件類別名稱ActionEvent
l   事件來源任務三、傳送事件給已註冊的傾聽者:
actionPerformed(ActionEvent e)
l   範例一:
package testPackage;
import javax.swing.*;
import java.awt.event.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    public testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        testJPanel.setLayout(null);
       
        JButton aBtn = new JButton("Button A");
        aBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JButton hitBtn = (JButton)e.getSource();
                JOptionPane.showMessageDialog(null, hitBtn.getText() + " - Hello World");
            }
        });
        aBtn.setBounds(25, 25, 100, 25);
        testJPanel.add(aBtn);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}
l   範例二:
package testPackage;
import javax.swing.*;
import java.awt.event.*;
class testJFrame extends JFrame implements ActionListener{
    JPanel testJPanel = new JPanel();
    public testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        testJPanel.setLayout(null);
       
        JButton aBtn = new JButton("Button A");
        aBtn.addActionListener(this);
        aBtn.setBounds(25, 25, 100, 25);
        testJPanel.add(aBtn);
       
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e){
        JButton hitBtn = (JButton)e.getSource();
        JOptionPane.showMessageDialog(null, hitBtn.getText() + " - Hello World");
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

二、Swing元件

JPanel面板元件
l   常用的建構式:
//
必須另由setLayout方法來設定
JPanel obj = new JPanel();
//
引數用來指定面板的版面配置方式
JPanel obj = new JPanel(LayoutManager layout);
l   常用的方法成員:
// JPanel testJPanel = new JPanel();
//
使用前必須載入:import java.awt.*;,設定面板元件的背景顏色
testJPanel.setBackground(Color.yellow);
//
使用前必須載入:import java.awt.*;,設定面板元件的邊框線條顏色、厚度與文字
testJPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black), "Title"));
l   範例:
package testPackage;
import javax.swing.*;
import java.awt.*;
class testJFrame extends JFrame{
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setLayout(null);
        
        JPanel testJPanel = new JPanel();
        add(testJPanel);
        testJPanel.setBounds(25, 25, 200, 125);
        testJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
       
        String[] btnName = {"Button A", "Button B", "Button C"};
        JButton[] btn = new JButton[btnName.length];
        for (int i = 0; i < btnName.length; i++){
            btn[i] = new JButton(btnName[i]);
            testJPanel.add(btn[i]);}
        
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JLabel標籤元件
l   常用的建構式:
//
對齊方式有JLabel.LEFTJLabel.CENTERJLabel.RIGHTJLabel.LEADINGJLabel.TRAILING
JLabel obj = new JLabel();
JLabel obj = new JLabel(
字串);
JLabel obj = new JLabel(
字串, 對齊方式);
JLabel obj = new JLabel(
圖示);
JLabel obj = new JLabel(
圖示, 對齊方式);
JLabel obj = new JLabel(
字串, 圖示, 對齊方式);
l   常用的方法成員:
// JLabel imageJLabel = new JLabel();
// JLabel textJLabel = new JLabel();
//
設置字串
textJLabel.setText("Hello World");
//
設置圖示
imageJLabel.setIcon(new ImageIcon("D:\\test.jpg"));
//
取得字串
System.out.println(textJLabel.getText());
//
取得圖示
System.out.println(imageJLabel.getIcon());
l   範例:
package testPackage;
import javax.swing.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        testJPanel.setLayout(null);
       
        JLabel imageJLabel = new JLabel(new ImageIcon("D:\\test.jpg"));
        imageJLabel.setBounds(25, 25, 180, 135);
        testJPanel.add(imageJLabel);
       
        JLabel textJLabel = new JLabel("Hello World");
        textJLabel.setBounds(25, 205, 75, 25);
        testJPanel.add(textJLabel);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JTextField文字欄位元件
l   常用的建構式:
JTextField obj = new JTextField();
JTextField obj = new JTextField(
字串);
JTextField obj = new JTextField(
列數);
JTextField obj = new JTextField(
字串, 列數);
l   常用的方法成員:
// JTextField txtF = new JTextField();
//
設置字串
txtF.setText("Hello World");
//
設置列數
txtF.setColumns(5);
//
使用前必須載入:import java.awt.Font;,設定字型
txtF.setFont(new Font("Calibri", Font.BOLD,12));
//
設定當滑鼠移動到文字欄位時出現提示字元
txtF.setToolTipText("Hello World");
//
設定允許編輯文字
txtF.setEditable(true);
//
取得字串
System.out.println(txtF.getText());
//
取得列數
System.out.println(txtF.getColumns());
l   範例:
package testPackage;
import javax.swing.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        testJPanel.setLayout(null);
       
        JTextField txtF = new JTextField();
        txtF.setBounds(25, 25, 100, 25);
        testJPanel.add(txtF);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JButton按鈕元件
l   常用的建構式:
JButton obj = new JButton();
JButton obj = new JButton(
字串);
JButton obj = new JButton(
圖示);
JButton obj = new JButton(
字串, 圖示);
l   常用的方法成員:
// JButton btn = new JButton();
//
設置字串
btn.setText("Hello World");
//
設置圖示
btn.setIcon(new ImageIcon("D:\\test.jpg"));
//
設置失效時的圖示
btn.setDisabledIcon(new ImageIcon("D:\\test.jpg"));
//
設置按下時的圖示
btn.setPressedIcon(new ImageIcon("D:\\test.jpg"));
//
設置滑鼠越過時的圖示
btn.setRolloverIcon(new ImageIcon("D:\\test.jpg"));
//
設定字串和圖示的垂直位置,有TOPCENTERBOTTOM三種
btn.setVerticalAlignment(JButton.CENTER);
//
設定字串和圖示的水平位置,有LEFTCENTERRIGHT三種
btn.setHorizontalTextPosition(JButton.CENTER);
//
設定按鈕是否顯示邊框
btn.setBorderPainted(true);
//
設定按鈕取得焦點時是否顯示虛線
btn.setFocusPainted(true);
//
取得字串
System.out.println(btn.getText());
//
取得圖示
System.out.println(btn.getIcon());
//
取得失效時的圖示
System.out.println(btn.getDisabledIcon());
//
取得按下時的圖示
System.out.println(btn.getPressedIcon());
//
取得滑鼠越過時的圖示
System.out.println(btn.getRolloverIcon());
l   範例:
package testPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        testJPanel.setLayout(null);
       
        JButton btn = new JButton("Button");
        btn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                testJPanel.setBackground(Color.blue);
            }
        });
        btn.setBounds(25, 25, 100, 25);
        testJPanel.add(btn);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JOptionPane對話方塊元件
l   常用的建構式:
//
訊息種類有JOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGEJOptionPane.PLAIN_MESSAGE
//
按鈕種類有JOptionPane.DEFAULT_OPTIONJOptionPane.CANCEL_OPTIONJOptionPane.CLOSED_OPTIONJOptionPane.OK_OPTIONJOptionPane.YES_OPTIONJOptionPane.NO_OPTION
JOptionPane obj = new JOptionPane();
JOptionPane obj = new JOptionPane(
字串);
JOptionPane obj = new JOptionPane(
字串, 訊息種類);
JOptionPane obj = new JOptionPane(
字串, 訊息種類, 按鈕種類);
JOptionPane obj = new JOptionPane(
字串, 訊息種類, 按鈕種類, 圖示);
l   常用的方法成員:
// JOptionPane opt = new JOptionPane();
//
設置字串
opt.setInputValue("Hello World");
//
設置輸入區
opt.setWantsInput(true);
//
設置選擇區塊
String[] pokemon = {"Turtwig", "Chimchar", "Piplup"};
opt.setSelectionValues(pokemon);
//
取得字串
System.out.println(opt.getInputValue());
//
取得是否有輸入區
System.out.println(opt.getWantsInput());
//
取得圖示
System.out.println(opt.getIcon());
l   範例:
package testPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class testJFrame extends JFrame{
    JPanel testJPanel = new JPanel();
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setContentPane(testJPanel);
        testJPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
       
        JButton aBtn = new JButton("Message");
        aBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JOptionPane.showMessageDialog(null, "Content", "Title", JOptionPane.WARNING_MESSAGE);
            }
        });
        testJPanel.add(aBtn);
       
        JButton bBtn = new JButton("Input");
        bBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JOptionPane.showInputDialog(null, "Input:", "Title", JOptionPane.QUESTION_MESSAGE);
            }
        });
        testJPanel.add(bBtn);
       
        JButton cBtn = new JButton("Confirm");
        cBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JOptionPane.showConfirmDialog(null, "Content", "Title", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            }
        });
        testJPanel.add(cBtn);
       
        JOptionPane opt = new JOptionPane("Hello World", JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_OPTION);
        testJPanel.add(opt);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JCheckBox核取方塊元件
l   常用的建構式:
JCheckBox obj = new JCheckBox(
字串);
JCheckBox obj = new JCheckBox(
字串, 布林);
l   常用的方法成員:
// JCheckBox chk = new JCheckBox("Fennekin");
//
設定核取方塊是否被選取
chk.setSelected(true);
//
取得核取方塊是否被選取
System.out.println(chk.isSelected());
l   範例:
package testPackage;
import javax.swing.*;
import java.awt.*;
class testJFrame extends JFrame{
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setLayout(null);
         
        JPanel testJPanel = new JPanel();
        add(testJPanel);
        testJPanel.setBounds(25, 25, 100, 100);
        testJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
       
        JCheckBox[] chk = new JCheckBox[3];
        chk[0] = new JCheckBox("Turtwig");
        chk[1] = new JCheckBox("Chimchar");
        chk[2] = new JCheckBox("Piplup");
        for (int i = 0; i < chk.length; i++){
            testJPanel.add(chk[i]);}
        
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JRadioButton選項圓鈕元件
l   常用的建構式:
ButtonGroup obj = new ButtonGroup();
JRadioButton obj = new JRadioButton(
字串);
JRadioButton obj = new JRadioButton(
字串, 布林);
l   常用的方法成員:
// JPanel testJPanel = new JPanel();
// ButtonGroup btnGroup = new ButtonGroup();
// JRadioButton rdb = new JRadioButton("Fennekin");
//
設置選項圓鈕元件
btnGroup.add(rdb);
testJPanel.add(rdb);
//
移除選項圓鈕元件
btnGroup.remove(rdb);
testJPanel.remove(rdb);
l   範例:
package testPackage;
import javax.swing.*;
import java.awt.*;
class testJFrame extends JFrame{
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setLayout(null);
       
        JPanel testJPanel = new JPanel();
        add(testJPanel);
        testJPanel.setBounds(25, 25, 100, 100);
        testJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
       
        ButtonGroup btnGroup = new ButtonGroup();
        JRadioButton[] rdb = new JRadioButton[3];
        rdb[0] = new JRadioButton("Turtwig");
        rdb[1] = new JRadioButton("Chimchar");
        rdb[2] = new JRadioButton("Piplup");
        for (int i = 0; i < rdb.length; i++){
            btnGroup.add(rdb[i]);
            testJPanel.add(rdb[i]);}
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JTextArea多行文字欄位元件
l   常用的建構式:
JTextArea obj = new JTextArea();
JTextArea obj = new JTextArea(
列數, 欄數);
JTextArea obj = new JTextArea(
字串);
JTextArea obj = new JTextArea(
字串, 列數, 欄數);
l   常用的方法成員:
// JTextArea txtA = new JTextArea();
//
設置字串
txtA.append("Hello World");
//
設置字串插入的位置
txtA.insert("Poor ", 6);
//
設定顯示列數
txtA.setRows(5);
//
設定顯示欄數
txtA.setColumns(5);
//
設定文字超過元件寬度的自動換行功能
txtA.setLineWrap(true);
l   範例:
package testPackage;
import javax.swing.*;
class testJFrame extends JFrame{
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
         setLayout(null);
       
        JTextArea txtA = new JTextArea("Hello World");
        add(txtA);
        txtA.setBounds(5, 5, 420, 250);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JScrollPane捲軸面板元件
l   常用的建構式:
//
垂直顯示方式有ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYSScrollPaneConstants.VERTICAL_SCROLLBAR_ NEVERScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
//
水平顯示方式有ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYSScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVERScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
JScrollPane obj = new JScrollPane(view
元件);
JScrollPane obj = new JScrollPane(view
元件, 垂直顯示方式, 水平顯示方式);
l   範例:
package testPackage;
import javax.swing.*;
class testJFrame extends JFrame{
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setLayout(null);
       
        JTextArea txtA = new JTextArea("Hello World");
       
        JScrollPane pane = new JScrollPane(txtA, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        add(pane);
        pane.setBounds(5, 5, 420, 250);
       
        setVisible(true);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JList清單元件
l   常用的建構式:
JList<
資料型別> obj = new JList<>();
JList<
資料型別> obj = new JList<>(陣列);
l   常用的方法成員:
// String[] pokemon = {"Turtwig", "Chimchar", "Piplup"};
// JList<String> testJList = new JList<>();
//
設置字串陣列至清單元件
testJList.setListData(pokemon);
//
設置列數
testJList.setVisibleRowCount(3);
//
以下方法須搭配清單事件使用,見範例
//
以串列取得所有被選取項目的字串
ArrayList<String> aObj = new ArrayList<>(testJList.getSelectedValuesList());
//
以陣列取得所有被選取項目的索引值
int[] bObj = testJList.getSelectedIndices();
//
取得被選取項目最前面的字串
String cObj = testJList.getSelectedValue();
//
取得被選取項目最前面的索引值
int dObj = testJList.getSelectedIndex();
l   範例:
package testPackage;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.util.*;
class testJFrame extends JFrame implements ListSelectionListener{
    String[] pokemon = {"Turtwig", "Chimchar", "Piplup"};
    JList<String> testJList = new JList<>(pokemon);
    JTextArea txtA = new JTextArea("Choose Your Favorite Pokemons", 3, 3);
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setLayout(null);
        
        JPanel aTestJPanel = new JPanel();
        add(aTestJPanel);
        aTestJPanel.setBounds(25, 25, 200, 75);
        aTestJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        aTestJPanel.add(testJList);
       
        testJList.addListSelectionListener(this);
       
        JPanel bTestJPanel = new JPanel();
        add(bTestJPanel);
        bTestJPanel.setBounds(25, 125, 200, 75);
        bTestJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        bTestJPanel.add(txtA);
       
        setVisible(true);
    }
    public void valueChanged(ListSelectionEvent e){
        ArrayList<String> pm = new ArrayList<>(testJList.getSelectedValuesList());
        int[] pmIndex = testJList.getSelectedIndices();
        String show = "";
        int i = 0;
        for (String s : pm){
            show += s + ", Index = " + pmIndex[i] + "\n";
            i++;}
        txtA.setText(show);
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

JComboBox下拉式清單元件
l   常用的建構式:
JComboBox<
資料型態> obj = new JComboBox<>();
JComboBox<
資料型態> obj = new JComboBox<>(陣列);
l   常用的方法成員:
// JComboBox<String> testJCBox = new JComboBox<>();
//
設置字串
testJCBox.addItem("Hello World");
//
設置字串插入的位置
testJCBox.insertItemAt("Poor", 0);
//
移除字串
testJCBox.removeItem("Hello World");
//
移除索引位置的字串
testJCBox.removeItemAt(0);
//
設定是否能編輯文字
testJCBox.setEditable(false);
//
取得索引位置的字串
System.out.println(testJCBox.getItemAt(2));
//
以下方法須搭配下拉式清單事件使用,見範例
//
取得被選取項目的字串
Object aObj = testJCBox.getSelectedItem();
//
取得被選取項目的索引值
int bObj = testJCBox.getSelectedIndex();
l   範例:
package testPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class testJFrame extends JFrame implements ItemListener, ActionListener{
    String[] pokemon = {"Turtwig", "Chimchar", "Piplup"};
    JComboBox<String> testJCBox = new JComboBox<>(pokemon);
    JLabel testJLabel = new JLabel("Choose Your Favorite Pokemon");
    JButton addBtn = new JButton("Add");
    JButton delBtn = new JButton("Delete");
    testJFrame(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        setLayout(null);
       
        JPanel aTestJPanel = new JPanel();
        add(aTestJPanel);
        aTestJPanel.setBounds(25, 25, 200, 75);
        aTestJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        aTestJPanel.add(testJCBox);
       
        testJCBox.addItemListener(this);
       
        JPanel bTestJPanel = new JPanel();
        add(bTestJPanel);
        bTestJPanel.setBounds(250, 25, 200, 75);
        bTestJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        bTestJPanel.add(addBtn);
        bTestJPanel.add(delBtn);
       
        addBtn.addActionListener(this);
        delBtn.addActionListener(this);
       
        JPanel cTestJPanel = new JPanel();
        add(cTestJPanel);
        cTestJPanel.setBounds(25, 125, 200, 75);
        cTestJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        cTestJPanel.add(testJLabel);
        
        setVisible(true);
    }
    public void itemStateChanged(ItemEvent e){
        Object pm = testJCBox.getSelectedItem();
        int pmIndex = testJCBox.getSelectedIndex();
        testJLabel.setText(pm + ", Index = " + pmIndex);
    }
    public void actionPerformed(ActionEvent e){
        if (e.getSource() == addBtn){
            String inputStr = JOptionPane.showInputDialog("Input:");
            testJCBox.addItem(inputStr);
            testJLabel.setText("Add " + inputStr + " to Last");}
        if (e.getSource() == delBtn){
            Object selectedStr = testJCBox.getSelectedItem();
            testJCBox.removeItem(selectedStr);
            testJLabel.setText("Delete " + selectedStr);}
    }
}
public class test{
    public static void main(String[] args){
        new testJFrame();
    }
}

三、I/O常用類別

File類別
l   範例一:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args){
        File a = new File("D:\\test.txt");
        //
傳回檔案名稱
        System.out.println(a.getName());
        //
傳回檔案長度
        System.out.println(a.length());
        //
傳回true表示為檔案
        System.out.println(a.isFile());
        //
傳回true表示為目錄
        System.out.println(a.isDirectory());
        //
傳回true表示成功將檔案設為唯讀
        System.out.println(a.setReadOnly());
        //
傳回true表示可讀取
        System.out.println(a.canRead());
        //
傳回true表示可寫入
        System.out.println(a.canWrite());
        //
傳回路徑
        System.out.println(a.toString());
        //
傳回true表示成功刪除檔案
        System.out.println(a.delete());
        //
傳回true表示檔案存在
        System.out.println(a.exists());
    }
}
l   範例二:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args){
            File a = new File("D:\\test.txt");
        try{
            //
傳回true表示成功建立檔案
            System.out.println(a.createNewFile());}
        catch (IOException e){
            e.printStackTrace();}
        File b = new File("D:\\test2.txt");
        //
傳回true表示成功重新命名檔案
        System.out.println(a.renameTo(b));
    }
}

Reader檔案讀取類別
l   FileReader類別:
package testPackage;
import java.io.*;
public class test{
    //
使用throws IOException即可不使用try...catch
    public static void main(String[] args) throws IOException{
        File txtFile = new File("D:\\test.txt");
        //
建構式引數可傳入File物件或檔案路徑
        FileReader a = new FileReader(txtFile);
        int size = (int)txtFile.length();
        char[] buffer = new char[size];
        // read()
方法未傳入引數時讀取一個字元
        a.read(buffer);
        System.out.println(buffer);
        a.close();
    }
}
l   BufferedReader類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        String buffer;
        //
第一引數為Reader物件,第二引數為緩衝區大小
        BufferedReader a = new BufferedReader(new FileReader("D:\\test.txt"));
        do{
            buffer = a.readLine();
            if (buffer == null){
                break;}
            System.out.println(buffer);}
            while (true);
        a.close();
    }
}
l   CharArrayReader類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        String str = "Hello World\n";
        char[] buffer = new char[str.length()];
        for (int i = 0; i < str.length(); i++){
            buffer[i] = str.charAt(i);}
        //
第一引數為陣列,第二引數為開始讀取處,第三引數為取得位元組長度
        CharArrayReader a = new CharArrayReader(buffer);
        for (int i = 0; i < str.length(); i++){
            System.out.print((char)a.read());}
    }
}

Writer檔案寫入類別
l   FileWriter類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
建構式第一引數可傳入File物件或檔案路徑,第二引數預設false表示新增的資料將覆蓋原來的資料
        FileWriter a = new FileWriter("D:\\test.txt", true);
        a.write("Hello World\n");
        a.close();
    }
}
l   BufferedWriter類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
第一引數為Writer物件,第二引數為緩衝區大小
        BufferedWriter a = new BufferedWriter(new FileWriter("D:\\test.txt", true));
        a.write("Hello World");
        a.newLine();
        a.close();
    }
}
l   CharArrayWriter類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
引數為緩衝區大小
        CharArrayWriter a = new CharArrayWriter();
        String str = "Hello World\n";
        char[] aBuffer = new char[str.length()];
        for (int i = 0; i < str.length(); i++){
            aBuffer[i] = str.charAt(i);}
        a.write(aBuffer);
        char[] bBuffer = a.toCharArray();
        int size = bBuffer.length;
        for (int i = 0; i < size; i++){
            System.out.print(bBuffer[i]);}
    }
}

InputStream二進位檔讀取類別
l   FileInputStream類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
建構式引數可傳入File物件或檔案路徑
        FileInputStream a = new FileInputStream("D:\\test.txt");
        int size = a.available();
        byte[] buffer = new byte[size];
        a.read(buffer);
        for (int i = 0; i < size; i++){
            System.out.print((char)buffer[i]);}
        a.close();
    }
}
l   BufferedInputStream類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String args[]) throws IOException{
        //
第一引數為InputStream物件,第二引數為緩衝區大小
        BufferedInputStream a = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
        int size = a.available();
        byte[] buffer = new byte[size];
        a.read(buffer);
        for (int i = 0; i < size; i++){
            System.out.print((char)buffer[i]);}
        a.close();
    }
}
l   ByteArrayInputStream類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args){
        String str = "Hello World\n";
        byte[] buffer = str.getBytes();
        //
第一引數為陣列,第二引數為開始讀取處,第三引數為取得位元組長度
        ByteArrayInputStream a = new ByteArrayInputStream(buffer);
        int size = a.available();
        for (int i = 0; i < size; i++){
            System.out.print((char)a.read());}
    }
}

OutputStream二進位檔寫入類別
l   FileOutputStream類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
建構式第一引數可傳入File物件或檔案路徑,第二引數預設false表示新增的資料將覆蓋原來的資料
        FileOutputStream a = new FileOutputStream("D:\\test.txt", true);
        String str = "Hello World\n";
        byte[] buffer = str.getBytes();
        for (int i = 0; i < buffer.length; i++){
            a.write(buffer[i]);}
        a.close();
    }
}
l   BufferedOutputStream類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
第一引數為OutputStream物件,第二引數為緩衝區大小
        BufferedOutputStream a = new BufferedOutputStream(new FileOutputStream("D:\\test.txt", true));
        String str = "Hello World\n";
        byte[] buffer = str.getBytes();
        for (int i = 0; i < buffer.length; i++){
            a.write(buffer[i]);}
        a.close();
    }
}
l   ByteArrayOutputStream類別:
package testPackage;
import java.io.*;
public class test{
    public static void main(String[] args) throws IOException{
        //
引數為緩衝區大小
        ByteArrayOutputStream a = new ByteArrayOutputStream();
        String str = "Hello World\n";
        byte[] aBuffer = str.getBytes();
        a.write(aBuffer);
        byte[] bBuffer = a.toByteArray();
        int size = bBuffer.length;
        for (int i = 0; i < size; i++){
            System.out.print((char)bBuffer[i]);}
    }
}

四、JDBC資料庫程式設計

MySQL開放原始碼關聯式資料庫管理系統
l   學習MySQL的資源:
MySQL Cookbook By PaulDuBois
MySQL超新手入門
(
推薦)
l   下載、安裝MySQL及其相關工具:
Windows上安裝MySQLSetup Type建議選擇Server Only以避免安裝很多額外的Microsoft軟體與函式庫,若選擇Server OnlyConfigure時必須選擇Server Computer
MySQL
MySQL Workbench
phpMyAdmin之類的工具讓快速檢視、排序與新增資料變得很簡單:
MySQLWorkbench
phpMyAdmin
l   MySQL簡易命令列操作-新建資料庫、資料表:
-- 
新建資料庫
CREATE DATABASE testDB;
-- 
使用資料庫
USE testDB;
-- 
新建資料表,MySQL的資料表不能沒有欄位,包含名稱、變數型別、其它可省略的屬性等,欄位最後定義資料表的鍵
CREATE TABLE testable (id BIGINT(7) NOT NULL AUTO_INCREMENT, title VARCHAR(200), content VARCHAR(10000), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id));
-- 
顯示資料表結構
DESCRIBE testTable;
l   MySQL簡易命令列操作-查詢、新增、修改、刪除資料表紀錄:
-- 
SELECT為例,MySQL子句使用的順序
SELECT
à FROM à WHERE à GROUP BY à HAVING à ORDER BY à LIMIT
-- SELECT
查詢資料表紀錄
SELECT * FROM testTable WHERE title = "testTitle" AND content = "testContent";
SELECT * FROM testTable WHERE id BETWEEN 1 AND 5;
SELECT * FROM testTable WHERE id NOT IN (1, 3, 5);
SELECT * FROM testTable ORDER BY title DESC LIMIT 5;
SELECT id, title AS newTitle FROM testTable WHERE content LIKE "%test%";
SELECT DISTINCT title FROM testable;
-- INSERT
新增資料表紀錄
INSERT INTO testTable (title, content) VALUES ("testTitle", "testContent");
-- UPDATE
修改資料表紀錄
UPDATE testTable SET title = "newTitle", content = "newContent" WHERE id = 1;
-- DELETE
刪除資料表紀錄
DELETE FROM testTable WHERE id = 1;
-- 
建立與刪除索引
CREATE INDEX testIndex ON testTable (title, content(16));
ALTER TABLE testTable DROP INDEX testIndex;
l   MySQL簡易命令列操作-統計函式:
SELECT Min(id) FROM testTable;
SELECT Max(id) FROM testTable;
SELECT Avg(id) FROM testTable;
SELECT Sum(id) FROM testTable;
SELECT Count(id) FROM testTable;

使用MySQL,下載JDBC(Java Database Connectivity)資料庫驅動程式
l   下載後免安裝,解壓縮至C:\Java即可:
https://dev.mysql.com/downloads/connector/j/
選擇Platform Independent (Architecture Independent), ZIP Archive
l   Eclipse IDE設置驅動程式:
testProjectJRE System Library按右鍵 à Build Path à Configure Build Path... à Libraries à Modulepath à Add External JARs à 選取mysql-connector-java-8.0.11.jar à Apply and Close
l   JDBC介面:
import java.sql.*;
之後才可以使用DriverManager.getConnection()靜態方法。
Connection
介面物件可以開啟與關閉資料庫的連接。
Statement
介面物件可以新增、修改、與刪除資料表的紀錄。
ResultSet
介面物件可以取得資料表的紀錄。
ResultSetMetaData
介面物件可以取得資料表的格式。

連接資料庫
l   範例:
package testPackage;
import java.sql.*;
public class test{
    public static void main(String[] args){
        try{
             Class.forName("com.mysql.cj.jdbc.Driver");}
        catch (ClassNotFoundException ce){
             System.out.println("No JDBC Driver: " + ce.getMessage());}
        try{
            //
開啟與資料庫的連線
             Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB ? serverTimezone = UTC", "root", "myPassword");
             System.out.println("Turn On the Connection");
            //
關閉與資料庫的連線
            cn.close();
            System.out.println("Turn Off the Connection");}
        catch(SQLException e){
             System.out.println("Connection Failure: " + e.getMessage());}
    }
}

連接資料庫以查詢、新增、修改、刪除資料表紀錄
l   Statement介面常用方法,都會丟出SQLException例外:
//
執行SQL語法的SELECT陳述式,傳回ResultSet物件
ResultSet executeQuery(String sql)
//
執行SQL語法的INSERTUPDATEDELETE陳述式,傳回更動資料列數
int executeUpdate(String sql)
//
傳回更新資料筆數
int getUpdateCount()
//
傳回ResultSet物件
ResultSet getResultSet()
//
釋放Statement物件資源
void close()
l   ResultSet介面常用方法,都會丟出SQLException例外:
//
傳回資料表第i欄的浮點數資料
float getFloat(int i)
//
傳回資料表指定欄名的浮點數資料
float getFloat(String columnName)
//
傳回資料表第i欄的整數資料
int getInt(int i)
//
傳回資料表指定欄名的整數資料
int getInt(String columnName)
//
傳回資料表第i欄的物件
Object getObject(int i)
//
傳回資料表指定欄名的物件
Object getObject(String columnName)
//
傳回資料表第i欄的字串
String getString(int i)
//
傳回資料表指定欄名的字串
String getString(String columnName)
//
判斷ResultSet物件是否有下一筆紀錄
boolean next()
//
傳回ResultSetMetaData物件
ResultSetMetaData getMetaData()
//
釋放ResultSet物件資源
void close()
l   ResultSetMetaData介面常用方法,都會丟出SQLException例外:
//
傳回資料表的欄數
int getColumnCount()
//
傳回資料表第i欄的欄名
String getColumnName(int i)
//
傳回資料表第i欄的資料型別
String getColumnTypeName(int i)
l   範例:
package testPackage;
import java.sql.*;
public class test{
    public static void main(String[] args){
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");}
        catch (ClassNotFoundException ce){
            System.out.println("No JDBC Driver: " + ce.getMessage());}
        try{
            Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB ? serverTimezone = UTC", "root", "myPassword");
            //
傳回Statement物件
            Statement sm = cn.createStatement();
           
            //
此程式區段須依資料表內容調整
            //
新增資料表紀錄
            sm.executeUpdate("INSERT INTO testTable (title, content) Values ('testTitle', 'testContent');");
            //
修改資料表紀錄
            sm.executeUpdate("UPDATE testTable SET title = 'testTitle2', content = 'testContent2' WHERE id = 50;");
            //
刪除資料表紀錄
            sm.executeUpdate("DELETE FROM testTable WHERE id = 50;");
            //
查詢資料表紀錄
            ResultSet rs = sm.executeQuery("SELECT * FROM testTable;");
            ResultSetMetaData rsmd = rs.getMetaData();
            for (int i = 1; i <= rsmd.getColumnCount(); i++){
                System.out.print(rsmd.getColumnName(i) + "\t");}
            System.out.println();
            for (int j = 1; j <= rsmd.getColumnCount(); j++){
                System.out.print(rsmd.getColumnTypeName(j) + "\t");}
            System.out.println("\n--------------------------------");
            while (rs.next()){
                System.out.print(rs.getInt(1) + "\t");
                System.out.print(rs.getString(2) + "\t");
                System.out.print(rs.getString(3) + "\t");
                System.out.print(rs.getString(4) + "\n");}
            
            sm.close();
            cn.close();}
        catch (SQLException e){
             System.out.println("Connection Failure: " + e.getMessage());}
    }
}

沒有留言:

張貼留言