很多與AWT類似.
事件處理參考:Java學習筆記--AWT事件處理
1.設計模式:
模型:存儲內容
視圖:顯示內容
控制器:處理用戶輸入·
2. 文本輸入常用組件
2.1 文本域:
JLabel labelname = new JLabel("username");
JTextArea textname = new JTextArea(1,40);//參數也可以為("默認字符",行,列);
JPanel panel = new JPanel();
panel.add(labelname);
panel.add(textname);
如果需要在運行時重新設定列數,需要調用包含這個文本框的容器的revalidate方法,可以重新設定容器的尺寸。
textField.setColumns(10);
panel.revalidate();
2.2 標簽:JLabel
容納文本的組件,沒有任何修飾,不能響應用戶輸入。
可以選擇內容的排列方式,可以用SwingConstants接口中的常量,如LEFT, RIGHT, CENTER, NORTH, EAST.
JLabel labelname = new JLabel("username",SwingConstants.RIGHT);
2.3 密碼域:JPasswordField
JPasswordField(String text , int columns); //創建一個新的密碼域
char[] getPassword() //返回密碼域中的文本
2.4 文本區:
用戶的輸入超過一行是,也可以用JTextArea,
textArea = nwe JTextArea(8,40); //8行40列的文本區
注:用戶不會受限於輸入指定的行列,輸入過長時,文本會滾動。
可以開啟換行特性避免裁剪過長的行 textArea.setLineWrap(true);
2.5 滾動條:
在Swing中,文本區沒有滾動條,需要時可以將文本區插入到滾動窗格中
textArea = new JTextArea(8,40);
JScrollPane scrollPane = new JScrollPane(textArea);
鏈接JScrollPane的使用:http://pan.baidu.com/s/1ntHWVMx
例子
public class MySwingModel {
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(450,450);
frame.setLayout(new BorderLayout(10,10));//設置布局管理器
//////////////////// PART SOUTH ///////////////////////
//每個JButton對象都存儲了一個按鈕模型對象,可以這樣得到它的引用
JButton mbutton = new JButton("我的按鈕");
ButtonModel mode1 = mbutton.getModel();
JPanel panelSouth = new JPanel();//新建面板
panelSouth.add(mbutton); //將按鈕加入面板
/////////////////// PART NORTH/////////////////////////
//指定文本域的行數、列數
JLabel labelname = new JLabel("username",SwingConstants.CENTER);
final JTextArea textname = new JTextArea("默認用戶名,請刪除后輸入用戶名",1,20);
String strpassword = null;
JLabel labelpassword = new JLabel("password",SwingConstants.CENTER);
final JPasswordField textpassword = new JPasswordField(strpassword,40);
//char [] mypassword = textpassword.getPassword();//獲取密碼
JPanel panelNorth = new JPanel();//創建網格布局的面板,添加用戶名、密碼
panelNorth.setLayout(new GridLayout(2,2,10,10));
panelNorth.add(labelname);
panelNorth.add(textname);
panelNorth.add(labelpassword);
panelNorth.add(textpassword);
////////////////// PART CENTER //////////////////////
final JTextArea textwords = new JTextArea(15,40);
textwords.setLineWrap(true);//開啟換行特性,避免文本過長
JScrollPane textscrollPane = new JScrollPane(textwords);//新建滾動窗格,當行數過大時顯示滾動條
////////////////// 設置按鈕響應 ///////////////////////
mbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent mEvent){
String myName = textname.getText();
char[] mypassword = textpassword.getPassword();//獲取密碼
textwords.setText("用戶名:"+myName+"\n密碼:"+new String(mypassword));
}
});
/////////////////////////////////////////////////////
frame.add(panelSouth,BorderLayout.SOUTH); //將面板加入框架
frame.add(panelNorth,BorderLayout.NORTH);
frame.add(textscrollPane,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. 選擇組件
3.1 復選框
復選框需要一個緊鄰它的標簽說明用途
JCheckBox bold = new JCheckBox("bold");
可以使用setSelected方法選定/取消復選框
bold.setSelected(true);
isSelected方法返回每個復選框當前狀態。true/false
兩個復選框可用同一監聽器
bold.addActionListener(listener);
italic.addActionListener(listener);
public class MySwingChoose {
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(450,450);
frame.setLayout(new BorderLayout(10,10)); //設置布局管理器
final JCheckBox bold = new JCheckBox("Bold");
final JCheckBox italic = new JCheckBox("Italic");
final JLabel labelSelect = new JLabel(); //顯示選擇了哪些選項
ActionListener mylistener = new ActionListener(){
public void actionPerformed(ActionEvent e) {
String strIsselect ="";
if(bold.isSelected()==true){
strIsselect+="Bold已選擇";
}if(italic.isSelected()==true){
strIsselect+="Italic已選擇";
}
labelSelect.setText(strIsselect);
}
};
bold.addActionListener(mylistener);
italic.addActionListener(mylistener);
JPanel panel = new JPanel();
panel.add(bold);
panel.add(italic);
panel.add(labelSelect);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3.2 單選按鈕組 JRadioButton
實現單選按鈕組
為單選按鈕組構造一個ButtonGroup對象
將JRadionButton類型的對象添加到按鈕組中
public class MySwingRadio {
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(450,450);
frame.setLayout(new BorderLayout(10,10));//設置布局管理器
//創建單選按鈕組
ButtonGroup mbuttongroup = new ButtonGroup();
//創建單選按鈕
JRadioButton jradioSmall = new JRadioButton("small",false);
JRadioButton jradioMedium = new JRadioButton("medium",false);
JRadioButton jradioLarge = new JRadioButton("large",false);
//將單選按鈕添加到按鈕組
mbuttongroup.add(jradioSmall);
mbuttongroup.add(jradioMedium);
mbuttongroup.add(jradioLarge);
//將按鈕添加到面板
JPanel panel = new JPanel();
panel.add(jradioSmall);
panel.add(jradioMedium);
panel.add(jradioLarge);
//將面板添加到框架,而不是單選按鈕組添加到框架
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
另一種實現方式,(不錯的例子,可以直接設定監聽器)
public class MySwingRadio2 {
private final static int DEFAULT_SIZE = 36;
//創建單選按鈕組
private static ButtonGroup mbuttongroup = new ButtonGroup();
//創建面板
static JPanel panel = new JPanel();
static JLabel mlabel = new JLabel("");
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(450,450);
frame.setLayout(new BorderLayout(10,10));//設置布局管理器
//將單選按鈕添加到按鈕組
addRadioButton("small",8);
addRadioButton("medium",16);
addRadioButton("large",32);
//將面板添加到框架,而不是單選按鈕組添加到框架
frame.add(mlabel,BorderLayout.CENTER);
frame.add(panel,BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void addRadioButton(final String name,final int size){
boolean selected = (size == DEFAULT_SIZE);
//新建單選按鈕
JRadioButton button = new JRadioButton(name,selected);
//將單選按鈕添加到單選按鈕組
mbuttongroup.add(button);
//將單選按鈕添加到面板
panel.add(button);
//設定監聽器,在標簽中顯示點擊的單選 按鈕
ActionListener mylistener = new ActionListener(){
public void actionPerformed(ActionEvent e){
mlabel.setText(name);
}
};
button.addActionListener(mylistener);
}
}

3.3 邊框 Border javax.swing.border
調用BorderFactory的靜態方法創建邊框
BroderFactory.createLineBorder(Border border)
BroderFactory.createCompoundBorder(Border border)
BroderFactory.createTitledBorder(Border border)
所有的方式見javax.swing下面的類BorderFactory
調用JComponent類中setBorder方法將結果邊框添加到組件
Border etched = BorderFactory.createEtchedBorder() Border titled = BorderFactory.createTitledBorder(etched,"A Title") panel.setBorder(titled)
框架可以組合。
示例代碼
public class MySwingText {
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(450,450);
frame.setLayout(new BorderLayout(10,10));//設置布局管理器
JPanel panel = new JPanel();
Border etched = BorderFactory.createEtchedBorder();
Border titled = BorderFactory.createTitledBorder(etched,"A Title");
panel.setBorder(titled);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3.4組合框 JComboBox<>
創建組合框 :
JComboBox<String> faceCombo = new JConboBox<>();
調用setEditable方法讓組合框可編輯
獲取當前選項 :getSelectedItem
若組合框不可編輯,最好調用 : faceCombo.getItemAt(faceCombo.getSelectedIndex())
addItem方法添加選項 : faceCombo.addItem("Serif");
在任意位置插入選項 : faceCombo.insertItemAt("Monospaced",0);
刪除選項:
faceCombo.removeItem("Monospaced");
faceCombo.removeItemAt(0);
示例
UseComboBox.java
public class UseComboBox {
public static void main(String[] args) {
ComboBoxFrame cbframe = new ComboBoxFrame();
cbframe.setVisible(true);
cbframe.setSize(400,400);
cbframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
ComboBoxFrame.java
public class ComboBoxFrame extends JFrame{
private JComboBox<String> faceCombo;
private JLabel label;
private static final int DEFAULT_SIZE =24;
public ComboBoxFrame(){
//添加文字標簽
label = new JLabel("我的標簽文字");
label.setFont(new Font("Serif",Font.PLAIN,DEFAULT_SIZE));
add(label,BorderLayout.CENTER);
//添加組合框
faceCombo = new JComboBox(); //創建組合框
faceCombo.addItem("Serif");//添加條目
faceCombo.addItem("SansSerif");
faceCombo.addItem("MonoSpaced");
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput");
//為組合框設置監聽器
faceCombo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
label.setFont(new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()),
Font.PLAIN,DEFAULT_SIZE));
}
});
//將組合框添加到panel
JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
add(comboPanel,BorderLayout.SOUTH);
pack();
}
}
3.5 滑動條 JSlider
JSlider slider = new JSlider(min,max,initialValue);
4. 菜單
4.1菜單創建
(1) 創建菜單欄 : JMenuBar menubar = new JMenuBar();
(2) 將菜單欄添加到框架上: frame.setJMenuBar(menuBar);
(3) 為每一個菜單建立一個菜單對象: JMenu editMenu = new JMenu("Edit");
(4) 將頂層菜單添加到菜單欄中: menuBar.add(editMenu);
(5) 向(3)中的菜單對象添加菜單項
JMenuItem pasteItem = new JMenuItem("Paste");
editMenu.add(pasteItem);//添加菜單項
editMenu.addSparator();//添加分隔符
JMenu optionMenu = ... ; //a submenu
editMenu.add(optionMenu);可以看到分隔符位於Paste和Read-only菜單項之間
動作監聽
為每個菜單項JMenuItem安裝一個動作監聽器
ActionListener listener = ...;
pasteItem.addActionListener(listener);
可以使用 JMenu.add(String s)方法將菜單項插入到菜單的尾部
editMenu.add("Paste");
ADD方法返回創建的子菜單項,可以采用下列方法獲取它,並添加監聽器:
JMenuItem pasteItem = editMenu.add("Paste");
pasetItem.addActionListener(listener);
在通常情況下,菜單項出發的命令也可以通過其他用戶界面元素(如工具欄上的按鈕)激活。通常,采用擴展抽象類AbstractAction來定義一個實現Action接口的類。這里需要在AbstractAction對象的構造器中指定菜單項標簽並且覆蓋actionPerformed方法來獲得菜單動作處理器。
Action exitAction = new AbstractAction("Edit"){
public void actionPerformed(ActionEvent event){
//動作代碼
System.exit(0);
}
};
然后將動作添加到菜單中
JMenuItem exitItem = fileMenu.add(exitAction);
這個命令利用動作名將一個菜單項添加到菜單中,這個動作對象將作為它的監聽器 。
上面這條語句是下面兩條語句的快捷形式:
JMenuItem exitItem = new JMenuItem(exitAction); fileMenu.add(exitItem);
示例代碼
public class MyJMenu {
public static void main(String[] args) {
JFrame mframe = new JFrame();
JMenuBar menubar = new JMenuBar();//創建菜單欄
//////////////////////// 菜單對象1 //////////////////////////
JMenu editMenu = new JMenu("Edit");//為每一個菜單建立一個菜單對象
menubar.add(editMenu);//將菜單添加到菜單欄
//-- 菜單項1 --//
JMenuItem pasteItem = new JMenuItem("Paste");
editMenu.add(pasteItem);//添加菜單項
editMenu.addSeparator();//添加分隔符
//-- 菜單項2 --//
JMenuItem readonlyItem = new JMenuItem("Read-Only");
editMenu.add(readonlyItem);//添加菜單項
////////////////////////菜單對象2 //////////////////////////
JMenu sourceMenu = new JMenu("Source");
menubar.add(sourceMenu);
editMenu.addSeparator();//添加分隔符
////////////////////////菜單對象3 //////////////////////////
Action exitAction = new AbstractAction("exit"){
public void actionPerformed(ActionEvent event){
//動作代碼
System.exit(0);
}
};
JMenuItem exitItem = editMenu.add(exitAction);
/*
* 上面這條語句是下面兩條語句的快捷形式:
* JMenuItem exitItem = new JMenuItem(exitAction);
* editMenu.add(exitItem);
* */
////////////////////////////////////////////////////////////
mframe.setJMenuBar(menubar);//菜單欄添加到框架上
mframe.setSize(450, 300);
mframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mframe.setVisible(true);
}
}
代碼效果

