📄 table.html
字号:
<li> <a href="#editor">Using Other Editors</a><li> <a href="#renderer">Using Custom Renderers</a><li> <a href="#celltooltip">Specifying Tool Tips for Cells</a><li> <a href="#headertooltip">Specifying Tool Tips for Column Headers</a><li> <a href="#sorting">Sorting and Otherwise Manipulating Data</a><li> <a href="#api">The Table API</a><li> <a href="#eg">Examples that Use Tables</a></ul></blockquote><h3><a name="simple">Creating a Simple Table</a></h3><blockquote><p><center><IMG SRC="../../figures/uiswing/components/SimpleTableDemo.gif" WIDTH="529" HEIGHT="116" ALIGN="BOTTOM" ALT="A snapshot of SimpleTableDemo, which displays a simple table."></center></p>[PENDING: This figure will be updated.]<blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/SimpleTableDemo.jnlp">Run SimpleTableDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#SimpleTableDemo">example index</a>.<li> Click the cell that contains "Snowboarding". <br> The entire first row is selected, indicating that you have selected Mary Campione's data. A special highlight indicates that the "Snowboarding" cell is editable. Generally, you begin editing a text cell by double-clicking it.<li> Position the cursor over "First Name". Now press the mouse button and drag to the right. <br> As you can see, users can rearrange columns in tables.<li> Position the cursor just to the right of a column header. Now press the mouse button and drag to the right or left. <br> The column changes size, and the other columns adjust to fill the remaining space.<li> Resize the window containing the table so that it's bigger than necessary to display the whole table. <br> All the table cells become wider, expanding to fill the extra horizontal space.</ol><hr></blockquote>Here is the code that implementsthe table in<a class="SourceLink" target="_blank" href="examples/SimpleTableDemo.java"><code>SimpleTableDemo.java</code></a>:<blockquote><pre>String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)}, {"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)}, {"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}};JTable table = new JTable(data, columnNames);</pre></blockquote>The <code>SimpleTableDemo</code> example uses one of two <code>JTable</code>constructors that directly accept data:<ul><li> <code>JTable(Object[][] rowData, Object[] columnNames)</code><li> <code>JTable(Vector rowData, Vector columnNames)</code></ul>The advantage of these constructorsis that they're easy to use.However, these constructors also have disadvantages:<ul><li> They automatically make every cell editable.<li> They treat all data types the same (as strings). For example, if a table column has <code>Boolean</code> data, the table can display the data in a check box. However, if you use one of the two <code>JTable</code> constructors listed previously, your <code>Boolean</code> data will be displayed as a string. You can see this difference in the last column of the two previous pictures of tables.<li> They require that you put all of the table's data in an array or vector, which isn't appropriate for some data. For example, if you're instantiating a set of objects from a database, you might want to query the objects directly for their values, rather than copying all their values into an array or vector.</ul>If you want to get around these restrictions,you need to implement your own table model,as described in <a href="#data">Creating a Table Model</a>.</blockquote><h3><a name="show">Adding a Table to a Container</a></h3><blockquote>It's easy to put a table in a<a href="scrollpane.html">scroll pane</a>.You need just one or two lines of code:<blockquote><pre>JScrollPane scrollPane = new JScrollPane(table);table.setPreferredScrollableViewportSize(new Dimension(500, 70));</pre></blockquote>The scroll pane automatically gets the table's header,which displays the column names,and puts it on top of the table.Even when the user scrolls down,the column names remain visible at the top of the viewing area.The scroll pane alsotries to make its viewing areathe same as the table'spreferred viewing size.The previous code snippet sets the table's preferred viewing size with the<code>setPreferredScrollableViewportSize</code> method.<p>If you're using a table without a scroll pane,then you must get the table header componentand place it yourself.For example:<blockquote><pre>container.setLayout(new BorderLayout());container.add(table.getTableHeader(), BorderLayout.PAGE_START);container.add(table, BorderLayout.CENTER);</pre></blockquote></blockquote><h3><a name="width">Setting and Changing Column Widths</a></h3><blockquote>By default, all columns in a tablestart out with equal width,and the columns automatically fill the entire widthof the table.When the table becomes wider or narrower(which might happen when the user resizes the window containing the table),all the column widths change appropriately.<p>When the user resizes a column by draggingits right border,then either other columns must change size,or the table's size must change.By default, the table's size remains the same,and all columns to the right of the drag pointresize to accommodate space added to or removedfrom the column to the left of the drag point.<p>The following figures illustrate the default resizing behavior.[PENDING: These will be updated.]<p><IMG SRC="../../figures/uiswing/components/SimpleTableDemo.gif" WIDTH="529" HEIGHT="116" ALT="SimpleTableDemo"><br><b>Initially, the columns have equal width.</b></p><p><IMG SRC="../../figures/uiswing/components/SimpleTableDemo-resize-0.gif" WIDTH="529" HEIGHT="116" ALT="SimpleTableDemo during resizing"><BR><b>When the user resizes a column,some of the othercolumns must adjust size for the table to stay the same size.</b></p><P><IMG SRC="../../figures/uiswing/components/SimpleTableDemo-resize-1.gif" WIDTH="439" HEIGHT="114" ALT="SimpleTableDemo after the entire table is resized"><br><b>When the entire table is resized,all the columns are resized.</b></p><p>To customize initial column widths,you can invoke <code>setPreferredWidth</code>on each of your table's columns.This sets both the preferred widths of the columns andtheir approximate relative widths.For example, adding the following code to <code>SimpleTableDemo</code>makes its third column bigger than the other columns:<blockquote><pre>TableColumn column = null;for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) { column.setPreferredWidth(100); //sport column is bigger } else { column.setPreferredWidth(50); }}</pre></blockquote>As the preceding code shows,each column in a table is represented by a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableColumn.html"><code>TableColumn</code></a> object.<code>TableColumn</code> supplies getter and setter methodsfor 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 widthsbased on the actual amount of spaceneeded to draw the cells' contents,see the <code>initColumnSizes</code> method in<a class="SourceLink" target="_blank" href="examples/TableRenderDemo.java"><code>TableRenderDemo.java</code></a>.<p>When the user explicitly resizes columns,the columns' <em>preferred</em> widths are set such thatthe user-specified sizes become the columns' new <em>current</em> widths.However, when table itself is resized —typically because the window has resized — the columns' preferred widths do not change.Instead, the existing preferred widthsare used to calculate new column widths to fill the available space.<p>You can change a table's resize behavior by invokingthe <code>setAutoResizeMode</code> method.The method's argumentshould have one of these values(defined as constants in <code>JTable</code>):<dl><dt> <code>AUTO_RESIZE_SUBSEQUENT_COLUMNS</code><dd> The default. In addition to resizing the column to the left of the drag point, adjusts the sizes of all columns to the right of the drag point.<dt> <code>AUTO_RESIZE_NEXT_COLUMN</code><dd> Adjusts only the columns immediately to the left and right of the drag point.<dt> <code>AUTO_RESIZE_OFF</code><dd> Adjusts the table size instead.</dl><p></blockquote><h3><a name="selection">Detecting User Selections</a></h3><blockquote>The following code snippetshows how to detect when the user selects a table row.By default, a table allows the user to select multiple rows —not columns or individual cells —and the selected rows need not be next to each other.Using the<code>setSelectionMode</code> method,the following code specifiesthat only one row at a time can be selected.<blockquote><pre>table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);...//Ask to be notified of selection changes.ListSelectionModel rowSM = table.getSelectionModel();rowSM.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { //Ignore extra messages. if (e.getValueIsAdjusting()) return; ListSelectionModel lsm = (ListSelectionModel)e.getSource(); if (lsm.isSelectionEmpty()) { <em>...//no rows are selected</em> } else { int selectedRow = lsm.getMinSelectionIndex(); <em>...//selectedRow is selected</em> } }});</pre></blockquote>The code is from<a class="SourceLink" target="_blank" href="examples/SimpleTableSelectionDemo.java"><code>SimpleTableSelectionDemo.java</code></a>.SimpleTableSelectionDemo also has code(not included in the preceding snippet)that changes the table's selection orientation.By changing a couple of boolean values,you can make the table allow either column selectionsor individual cell selections,instead of row selections.<p>For more information and examples ofimplementing selection,see <a href="../events/listselectionlistener.html">How to Write a List Selection Listener</a>.</blockquote><h3><a name="data">Creating a Table Model</a></h3><blockquote>As the following figure shows,every table gets its data from an objectthat implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html"><code>TableModel</code></a> interface.<p><center><IMG SRC="../../figures/uiswing/components/8model.gif" WIDTH="380" HEIGHT="67" ALIGN="BOTTOM" ALT="TableDemo"></center></p>[PENDING: This figure might be updated to look more modern.]<p>The <code>JTable</code> constructorused by <code>SimpleTableDemo</code>creates its table model withcode like this:<blockquote><pre>new AbstractTableModel() { public String getColumnName(int col) { return columnNames[col].toString(); } public int getRowCount() { return rowData.length; } public int getColumnCount() { return columnNames.length; } public Object getValueAt(int row, int col) { return rowData[row][col]; } public boolean isCellEditable(int row, int col) { return true; } public void setValueAt(Object value, int row, int col) { rowData[row][col] = value; fireTableCellUpdated(row, col); }}</pre></blockquote>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -