23
swing 基基基

swing 基础二

  • Upload
    bardia

  • View
    60

  • Download
    11

Embed Size (px)

DESCRIPTION

swing 基础二. 本节目标. Look And Feel 了解 MVC 体系结构 常用组件 JComboBox JTextPane JTabel JTree. 可插入的外观和感觉. UIManager 管理外观 setLookAndFeel(String className) SwingUtilities.updateComponentTreeUI(frame); 常用外观: Metal:javax.swing.plaf.metal.MetalLookAndFeel - PowerPoint PPT Presentation

Citation preview

Page 1: swing  基础二

swing 基础二

Page 2: swing  基础二

本节目标

Look And Feel

了解 MVC 体系结构

常用组件JComboBoxJTextPaneJTabelJTree

Page 3: swing  基础二

可插入的外观和感觉

UIManager 管理外观setLookAndFeel(String className)SwingUtilities.updateComponentTreeUI(frame);

常用外观:Metal:javax.swing.plaf.metal.MetalLookAndFeel

Motif :com.sun.java.swing.plaf.motif.MotifLookAndFeel

GTK+:com.sun.java.swing.plaf.gtk.GTKLookAndFeel

Windows:com.sun.java.swing.plaf.windows.WindowsLookAndFeel

Page 4: swing  基础二

MVC(Model-View-Control)体系结构

Swing 胜过 AWT 的主要优势在于 MVC 体系结构的普遍使用。在一个 MVC 用户界面中,存三个通讯对象:模型、视图和控制。模型是指定的逻辑表示法,视图是模型的可视化表示法,而控制则指定了如何处理用户输入。当模型发生改变时,它会通知所有依赖它的视图,视图使用控件指定其相应机制。  为了简化组件的设计工作,在 Swing 组件中视图和控制两部分合为一体。每个组件有一个相关的分离模型和它使用的界面(包括视图和控件)。比如,按钮 JButton 有一个存储其状态的分离模型 ButtonModel 对象。组件的模型是自动设置的,例如一般都使用 JButton 而不是使用 ButtonModel 对象。另外,通过 Model 类的子类或通过实现适当的接口,可以为组件建立自己的模型。把数据模型与组件联系起来用 setModel( ) 方法。

Page 5: swing  基础二

几个基于 MVC 实现的组件

JComboBox   JTextPane

JTable

JTree

Page 6: swing  基础二

JCombobox

ComboBoxModel

定制 ListCellRenderer 绘制单元格

setRenderer(ListCellRenderer cellRenderer)

Page 7: swing  基础二

JComboBox 示例 _1

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class JComboBox4{  String[] s={" 西瓜 "," 苹果 "," 草莓 "," 香蕉 "," 葡萄 "};   public JComboBox4(){  JFrame f=new JFrame("JComboBox");  Container contentPane=f.getContentPane(); JComboBox combo=new JComboBox(s);  combo.setBorder(BorderFactory.createTitledBorder(" 你最喜欢吃哪些水果 ?"));  combo.setRenderer(new ACellRenderer());  combo.setMaximumRowCount(3);  contentPane.add(combo);

f.pack();      f.show();      f.addWindowListener(new WindowAdapter(){   

Page 8: swing  基础二

JComboBox 示例 _2

public void windowClosing(WindowEvent e){      System.exit(0);     }      });       }  public static void main(String[] args){    new JComboBox4();  }} class ACellRenderer extends JLabel implements ListCellRenderer{ ACellRenderer(){  setOpaque(true);   }  public Component getListCellRendererComponent(JList  list,                                                Object value,                                                int index,                                                boolean isSelected,                                                boolean cellHasFocus){

Page 9: swing  基础二

JComboBox 示例 _3

if (value!=null){        setText(value.toString());        setIcon(new ImageIcon(".\\icons\\fruit"+(index+1)+".jpg"));      }        if (isSelected){         setBackground(list.getSelectionBackground());         setForeground(list.getSelectionForeground());       }else{         setBackground(list.getBackground());          setForeground(list.getForeground());      }                                          return this;           }                                                 }

Page 10: swing  基础二

