⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 table.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 5 页
字号:
As the preceding code shows,implementing a table model can be simple.Generally, you implement your table model in a subclass of the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html"><code>AbstractTableModel</code></a> class.<p>Your model might hold its datain an array, vector, or hash map,or it might get the data from an outside source such as a database.It might even generate the data at execution time.<p>Here again is a picture of a tableimplemented by <code>TableDemo</code>(which you can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableDemo.jnlp">run</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>) that has a custom table model:<p><center><IMG SRC="../../figures/uiswing/components/TableDemo.gif" WIDTH="528" HEIGHT="120" ALIGN="BOTTOM" ALT="A snapshot of TableDemo. Again."></center></p>[PENDING: This figure will be updated.]<p>This table is different from the <code>SimpleTableDemo</code> tablein the following ways:<ul><li> <code>TableDemo</code>'s custom table model,     even though it's simple,     can easily determine the data's type,     helping the <code>JTable</code> display the data in the best format.     <code>SimpleTableDemo</code>'s      automatically created table model, on the other hand,     isn't smart enough to know that the <b># of Years</b> column     contains numbers (which should generally be right aligned     and have a particular format).     It also doesn't know that the <code>Vegetarian</code> column     contains boolean values,     which can be represented by check boxes.<li> In <code>TableDemo</code>,     we implemented the custom table model     so that it doesn't let you edit the name columns;     it does, however, let you edit the other columns.     In <code>SimpleTableDemo</code>, all cells are editable.</ul><p>Below is the code from<a class="SourceLink" target="_blank" href="examples/TableDemo.java"><code>TableDemo.java</code></a>that is different from the code in<a class="SourceLink" target="_blank" href="examples/SimpleTableDemo.java"><code>SimpleTableDemo.java</code></a>.Bold font indicates the code that makes this table's modeldifferent from the table model defined automaticallyfor <code>SimpleTableDemo</code>.<blockquote><pre>public TableDemo() {    ...    JTable table = new JTable(new MyTableModel());    ...}class MyTableModel extends AbstractTableModel {    private String[] columnNames = <em>...//same as before...</em>    private Object[][] data = <em>...//same as before...</em>    public int getColumnCount() {        return columnNames.length;    }    public int getRowCount() {        return data.length;    }    public String getColumnName(int col) {        return columnNames[col];    }    public Object getValueAt(int row, int col) {        return data[row][col];    }    <b>public Class getColumnClass(int c) {        return getValueAt(0, c).getClass();    }</b>    /*     * Don't need to implement this method unless your table's     * editable.     */    public boolean isCellEditable(int row, int col) {        //Note that the data/cell address is constant,        //no matter where the cell appears onscreen.        <b>if (col < 2) {            return false;        } else {            return true;        }</b>    }    /*     * Don't need to implement this method unless your table's     * data can change.     */    public void setValueAt(Object value, int row, int col) {        data[row][col] = value;        fireTableCellUpdated(row, col);    }    ...}</pre></blockquote></blockquote><h3><a name="modelchange">Detecting Data Changes</a></h3><blockquote>A table and its model automatically detectwhenever the user edits the table's data.However, if the data changes for another reason,you must take special steps to notify the tableand its model of the data change.Also, if you don't implement a table model,as in <code>SimpleTableDemo</code>,then you must take special stepsto find out when the user edits the table's data.<p>An example of updating a table's datawithout directly editing itis in the BINGO application.The BINGO application, which is presented in<font color=red>[PENDING: The Bingo example has been removed.]</font>has a table that displays some informationabout each user who is signed up to play the game.When a new user signs up to play BINGO,the table needs to add a new row for that user.More precisely,the table model needs to getthe data for the new user,and then the table model needs to tell the tableto display the new data.<p>To notify the table model about a new user,the BINGO applicationinvokes the table model's <code>updatePlayer</code> method.You can see the code for that method in<font color=red>[PENDING: The Bingo example has been removed.]</font>which contains the implementation of the table model.The <code>updatePlayer</code> method records the new user's dataand fires a table-model event.Because every table listens for table-model eventsfrom its model,the user-information table automatically detects the changeand displays the new data.<p>To fire the table-model event,the model invokes the <code>fireTableRowsInserted</code> method,which is defined by the <code>AbstractTableModel</code> class.Other <code>fire<em>Xxxx</em></code> methods that<code>AbstractTableModel</code> defines are<code>fireTableCellUpdated</code>,<code>fireTableChanged</code>,<code>fireTableDataChanged</code>,<code>fireTableRowsDeleted</code>,<code>fireTableRowsInserted</code>,<code>fireTableRowsUpdated</code>, and<code>fireTableStructureChanged</code>.<p>If you have a class such as <code>SimpleTableDemo</code>that isn't a table or table model,but needs to react to changes in a table model,then you need to do something specialto find out when the user edits the table's data.Specifically, you need to register a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/event/TableModelListener.html"><code>TableModelListener</code></a> on the table model.Adding the bold code in the following snippetmakes <code>SimpleTableDemo</code>react to table data changes.<blockquote><pre><b>import javax.swing.event.*;import javax.swing.table.TableModel;</b>public class SimpleTableDemo ... <b>implements TableModelListener </b>{    ...    public SimpleTableDemo() {        ...        <b>table.getModel().addTableModelListener(this);</b>        ...    }    <b>public void tableChanged(TableModelEvent e) {        int row = e.getFirstRow();        int column = e.getColumn();        TableModel model = (TableModel)e.getSource();        String columnName = model.getColumnName(column);        Object data = model.getValueAt(row, column);        <em>...// Do something with the data...</em></b>    }    ...}</pre></blockquote><p></blockquote><h3><a name="editrender">Concepts: Editors and Renderers</a></h3><blockquote>Before you go on to the next few tasks,you need to understand how tables draw their cells.You might expect each cell in a table to be a component.However, for performance reasons,Swing tables aren't implemented that way.<p>Instead, a single<em>cell renderer</em>is generally used to draw all of the cellsthat contain the same type of data.You can think of the renderer as aconfigurable ink stampthat the table uses tostamp appropriately formatted data onto each cell.When the user starts to edit a cell's data,a <em>cell editor</em>takes over the cell,controlling the cell's editing behavior.<p>For example, each cell in the <b># of Years</b> column in <code>TableDemo</code>contains <code>Number</code> data  &#151;specifically, an <code>Integer</code> object.By default, the cell renderer for a <code>Number</code>-containing columnuses a single <code>JLabel</code> instanceto draw the appropriate numbers, right-aligned,on the column's cells.If the user begins editing one of the cells,the default cell editoruses a right-aligned <code>JTextField</code>to control the cell editing.<p>To choose the renderer that displaysthe cells in a column,a table first determines whether you specifieda renderer for that particular column.(We'll tell you how to specify renderers a bit later.)If you didn't,then the table invokes the table model's <code>getColumnClass</code> method,which gets the data type of the column's cells.Next, the table compares the column's data typewith a list of data types for which cell renderers are registered.This list is initialized by the table,but you can add to it or change it.Currently, tables put the followingtypes of data in the list:<ul><li> <code>Boolean</code> &#151; rendered with a check box.<li> <code>Number</code> &#151; rendered by a right-aligned label.<li> <code>Double</code>, <code>Float</code> &#151; same as      <code>Number</code>,      but the object-to-text translation is performed by a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html"><code>NumberFormat</code></a>      instance      (using the default number format for the current locale).<li> <code>Date</code> &#151; rendered by a label,      with the object-to-text translation performed by a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html"><code>DateFormat</code></a>      instance      (using a short style for the date and time).<li> <code>ImageIcon</code>, <code>Icon</code> &#151;     rendered by a centered label.<li> <code>Object</code> &#151; rendered by a label that displays the object's     string value.</ul><p>Cell editors are chosen using a similar algorithm.<p>Remember that if you let a tablecreate its own model,it uses <code>Object</code>as the type of every column.To specify more precise column types, the table model must definethe <code>getColumnClass</code> method appropriately,as demonstrated by<a class="SourceLink" target="_blank" href="examples/TableDemo.java"><code>TableDemo.java</code></a>.<p>Keep in mind thatalthough renderers determine how each cell or column header looksand can specify its tool tip text,renderers don't handle events.If you need to pick up the events that take place inside a table,the technique you use variesby the sort of event you're interested in:<p><blockquote><table summary="layout" cellspacing=2><tr><th align=left>Situation</th><th align=left>How to Get Events</th><tr valign=top><td>To detect events from a cell that's being edited...</td><td>Use the cell editor (or register a listener on the cell editor).</td></tr><tr valign=top><td>To detect row/column/cell selections and deselections...</td><td>Use a selection listener as described in<a href="#selection">Detecting User Selections</a>.</td></tr><tr valign=top><td>To detect mouse events on a column header...</td><td>Register the appropriate type of <a class="TutorialLink" target="_top" href="../events/mouselistener.html ">mouse listener </a> on the table's <code>JTableHeader</code> object.(See<a class="SourceLink" target="_blank" href="examples/TableSorter.java"><code>TableSorter.java</code></a> for an example.)</td></tr><tr valign=top><td>To detect other events...</td><td>Register the appropriate listeneron the <code>JTable</code> object.</td></tr></table></blockquote><p>The next few sections tell you howto customize display and editingby specifying renderers and editors.You can specify cell renderers and editorseither by column or by data type.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -