基本組件
先使用如下代碼,設置基本窗口:
import javax.swing.*;
import java.awt.*;
public class Example3{
public static void main(String[] args){
JFrame win = new JFrame("基本組件");
win.setBounds(200,50,360,640);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = win.getContentPane();
JPanel pan = new JPanel();
//......
//pan.add(xxx);
}
}
注意:使用命令行窗口執行java程序時,若程序中存在中文字符會導致顯示亂碼,此時可用utf-8的編碼來處理,具體操作如下:
1.標籤(JLable)
最簡單的組件,用於顯示單行靜態文本。用戶只能查看其內容而不能對其進行修改。標籤類沒有事件響應。
構造方法:
- JLabel lab = new JLable(“Hello world!!!”);
標籤內容一般不需要改變,但也可以使用setText和setIcon方法進行改變
2.按鈕(JButton)
構造方法:
- JButton button = new JButton(“登陸”);
常用方法:
- void setActionCommand(String);
- void addActionListener(ActionListener);
3.文本框(JTextField):單行文本
構造方法:
- JTextField tf = new JTextField(“aa”,8);
其他方法:
- public String getText()
- public String getSelectedText()
- public void setText(String s)
- public void setEchoChar(char c)
- public void setEditable(boolean b)
4.文本區(JTextArea):多行文本
構造方法:
- JTextArea ta = new JTextArea(“ab”,8,7);
其他方法:
- public getCaretPosition()
- public void insert(String str,int pos)
- public String getSelectedText()
- public int getSelectionStart()
- public int getSelectionEnd()
- public void replaceRange(String str,int start,int end)
應用中經常將文本區對象放入一個滾動窗格中,以使用滾動條功能,方法爲:
JTextArea ta = new JTextArea(int height,int weight);
JScrollPane sp = new JScrollPane(ta);
5.單選按鈕(JRadioButton)
構造方法(與JButton類似):
- JradioButton rbutt = new JradioButton(“男”,“true”);
常用方法:
- void addActionListener(ActionListener);
- void addItemListener(ItemListener);
- boolean isSelected();
- void setSelected(boolesan);
使用單選按鈕時經常用到ButtonGroup類,如下:
創建按鈕對象:
- ButtonGroup bg = new ButtonGroup();
創建若干單選按鈕對象:
- JRadioButton b1 = new JRadioButton(“x”);
- JRadioButton b2 = new JRadioButton(“y”);
將各單選按鈕添加到按鈕組中:
- bg.add(b1);
- bg,add(b2);
將單選按鈕添加到其他容器中:
- 容器對象.add(b1);
- 容器對象.add(b2);
注:按鈕組維持只有一個單選按鈕處於選擇狀態
6.複選框(JCheckbox)
構造方法:
- JCheckbox() 創建一個沒有標籤的複選框
- JCheckbox(Icon icon) 創建一個有圖標的複選框
- JCheckbox(Icon icon,boolean sele) 創建一個有圖標icon的複選框,初始狀態爲sels
- JCheckbox(String s) 創建一個有標籤的複選框
- JCheckbox(String s,boolean b) 創建一個有標籤的複選框,參數b設置初始狀態
- JCheckbox(String str,Icon icon) 創建一個有str文字及圖標icon的複選框
- JCheckbox(String str,Icon icon,boolean sele)創建一個有str文字及圖標icon的複選框,初始狀態爲sele
常用方法:
- isSelected():返回複選框按鈕的狀態,返回類型是boolean。若放回true,則表示該按鈕處於選中狀態;否則處於未選中狀態
- setSelected(boolean state):設置複選按鈕的狀態
7.列表框(JList)
構造方法:
- String ss[] = {“red”,“green”,“blue”};
- JList< String > list1 = new JList< String >(ss);
- JList< String > list2 = new JList< String >(Vector);
其他常用方法:
-
void addListSelecttionListener(…);
-
void setVisibleRowCount(int);
-
void setSelectionMode(int);
//取值如下(在ListSelectionModel中定義)
SINGLE_SELECTION
SINCLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION(默認) -
int getSelectedIndex();
-
int[] getSelectedIndices();
-
Object getSelectedValue();
-
Object[] getSelectedValue();
8.下拉列表(JComboBox)
構造方法:
- String ss[] = {“red”,“green”,“blue”};
- JComboBox< String > cb1 = new JComboBox< String >(ss);
- JComboBox< String > cb2 = new JComboBox< String >(Vector);
常用方法:
- addItem() 添加一個項目到JComboBox
- get/setSelectedIndex() 獲取/設置JComboBOX中選中項目的索引
- get/setSelectedItem() 獲取/設置選中的對象
- removeAllItems() 從JComboBox刪除所有對象
- removeItem() 從JComboBox刪除特定對象
- setEditable 把一個組合框設置爲可編輯的
9.密碼域(JPasswordField)
構造方法(類似於JTextField)
- JPasswordField tf = new JPasswordField(“aa”,8);
常用方法:
- void addActionListener(ActionListener);
- char[] getPassword();
- void setEchoChar(char);
- char getEchoChar();
10.滑動條(JSlider)
構造方法:
- JSlider slider = new JSlider(JSlider.HORIZONTAL,0,100,10);
常用方法:
- void addChangeListener(ChangeListener);
- void setValue(int);
- int getValue();
- void setMajorTickSpacing(int);
- void setMinorTickSpacing(int);
- void setPaintTicks(boolean); //false
- void setPaintLabels(boolean); //false
- void setPaintTrack(boolean); //true
- void setSnapToTicks(boolean); //false
11.進度條(JProgressBar)
構造方法:
- JProgressBar(int,int,int);
- JProgressBar pb = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
常用方法:
- void addChangeListener(ChangListener);
- void setValue(int); //設置當前值
- void setString(String); //設置顯示的字符串
- void setStringPainted(boolean); //設置是否顯示字符串,默認爲false
- void setBorderPainted(boolean); //設置是否顯示邊框,默認爲true
12.文件選擇器(JFileChooser)
構造方法:
- JFileChooser fc1,fc2; //聲明兩個對象變量
- fc1 = new JFileChooser(); //使用系統默認目錄
- fc2 = new JFileChooser(“d:\java”);
顯示方法:
- int showOpenDialog(Component);
- int showSaveDialog(Component);
//分別用於顯示標準的打開和保存對話框
//參數Component指定對話框依附的父組件
//返回值:APPROVE_OPTION 選擇了確認
CANCEL_OPTION 選擇了取消
ERROR_OPTION 出現了錯誤
其他常用方法:
- void setCurrentDirectory(File);
- void setMultiSelectionEnabled(boolean);
- File getSelectedFile();
- File[] getSelectedFiles();
- File getCurrentDirectory();
- String getName(File):
//取得文件/目錄名稱,不含路徑,可用File類的getAbsolutePath()方法獲取完整路徑 - void setFileSelectionMode(int);
//FILES_ONLY 只能選擇文件(默認)
DIRECTORIES_ONLY 只能選擇目錄
FILES_AND_DIRECTORIES 文件和目錄都可選 - void setFileFilter(FileFilter);
13.顏色選擇器(JColorChooser)
顯示方法:
使用JColorChooser提供的類方法showDialog
static Color showDialog(
Component, //父組件
String, //標題
Color //初始顏色值
);
//返回值:新選擇的顏色值Color
示例:
- Color c = JColorChooser.showDialog(this,“請選擇顏色”,Color.red);
//得到顏色對象c後,即可在需要的地方使用
14.對話框(JOptionPane)
Confirm對話框:
int showConfirmDialog(Component,Object);
//顯示含有Yes、No、Cancel按鈕的確認框
//參數:父組件,顯示信息
//返回值:
YES_OPTION 是
NO_OPTION 否
CANCEL_OPTION 撤銷
OK_OPTION 確認
CLOSED_OPTION 關閉
Input對話框:
String showInputDialog(Component,Object);
//參數:父組件,顯示信息
//返回值:
選擇確認後返回輸入的字符串
選擇取消或關閉後返回null
Message對話框:
- void showMessageDialog(Component,Object);
//參數:父組件,顯示信息
//沒有返回值,只是用來顯示一些信息
Option對話框:
int showOptionDialog(
Component, //父組件
Object, //顯示信息
String, //標題
int, //標準選項按鈕組類型
int, //標準信息圖標類型
Icon, //自定義信息圖標
Object[], //自定義選項按鈕組
Object //自定義默認的選項按鈕
);
15.微調器(JSpinner)
構造方法:
- JSpinner spinner = new JSpinner();
常用方法:
- void addChangeListener(ChangeListener);
- void setValue(Object);
- Object getValue();
- Object getNextValue();
- Object getPreviousValue();
16.計時器(Timer)
構造方法:
- Timer(int,ActionListener);
- Timer timer = new Timer(100,this);
常用方法:
- void start();
- void stop();
- void restar();
- void setDelay(int);
- void setRepeats(boolean);
- boolean isRunning();
17.組件的邊框設置邊框(Border)
創建邊框(使用BorderFactory類的類方法)
- Border border1 = BorderFactory.createLineBorder(Color,int);
//創建一個具有指定顏色和寬度的線邊框 - Border border2 = BorderFactory.createTitleBorder(String);
//創建一個新標題邊框,採用默認設置,並指定了標題文本 - Border border3 = BorderFactory.createLoweredBevelBorder();
//創建一個具有凹出斜面邊緣的邊框 - Border border4 = BorderFactory.createRaisedBorder();
//創建一個具有凸出斜面邊緣的邊框 - Border border5 = BorderFactory.createEtchedBevelBorder();
//創建一個具有“浮雕化”外觀效果的邊框,將組件的當前背景色用於突出顯示和陰影顯示
使用setBorder(border)方法是在組件的邊框
18.組件的分隔線(JSeparator)設置
構造方法:
- JSeparator separator1 = new JSeparator(); //默認水平
- JSeparator separator2 = new JSeparator(JSeparator.HORIZONTAL);
- JSeparator separator3 = new JSeparator(JSeparator.VERTICAL);
使用add(JSeparator)方法加到合適的位置
19.組件的顏色設置
設置顏色:
默認情況下,Java使用RGB(紅/綠/藍三基色,取值範圍[0,255])顏色描述系統
描述顏色的類是java.awt.Color
顏色對象的創建:
- Color c1 = new Color(0,0,255);
- Color c2 = new Color.BLACK; //Color.black
直接使用Color類中定義的標準顏色常量 - Color c3 = JColorChooser.showDialog(Component,String,Color);
有Color對象後,可使用:
- setForeground(Color); //設置組件的前景色
- setBackground(Color); //設置組件的背景色
20.組件的字體設置
字體類:java.awt.Font
字體對象的創建:
- Font(String name,int style,int size);
//名稱,如“隸書”
//風格,取值有PLAIN,BOLD,ITALIC
//大小,如 24,38
設置組件的字體:
- setFont(Font);
21.組件的光標設置
光標類:java.awt.Cursor
光標對象的獲取:
- Cursor.getPredefinedCursor(int);
//如:DEFAULT_CURSOR、HAND_CURSOR、WAIT_CURSOR、TEXT_CORSOR、CROSSHAIR_CURSOR
設置組件的光標:
- setCursor(Cursor.HAND_CURSOR);
22.中間容器的使用
JPanel
創建對象:
- JPanel p = new JPanel();
默認佈局爲FlowLayout,可以改變,如
- p.setLayout(new GridLayout(2,3));
添加組件:
- p.add(組件對象);
JScrollPane
- JTextArea ta = new JTextArea(50,50);
- JScrollPane sp = new JScrollPane(ta);
JSplitPane
- JTextArea ta = new JTextArea(50,50);
- JPanel p = new JPanel();
- JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_APLIT,ta,p);
另一種方式:
- JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,ta,p);
JTabbedPane
- JTabbedPane tp = new JTabbedPane();
- tp.setTabPlacement(int);
- tp.addChangeListener(ChangeListener);
- JPanel p = new JPanel();
- tp.addTab(“p”,p);
- tp.removeTabAt(0);
- int n = tp.getTabCount();
- JInternalFrame
根據上面介紹的基本組件,在同一頁面實現:
import javax.swing.*;
import java.awt.*;
public class Example3{
public static void main(String[] args){
JFrame win = new JFrame("基本組件");
win.setBounds(200,50,360,640); //設置窗口位置和大小
win.setVisible(true); //設置窗口可見
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設置關閉窗口時退出程序
Container con = win.getContentPane();
JPanel pan = new JPanel();
JLabel l_name = new JLabel("姓名"); //設置文本
pan.add(l_name);
JTextField tf_name = new JTextField(26); //設置文本框長度
pan.add(tf_name);
JLabel l_ma = new JLabel("密碼");
pan.add(l_ma);
JPasswordField password = new JPasswordField(26);
password.setEchoChar('*'); //設置密碼的隱形顯示
pan.add(password);
JLabel l_sex = new JLabel("性別");
pan.add(l_sex);
JRadioButton male = new JRadioButton("男",true); //設置單選按鈕
JRadioButton female = new JRadioButton("女");
ButtonGroup group = new ButtonGroup();
group.add(male);
group.add(female);
pan.add(male);
pan.add(female);
JLabel l_hobby = new JLabel("愛好");
JCheckBox[] hobby = {new JCheckBox("音樂"),new JCheckBox("書法"),new JCheckBox("繪畫")}; //設置多選按鈕
pan.add(l_hobby);
pan.add(hobby[0]);
pan.add(hobby[1]);
pan.add(hobby[2]);
JLabel l_course = new JLabel("選課");
pan.add(l_course);
String[] coursesNames = {"Java","Python","Ruby","Go","C++","數據結構","操作系統","網絡原理","計算機系統概論"};
JList<String> course; //設置列表框
course = new JList<String>(coursesNames);
pan.add(course);
JLabel l_depar = new JLabel("院系");
pan.add(l_depar);
String[] departmentNames = {"計科","網絡工程","物聯網","電子信息工程"};
JComboBox<String> department = new JComboBox<String>(departmentNames); //設置複選框
department.setEditable(false); //設置組合框不可編輯
pan.add(department);
JLabel l_lb = new JLabel("年齡");
pan.add(l_lb);
JSpinner jsp = new JSpinner(); //添加年齡微調器
jsp.setValue(new Integer(20));
pan.add(jsp);
con.add(pan);
JLabel l_jf = new JLabel("滑滑滑滑滑動條");
pan.add(l_jf);
JSlider addition = new JSlider(JSlider.HORIZONTAL,0,100,50); //設置滑動條
addition.setMajorTickSpacing(10);
addition.setMinorTickSpacing(5);
addition.setPaintTicks(true);
addition.setPaintLabels(true);
addition.setSnapToTicks(true);
pan.add(addition);
JButton b_sub = new JButton("確認"); //設置按鈕
pan.add(b_sub);
JButton b_save = new JButton("保存");
pan.add(b_save);
JTextArea ta = new JTextArea(10,30); //設置爲本區
JScrollPane sp = new JScrollPane(ta);
pan.add(sp);
JProgressBar progbar = new JProgressBar(JProgressBar.HORIZONTAL,0,100); //設置進度條
progbar.setStringPainted(true);
pan.add(progbar);
}
}