JTextPane 示例 _1import java.awt.Color;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JTextPane;import javax.swing.text.MutableAttributeSet;import javax.swing.text.SimpleAttributeSet;import javax.swing.text.StyleConstants;import javax.swing.text.StyledDocument;import javax.swing.JScrollPane;public class DemoJTextPane2 extends JFrame {

JTextPane jtextPane;MutableAttributeSet center_align, char_style_1, char_style_2;public DemoJTextPane2() {

jtextPane = new JTextPane();JScrollPane scroll = new JScrollPane(jtextPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);StyledDocument mydocument=jtextPane.getStyledDocument();center_align=new SimpleAttributeSet();

Page 11: swing  基础二

JTextPane 示例 _2char_style_1=new SimpleAttributeSet();char_style_2=new SimpleAttributeSet();StyleConstants.setAlignment(center_align,

StyleConstants.ALIGN_CENTER);StyleConstants.setFontFamily(char_style_1,"Timer");StyleConstants.setFontSize(char_style_1,20);StyleConstants.setForeground(char_style_1,Color.red);StyleConstants.setFontFamily(char_style_2,"Serif");StyleConstants.setFontSize(char_style_2,14);StyleConstants.setForeground(char_style_2,Color.BLUE);try{

jtextPane.setCaretPosition(mydocument.getLength()); // 设置插入位置

jtextPane.insertIcon(new ImageIcon(this.getClass().getResource("images/qqicon.gif")));

mydocument.insertString(mydocument.getLength(),"\n\nfirst\n\n",char_style_1);

}catch(Exception e){}

Page 12: swing  基础二

JTextPane 示例 _3try{

mydocument.insertString(mydocument.getLength(),"second\n\n",char_style_2);jtextPane.setCaretPosition(mydocument.getLength()); //

设置插入位置jtextPane.insertIcon(new ImageIcon(this.getClass().getRe

source("images/qqicon.gif")));}catch(Exception e){}getContentPane().add(scroll);setSize(400,300);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}public static void main(String args[]){

new DemoJTextPane2();}

}

Page 13: swing  基础二

表格 (JTable)

JTable 构造方法 :JTable(TableModel dm)JTable(object[][]rowData,object[]columnNames)JTable(Vector rowData,Vector columnNames)

JTable 类常用的方法有:getModel() // 获得表格的数据来源对象getSelectedRow() // 获得选中的行数

Page 14: swing  基础二

表格 (JTable) 表格是 Swing 新增加的组件,主要功能是把数据以二维表格的形式显示出来。使用表格,依据 M-V-C 的思想,最好先生成一个 MyTableModel 类型的对象来表示数据,这个类是从 AbstractTableModel 类中继承来的,其中有几个方法是一定要重写,例如 getColumnCount , getRowCount , getColumnName , getValueAt 。因为 JTable 会从这个对象中自动获取表格显示所必需的数据,AbstractTableModel 类的对象负责表格大小的确定(行、列)、内容的填写、赋值、表格单元更新的检测等等一切跟表格内容有关的属性及其操作。 JTable 类生成的对象以该 TableModel 为参数,并负责将 TableModel 对象中的数据以表格的形式显示出来。

Page 15: swing  基础二

JTable 示例 _1import javax.swing.table.AbstractTableModel;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class DemoJTableModel2 implements ActionListener {

JTable t = null;public DemoJTableModel2() {

JFrame f = new JFrame("DataModel");JButton b1 = new JButton(" 数学老师 ");b1.addActionListener(this);JButton b2 = new JButton(" 学生阿呆 ");b2.addActionListener(this);JPanel panel = new JPanel();panel.add(b1);panel.add(b2);t = new JTable(new MyTableModel2_1(1));t.setPreferredScrollableViewportSize(new Dimension(550, 30));JScrollPane s = new JScrollPane(t);f.getContentPane().add(panel, BorderLayout.NORTH);

Page 16: swing  基础二

JTable 示例 _2f.getContentPane().add(s, BorderLayout.CENTER);f.pack();f.setVisible(true);f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {

System.exit(0);}});

}public void actionPerformed(ActionEvent e) {

if (e.getActionCommand().equals(" 学生阿呆 "))t.setModel(new MyTableModel2_1(1));if (e.getActionCommand().equals(" 数学老师 "))t.setModel(new MyTableModel2_1(2));t.revalidate();

}public static void main(String args[]) {

new DemoJTableModel2();}

}

Page 17: swing  基础二

