Java Swing sun官方书籍部分翻译

来源:互联网 发布:滚动字幕制作软件 编辑:程序博客网 时间:2024/05/21 09:10

Swing 2 Edito1

1.   Swing的特性

<1> Pluggable Look-and-Feels 可插入的实感外观,可以动态的去替换。

<2> Lightweight Components   轻量级组件

<3> Swing提供更广泛的组件

<4> Swing可以替换它的插入效果.通过替换Border

<5> Swing组件有tooltips

 


 

2.  UIManager.setLookAndFeel(lnfName);

   SwingUtilities.updateComponentTreeUI(frame);

 

JTable学习

1.

JTable(Object[][] rowData, Object[] columnNames)

JTable(Vector rowData, Vector columnNames)

使用以上两个构造函数的不利点:

<1>单元格都可以编辑

<2>By default, all columns in a table startout with equal width, and the columns automatically fill the entire width ofthe table,When the table becomes wider or narrower (which might happen when theuser resizes the window containing the table), all the column widths changeappropriately.

默认,所有的列都是相当的宽度,会自动填充整个表格的宽度.当调整表格的宽度,所有的列会自动的改变宽度.

2.
TableColumn column = null;
for (int i = 0; i < 5; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 2) {
        column.setPreferredWidth(100); //third column is bigger
    } else {
        column.setPreferredWidth(50);
    }
}
 
3.
TableColumn supplies getter and setter methods for the minimum, preferred, and maximum widths of a column, as well as a method for getting the current width. For an example of setting cell widths based on an approximation of the space needed to draw the cells' contents, see the initColumnSizes method in TableRenderDemo.java.
 
4.

User Selections

<1>The user can select a contiguous rangeof rows or an arbitrary set of rows

用户可以选择连续变化的行或者任意的行
 
<2>Row Selection    Column Selection   Cell Selection
 
 
5.
Creating a Table Model 
 
6.
Listening for Data Changes 
 
<1>A table model can have a set of listeners that are notified whenever the table data changes. Listeners are instances of TableModelListener
 
7.
Firing Data Change Events 

Method

Change

fireTableCellUpdated

Update of specified cell.

fireTableRowsUpdated

Update of specified rows

fireTableDataChanged

Update of entire table (data only).

fireTableRowsInserted

New rows inserted.

fireTableRowsDeleted

Existing rows Deleted

fireTableStructureChanged  

Invalidate entire table, both data and structure

 

 

 
 
8.
Concepts: Editors and Renderers 
 
9.
Using Custom Renderers 
<1>You can set a type-specific cell renderer using the JTable method setDefaultRenderer. To specify that cells in a particular column should use a renderer, you use the TableColumn method setCellRenderer. You can even specify a cell-specific renderer by creating a JTable subclass
 
<2>If extending DefaultTableCellRenderer is insufficient, you can build a renderer using another superclass. The easiest way is to create a subclass of an existing component, making your subclass implement the TableCellRenderer interface

 

<3>In the snapshotof TableDialogEditDemo, the renderer used for Favorite Colorcells is a subclass of JLabel called ColorRenderer.Here are excerpts from ColorRenderer.java that show how it isimplemented.

public class ColorRenderer extends JLabel
                           implements TableCellRenderer {
    ...
    public ColorRenderer(boolean isBordered) {
        this.isBordered = isBordered;
        setOpaque(true); //MUST do this for background to show up.
    }
 
    public Component getTableCellRendererComponent(
                            JTable table, Object color,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
        Color newColor = (Color)color;
        setBackground(newColor);
        if (isBordered) {
            if (isSelected) {
                ...
                //selectedBorder is a solid border in the color
                //table.getSelectionBackground().
                setBorder(selectedBorder);
            } else {
                ...
                //unselectedBorder is a solid border in the color
                //table.getBackground().
                setBorder(unselectedBorder);
            }
        }
        
        setToolTipText(...); //Discussed in the following section
        return this;
    }
}

Here is the code from TableDialogEditDemo.java that registers a ColorRendererinstance as the default renderer for all Color data:

table.setDefaultRenderer(Color.class, new ColorRenderer(true));

 

<4>To specify acell-specific renderer, you need to define a JTable subclass thatoverrides the getCellRenderer method. For example, the followingcode makes the first cell in the first column of the table use a customrenderer:

TableCellRenderer weirdRenderer = new WeirdRenderer();
table = new JTable(...) {
    public TableCellRenderer getCellRenderer(int row, int column) {
        if ((row == 0) && (column == 0)) {
            return weirdRenderer;
        }
        // else...
        return super.getCellRenderer(row, column);
    }
};

 

