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

📄 table.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 5 页
字号:
    }    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(...); <em>//Discussed in the following section</em>        return this;    }}</pre></blockquote>Here is the code from <a class="SourceLink" target="_blank" href="examples/TableDialogEditDemo.java"><code>TableDialogEditDemo.java</code></a> that registers a <code>ColorRenderer</code> instanceas the default renderer for all<code>Color</code> data:<blockquote><pre>table.setDefaultRenderer(Color.class, new ColorRenderer(true));</pre></blockquote><p>The next section shows a couple of examples of using<code>TableColumn</code>'s <code>setCellRenderer</code> method,so we'll skip that for now and show youhow to specify a rendererfor a particular cell. To specify a cell-specific renderer,you need to define a <code>JTable</code> subclassthat overrides the<code>getCellRenderer</code> method.For example,the following code makes the first cellin the first column of the tableuse a custom renderer:<blockquote><pre>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);    }};</pre></blockquote></blockquote><h3><a name="celltooltip">Specifying Tool Tips for Cells</a></h3><blockquote>By default,the tool tip text displayed for a table cellis determined by the cell's renderer.However, sometimes it can be simpler to specify tool tip textby overriding <code>JTable</code>'s implementationof the <code>getToolTipText(MouseEvent)</code> method.This section tells you how to use both techniques.<p>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 the rendering component is a <code>JComponent</code>,invoke the <code>setToolTipText</code> method on it.<p>An example of setting tool tips for cells is inTableRenderDemo,which you can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableRenderDemo.jnlp">run</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.The source code is in<a class="SourceLink" target="_blank" href="examples/TableRenderDemo.java"><code>TableRenderDemo.java</code></a>.  It adds tool tipsto the cells of the <b>Sport</b> columnwith the following code:<blockquote><pre>//Set up tool tips for the sport cells.DefaultTableCellRenderer renderer =        new DefaultTableCellRenderer();<b>renderer.setToolTipText("Click for combo box");</b>sportColumn.setCellRenderer(renderer);</pre></blockquote>Here is a picture of the resulting tool tip:<p>[PENDING: We will put a picture here. It might be cropped to justinclude the relevant cell and its tool tip(along with whatever other cells are between them).]<p>Although the tool tip text in the previous example is static,you can alsoimplement tool tipswhose text changesdepending on the state of the cell or program.Here are a couple ways to do so:<ul><li> Add a bit of codeto the renderer's implementation of the<code>getTableCellRendererComponent</code> method.<li> Override the <code>JTable</code> method <code>getToolTipText(MouseEvent)</code>.</ul><p>An example of adding code to a cell renderer is in<ahref="examples/index.html#TableDialogEditDemo">TableDialogEditDemo</a>(which you can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableDialogEditDemo.jnlp">run</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>).TableDialogEditDemo uses a renderer for colors,implemented in <a class="SourceLink" target="_blank" href="examples/ColorRenderer.java"><code>ColorRenderer.java</code></a>,that sets the tool tip text using the boldface codein the following snippet:<blockquote><pre>public class ColorRenderer extends JLabel                            implements TableCellRenderer {    ...    public Component getTableCellRendererComponent(                            JTable table, Object color,                            boolean isSelected, boolean hasFocus,                            int row, int column) {        Color newColor = (Color)color;        ...        <b>setToolTipText("RGB value: " + newColor.getRed() + ", "                                     + newColor.getGreen() + ", "                                     + newColor.getBlue());</b>        return this;    }}</pre></blockquote>Here is an example of what the tool tip looks like:<p><center><IMG SRC="../../figures/uiswing/components/TableDialogEditDemo-tooltip.gif" WIDTH="528" HEIGHT="122" ALIGN="BOTTOM" ALT="TableDialogEditDemo with a tool tip describing the moused-over cell's RGB value"></center></p>[PENDING: this snapshot needs to be updated.It should probably be cropped, as well.]<p>As we mentioned before, you can specify tool tip text by overriding<code>JTable</code>'s <code>getToolTipText(MouseEvent)</code> method.The program<a href="examples/index.html#TableToolTipsDemo">TableToolTipsDemo</a>shows how.You can <b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableToolTipsDemo.jnlp">run TableToolTipsDemo</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.The cells with tool tips are in the <b>Sport</b>and <b>Vegetarian</b> columns.Here's are pictures of their tool tips:<p>[PENDING: put a picture here. It could be cropped to justinclude the relevant cell and its tool tip(along with whatever other cells are between them).]<p><p><center><IMG SRC="../../figures/uiswing/components/TableToolTipsDemo-tooltip.gif" WIDTH="528" HEIGHT="122" ALIGN="BOTTOM" ALT="TableToolTipsDemo with a tool tip for a cell in the Vegetarian column"></center></p>[PENDING: this snapshot needs to be updated and cropped.]<p>Here is the code from<a class="SourceLink" target="_blank" href="examples/TableToolTipsDemo.java"><code>TableToolTipsDemo.java</code></a> that implements tool tips for cells in the <b>Sport</b> and <b>Vegetarian</b> columns:<blockquote><pre>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;    }    ...}</pre></blockquote>The code is fairly straightforward,except perhaps for the call to <code>convertColumnIndexToModel</code>.That call is necessary because if the user moves the columns around,the view's index for the column doesn't match the model's indexfor the column.For example, the user might drag the <b>Vegetarian</b> column(which the model considers to be at index 4)so it's displayed as the first column &#151; at view index 0.Since <code>prepareRenderer</code> gives us the view index,we need to translate the view index to a model indexso we can be sure we're dealing with the intended column.</blockquote><h3><a name="headertooltip">Specifying Tool Tips for Column Headers</a></h3><blockquote>You can add a tool tip to a column headerby setting the tool tip text for the table's <code>JTableHeader</code>.Often, different column headers require different tool tip text.You can change the textby overriding the table header's<code>getToolTipText(MouseEvent)</code> method.<p>An example of using the same tool tip text for all column headers is in <a href="examples/index.html#TableSorterDemo">TableSorterDemo</a>.Here is how it sets the tool tip text:<blockquote><pre>table.getTableHeader().setToolTipText(        "Click to sort; Shift-Click to sort in reverse order");</pre></blockquote><p><a href="examples/index.html#TableToolTipsDemo">TableToolTipsDemo</a>has an example of implementing column header tool tipsthat vary by column.If you<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableToolTipsDemo.jnlp">run TableToolTipsDemo</a></b> (it requires release 6),which you can do using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>, you'll see the tool tips when you mouse over any column headerexcept for the first two.We elected not to supply tool tips for the name columnssince they seemed self explanatory.(Actually, we just wanted to show you that it could be done.)Here's a picture of one of the column header tool tips:<p><center><IMG SRC="../../figures/uiswing/components/TableToolTipsDemo-tooltip-ch.gif" WIDTH="528" HEIGHT="122" ALIGN="BOTTOM" ALT="TableToolTipsDemo with a tool tip for a column header"></center></p>[PENDING: this snapshot needs to be updated.It should also be cropped.]<p>The following code implements the tool tips.Basically, it creates a subclass of <code>JTableHeader</code>that overrides the <code>getToolTipText(MouseEvent)</code> methodso that it returns the text for the current column.To associate the revised table header with the table,the <code>JTable</code> method<code>createDefaultTableHeader</code> is overriddenso that it returns an instance of the <code>JTableHeader</code> subclass.<blockquote><pre>protected String[] columnToolTips = {    null,    null,    "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];            }        };    }};</pre></blockquote></blockquote><h3><a name="sorting">Sorting and Otherwise Manipulating Data</a></h3><blockquote>One way to perform data manipulation such as sortingis to use one or more specialized table models(<em>data manipulators</em>),in addition to the table model that provides the data(the data model).The data manipulatorsshould sit between the tableand the data model,as the following picture shows:<p><center><IMG SRC="../../figures/uiswing/components/9model.gif" WIDTH="474" HEIGHT="57" ALIGN="BOTTOM" ALT="A data manipulator sits between a table and its model."></center></p>[PENDING: This figure will be updated.]<p>If you decide to implement a data manipulator,take a look at<a class="SourceLink" target="_blank" href="examples/TableMap.java"><code>TableMap.java</code></a> and<a class="SourceLink" target="_blank" href="examples/TableSorter.java"><code>TableSorter.java</code></a>.The <code>TableMap</code> classimplements <code>TableModel</code>and serves as a superclass for data manipulators.<code>TableSorter</code> is a data manipulator that sorts the data provided by another table model.It used to be implemented as a subclass of <code>TableMap</code>,but now is a direct subclass of <code>AbstractTableModel</code>.You can use <code>TableSorter</code> as-is to provide sorting functionality,or you can use either <code>TableSorter</code>or <code>TableMap</code> as a basis for writing your own data manipulator.<p>To implement sortingwith <code>TableSorter</code>,you need just three lines of code.The following listingshows the differences between <code>TableDemo</code>and its sorting cousin,<a class="SourceLink" target="_blank" href="examples/TableSorterDemo.java"><code>TableSorterDemo.java</code></a>.<blockquote><pre><B>TableSorter sorter = new TableSorter(new MyTableModel()); //ADDED THIS</b>//JTable table =

⌨️ 快捷键说明

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