JTable 示例 _3class MyTableModel2_1 extends AbstractTableModel {

Object[][] p1 = { { " 阿呆 ", "1234", new Integer(66), new Integer(50),new Integer(11

6), new Boolean(false), new Boolean(false) }};String[] n1 = { " 姓名 ", " 学号 ", " 语文 ", " 数学 ", " 总分 ", " 及格 ", " 作弊 " };Object[][] p2 = {

{ " 阿呆 ", "1234", new Integer(50), new Boolean(false),new Boolean(false), "01234" },{ " 阿瓜 ", "1235", new Integer(75), new Boolean(true),new Boolean(false), "05678" }

};String[] n2 = { " 姓名 ", " 学号 ", " 数学 ", " 及格 ", " 作弊 ", " 电话 " };int model = 1;public MyTableModel2_1(int i) {

model = i;}public int getColumnCount() {

if (model == 1)return n1.length;

else

Page 18: swing  基础二

JTable 示例 _4

return n2.length;}public int getRowCount() {

if (model == 1) return p1.length;else return p2.length;

}public String getColumnName(int col) {

if (model == 1) return n1[col];else return n2[col];

}public Object getValueAt(int row, int col) {

if (model == 1) return p1[row][col];else return p2[row][col];

}public Class getColumnClass(int c) {

return getValueAt(0, c).getClass();}

}

Page 19: swing  基础二

JTree 示例 _1import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.tree.*;public class DemoJTree1 extends JPanel {

String[][] data = { { "Colors", "Red", "Blue", "Green" },{ "Flavors", "Tart", "Sweet", "Bland" },{ "Length", "Short", "Medium", "Long" },{ "Volume", "High", "Medium", "Low" },{ "Temperature", "High", "Medium", "Low" },{ "Intensity", "High", "Medium", "Low" } };

static int i = 0; // I 用于统计按钮点击的次数DefaultMutableTreeNode root, child, targetNode;JTree tree;DefaultTreeModel model;public DemoJTree1() {

setLayout(new BorderLayout());// 根节点进行初始化root = new DefaultMutableTreeNode("root");

Page 20: swing  基础二

JTree 示例 _2// 树进行初始化,其数据来源是 root 对象tree = new JTree(root);DefaultTreeCellRenderer dtcr=new DefaultTreeCellRenderer();dtcr.setBackgroundSelectionColor(Color.ORANGE);tree.setCellRenderer(dtcr);// 把滚动面板添加到 Trees 中add(new JScrollPane(tree));// 获得数据对象 DefaultTreeModelmodel = (DefaultTreeModel) tree.getModel();// 按钮 test 进行初始化JButton test = new JButton("Press me");// 按钮 test 注册监听器test.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {if (i < data.length) {// 按钮 test 点击的次数小于 data 的长度child = new Branch(data[i++]).node();// 生成子节点targetNode = (DefaultMutableTreeNode)

Page 21: swing  基础二

JTree 示例 _3tree.getLastSelectedPathComponent();if (targetNode == null)

targetNode = root;model.insertNodeInto(child, targetNode, 0);// 把 child 添加到 chosen}

}});test.setBackground(Color.blue);// 按钮 test 设置背景色为蓝色test.setForeground(Color.white);// 按钮 test 设置前景色为白色JPanel p = new JPanel();// 面板 p 初始化p.add(test);// 把按钮添加到面板 p 中add(p, BorderLayout.SOUTH);// 把面板 p 添加到 Trees 中

}public static void main(String args[]) {

Page 22: swing  基础二

JTree 示例 _4

JFrame jf = new JFrame("JTree demo");jf.getContentPane().add(new DemoJTree1(), B

orderLayout.CENTER);// 把 Trees 对象添加到 JFrame 对象的中央jf.setSize(200, 500);jf.setVisible(true);

}}class Branch {

DefaultMutableTreeNode r;public Branch(String[] data) {

r = new DefaultMutableTreeNode(data[0]);// 给节点 r 添加多个子节点for (int i = 1; i < data.length; i++) {r.add(new DefaultMutableTreeNode(data[i]));} }

public DefaultMutableTreeNode node() {// 返回节点return r;

}}

Page 23: swing  基础二

Swing 的程序设计Swing 的程序设计一般可按照下列流程进行:    1. 引入 Swing 包    2. 选择 " 外观和感觉 "    3. 设置顶层容器    4. 设置按钮和标签    5. 向容器中添加组件    6. 在组件周围添加边界    7. 进行事件处理