10.

SpecifyingTool Tips for Cells

<1>By default, thetool tip text displayed for a table cell is determined by the cell's renderer.However, sometimes it can be simpler to specify tool tip text by overriding JTable'simplementation of the getToolTipText(MouseEvent) method. Thissection shows you how to use both techniques.

 

<2>To add a tool tip to a cell using its renderer,you first need to get or create the cell renderer. Then, after making sure therendering component is a JComponent, invoke the setToolTipTextmethod on it

 

<3>JTable table = new JTable(new MyTableModel()) {    
    //Implement table cell tool tips.
    public String getToolTipText(MouseEvent e) {
        String tip = null;
        java.awt.Point p = e.getPoint();
        int rowIndex = rowAtPoint(p);
        int colIndex = columnAtPoint(p);
        int realColumnIndex = convertColumnIndexToModel(colIndex);
 
        if (realColumnIndex == 2) { //Sport column
            tip = "This person's favorite sport to "
                   + "participate in is: "
                   + getValueAt(rowIndex, colIndex);
 
        } else if (realColumnIndex == 4) { //Veggie column
            TableModel model = getModel();
            String firstName = (String)model.getValueAt(rowIndex,0);
            String lastName = (String)model.getValueAt(rowIndex,1);
            Boolean veggie = (Boolean)model.getValueAt(rowIndex,4);
            if (Boolean.TRUE.equals(veggie)) {
                tip = firstName + " " + lastName
                      + " is a vegetarian";
            } else {
                tip = firstName + " " + lastName
                      + " is not a vegetarian";
            }
 
        } else { //another column
            //You can omit this part if you know you don't 
            //have any renderers that supply their own tool 
            //tips.
            tip = super.getToolTipText(e);
        }
        return tip;
    }
    ...
}

11

Specifying Tool Tips for ColumnHeaders

<1>You can add a tooltip to a column header by setting the tool tip text for the table's JTableHeader.Often, different column headers require different tool tip text. You can changethe text by overriding the table header's getToolTipText method.Alternately, you can invoke TableColumn.setHeaderRenderer toprovide a custom renderer for the header.

<2>The following codeimplements the tool tips. Basically, it creates a subclass of JTableHeaderthat overrides the getToolTipText(MouseEvent) method so that itreturns the text for the current column. To associate the revised table headerwith the table, the JTable method createDefaultTableHeaderis overridden so that it returns an instance of the JTableHeadersubclass.

protected String[] columnToolTips = {
    null, // "First Name" assumed obvious
    null, // "Last Name" assumed obvious
    "The person's favorite sport to participate in",
    "The number of years the person has played the sport",
    "If checked, the person eats no meat"};
...
 
JTable table = new JTable(new MyTableModel()) {
    ...
 
    //Implement table header tool tips.
    protected JTableHeader createDefaultTableHeader() {
        return new JTableHeader(columnModel) {
            public String getToolTipText(MouseEvent e) {
                String tip = null;
                java.awt.Point p = e.getPoint();
                int index = columnModel.getColumnIndexAtX(p.x);
                int realIndex = 
                        columnModel.getColumn(index).getModelIndex();
                return columnToolTips[realIndex];
            }
        };
    }
};

 

12

Sorting and Filtering

<1>Table sorting andfiltering is managed by a sorter object. The easiest way to provide asorter object is to set autoCreateRowSorter bound property to true:

JTable table = new JTable();

table.setAutoCreateRowSorter(true);

This action defines a row sorter that is an instance of javax.swing.table.TableRowSorter. This provides a tablethat does a simple locale-specific sort when the user clicks on a columnheader. This is demonstrated in TableSortDemo.java, as seen in this screen shot:


To have more control over sorting, you can construct an instance ofTableRowSorter and specify that it is the sorter object for your table.

TableRowSorter<TableModel> sorter

    = newTableRowSorter<TableModel>(table.getModel());

table.setRowSorter(sorter);

 

<2>When a table uses asorter, the data the users sees may be in a different order than that specifiedby the data model, and may not include all rows specified by the data model.The data the user actually sees is known as the view, and has its ownset of coordinates. JTable provides methods that convert from model coordinatesto view coordinates — convertColumnIndexToView and convertRowIndexToView — and that convert from viewcoordinates to model coordinates — convertColumnIndexToModel and convertRowIndexToModel.


NOTE: When using asorter, always remember to translate cell coordinates

 

13

Using a Combo Box as an Editor

14

Using Other Editors

<1>What if you want tospecify an editor other than a text field, check box, or combo box? As DefaultCellEditordoes not support other types of components, you must do a little more work. Youneed to create a class that implements the TableCellEditor interface. The AbstractCellEditor class is a good superclassto use. It implements TableCellEditor's superinterface, CellEditor, saving you the trouble ofimplementing the event firing code necessary for cell editors

 

<2>Your cell editor class needs to define at leasttwo methods — getCellEditorValue and getTableCellEditorComponent.The getCellEditorValue method, required by CellEditor,returns the cell's current value. The getTableCellEditorComponentmethod, required by TableCellEditor, should configure and returnthe component that you want to use as the editor.

<3>Here is the code, taken from ColorEditor.java, that implements the celleditor.

public class ColorEditor extends AbstractCellEditor
                         implements TableCellEditor,
                                    ActionListener {
    Color currentColor;
    JButton button;
    JColorChooser colorChooser;
    JDialog dialog;
    protected static final String EDIT = "edit";
 
    public ColorEditor() {
        button = new JButton();
        button.setActionCommand(EDIT);
        button.addActionListener(this);
        button.setBorderPainted(false);
 
        //Set up the dialog that the button brings up.
        colorChooser = new JColorChooser();
        dialog = JColorChooser.createDialog(button,
                                        "Pick a Color",
                                        true,  //modal
                                        colorChooser,
                                        this,  //OK button handler
                                        null); //no CANCEL button handler
    }
 
    public void actionPerformed(ActionEvent e) {
        if (EDIT.equals(e.getActionCommand())) {
            //The user has clicked the cell, so
            //bring up the dialog.
            button.setBackground(currentColor);
            colorChooser.setColor(currentColor);
            dialog.setVisible(true);
 
            fireEditingStopped(); //Make the renderer reappear.
 
        } else { //User pressed dialog's "OK" button.
            currentColor = colorChooser.getColor();
        }
    }
 
    //Implement the one CellEditor method that AbstractCellEditor doesn't.
    public Object getCellEditorValue() {
        return currentColor;
    }
 
    //Implement the one method defined by TableCellEditor.
    public Component getTableCellEditorComponent(JTable table,
                                                 Object value,
                                                 boolean isSelected,
                                                 int row,
                                                 int column) {
        currentColor = (Color)value;
        return button;
    }
}

As you can see, the code is pretty simple. The only partthat is a bit tricky is the call to fireEditingStopped at the endof the editor button's action handler. Without this call, the editor wouldremain active, even though the modal dialog is no longer visible. The call to fireEditingStoppedlets the table know that it can deactivate the editor, letting the cell behandled by the renderer again.

15

Using an Editor to Validate User-EnteredText

16

Printing

 

JTextComponent

 



 

 

LookAndFeel

The abstract base class from which all the differentL&Fs extend. It defines a number of static convenience methods, as well assome abstract methods required by every L&F.

UIDefaults

An L&F is responsible for defining a set of defaultproperties. UIDefaults is a Hashtable subclass that holds these properties. Theproperties include UIClassID to ComponentUI subclass mappings (e.g.,"TreeUI" to MetalTreeUI) as well as lower-level defaults, such ascolors and fonts.

UIDefaults.ActiveValue andUIDefaults.LazyValue

These inner interfaces of UIDefaults enable someoptimizations for resource values.

UIResource

This is an empty interface (like Serializable orCloneable) used to tag property values. It allows values defined by the L&Fto be distinguished from values set by the user, as described in Section26.3.5 later in this chapter.

UIManager

If you've ever changed the L&F of a Swing program atruntime, you're probably already familiar with this class. UIManager isresponsible for tracking a global view of the L&Fs available in anapplication. It keeps track of the currently installed L&F and provides amechanism to change the L&F. All of its methods are static, but it does providea mechanism that allows multiple applets within a single virtual machine to usedifferent L&Fs.

UIManager.LookAndFeelInfo

This inner class is used to describe available L&Fswithout actually having to load the L&F classes. UIManager uses this classto provide a list of available L&Fs.

ComponentUI

This is the base class common to all UI delegates. Itdefines all of the methods related to painting and sizing that the differentdelegate subclasses must implement.

JComponent

You're certainly familiar with this class by nowt's the base class for all of the Swing components. Weinclude it in this diagram to show that at any time, each JComponent has areference to a single ComponentUI. ComponentUI objects may, however, be sharedby multiple components. JComponent was covered in gory detail back in Chapter3.