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

📄 table.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 5 页
字号:
</blockquote><h3><a name="combobox">Using a Combo Box as an Editor</a></h3><blockquote>Setting up a<a href="combobox.html">combo box</a> as an editor is simple,as the following example shows.The bold line of codesets up the combo box as the editor for a specific column.<blockquote><pre>TableColumn sportColumn = table.getColumnModel().getColumn(2);...JComboBox comboBox = new JComboBox();comboBox.addItem("Snowboarding");comboBox.addItem("Rowing");comboBox.addItem("Chasing toddlers");comboBox.addItem("Speed reading");comboBox.addItem("Teaching high school");comboBox.addItem("None");<b>sportColumn.setCellEditor(new DefaultCellEditor(comboBox));</b></pre></blockquote>Here is a picture of the combo box editor in use:<p><center><IMG SRC="../../figures/uiswing/components/TableRenderDemo.gif" WIDTH="529" HEIGHT="159" ALIGN="BOTTOM" ALT="A combo box cell editor in use"></center></p>[PENDING: This figure will be updated.It should probably include the cursor.]<p>The preceding code is from<a class="SourceLink" target="_blank" href="examples/TableRenderDemo.java"><code>TableRenderDemo.java</code></a>.You can <b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableRenderDemo.jnlp">run TableRenderDemo</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.</blockquote><h3><a name="validtext">Using an Editor to Validate User-Entered Text</a></h3><blockquote>If a cell's default editor allows text entry,you get some error checking for freeif the cell's typeis specified as something other than <code>String</code>or <code>Object</code>.The error checking is a side effectof converting the entered textinto an object of the proper type.<p>The automatic checking of user-entered strings occurswhen the default editorattempts to create a new instance of the classassociated with the cell's column.The default editor creates this instance using a constructorthat takes a <code>String</code> as an argument.For example,in a column whose cells have type <code>Integer</code>,when the user types in "123"the default editor creates the corresponding <code>Integer</code>using code equivalent to<code>new Integer("123")</code>.If the constructor throws an exception,the cell's outline turns redand refuses to let focus move out of the cell.If you implement a class used as a column data type,you can use the default editorif your class supplies a constructor that takesa single argument of type <code>String</code>.<p>If you like having a text field as the editor for a cell,but want to customize it &#151;perhaps to check user-entered text more strictlyor to react differently when the text is invalid &#151;you can change the cell editor to use a<a href="formattedtextfield.html">formatted text field</a>.The formatted text fieldcan check the valueeither continuously while the user is typingor after the user has indicated the end of typing(such as by pressing Enter).<p>The following code, taken from a demo named<a href="examples/index.html#TableFTFEditDemo">TableFTFEditDemo</a>,sets up a formatted text field as an editorthat limits all integer valuesto be between 0 and 100.You can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableFTFEditDemo.jnlp">run TableFTFEditDemo</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.The following code makes the formatted text fieldthe editor for all columnsthat contain data of type <code>Integer</code>.<blockquote><pre>table.setDefaultEditor(Integer.class,                       new IntegerEditor(0, 100));</pre></blockquote>The <code>IntegerEditor</code> class is implemented as a subclass of <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/DefaultCellEditor.html"><code>DefaultCellEditor</code></a> that uses a <code>JFormattedTextField</code>instead of the <code>JTextField</code>that <code>DefaultCellEditor</code> supports.It accomplishes this by first setting up a formatted text fieldto use an integer format and havethe specified minimum and maximum values,using the API described in <a href="formattedtextfield.html">How to Use Formatted Text Fields</a>.It then overrides the <code>DefaultCellEditor</code>implementation of the<code>getTableCellEditorComponent</code>,<code>getCellEditorValue</code>,and <code>stopCellEditing</code> methods,adding the operations that are necessary for formatted text fields.<p>The override of <code>getTableCellEditorComponent</code>sets the formatted text field's <em>value</em> property(and not just the <em>text</em> property it inherits from <code>JTextField</code>)before the editor is shown.The override of <code>getCellEditorValue</code>keeps the cell value as an <code>Integer</code>,rather than, say, the <code>Long</code> value that the formatted text field's parser tends to return.Finally, overriding <code>stopCellEditing</code>lets us check whether the text is valid,possibly stopping the editor from being dismissed.If the text isn't valid,our implementation of <code>stopCellEditing</code>puts up a dialog that gives the user the optionof continuing to edit or reverting to the last good value.The source code is a bit too long to include here,but you can find it in<a class="SourceLink" target="_blank" href="examples/IntegerEditor.java"><code>IntegerEditor.java</code></a>.</blockquote><h3><a name="editor">Using Other Editors</a></h3><blockquote>Whether you're setting the editor for a single column of cells(using the <code>TableColumn</code> <code>setCellEditor</code> method)or for a specific type of data(using the <code>JTable</code><code>setDefaultEditor</code> method),you specify the editor usingan argument that adheres to the <code>TableCellEditor</code>interface.Fortunately, the <code>DefaultCellEditor</code> classimplements this interface and providesconstructors to let you specify an editing componentthat's a <code>JTextField</code>,<code>JCheckBox</code>, or<code>JComboBox</code>.You usually don't have to explicitly specify a check box as an editor,since columns with <code>Boolean</code> dataautomatically use a check box renderer and editor.<p>What if you want to specify an editorthat isn't a text field, check box, or combo box?Well, because <code>DefaultCellEditor</code>doesn't support other types of components,you must do a little more work.You need to create a class that implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableCellEditor.html"><code>TableCellEditor</code></a> interface.The <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/AbstractCellEditor.html"><code>AbstractCellEditor</code></a> class is a good superclass to use.It implements <code>TableCellEditor</code>'s superinterface,<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/CellEditor.html"><code>CellEditor</code></a>, saving you the trouble of implementingthe event firing codenecessary for cell editors.<p>Your cell editor class needs to define at least two methods &#151; <code>getCellEditorValue</code> and<code>getTableCellEditorComponent</code>.The <code>getCellEditorValue</code>method, required by <code>CellEditor</code>,returns the cell's current value.The <code>getTableCellEditorComponent</code>method, required by <code>TableCellEditor</code>,should configure and return the componentthat you want to use as the editor.<p>Here is a picture of a table with a dialog thatserves, indirectly, as a cell editor.When the user begins editing a cell in the <b>Favorite Color</b> column,a button (the true cell editor) appears andbrings up the dialog,with which the user can choose a different color.<a name="colorRenderer"><p><center><IMG SRC="../../figures/uiswing/components/TableDialogEditDemo.gif" WIDTH="646" HEIGHT="232" ALIGN="BOTTOM" ALT="The cell editor brings up a dialog"></center></p></a>[PENDING: This figure will be updated.]<p>You can<b><a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TableDialogEditDemo.jnlp">run TableDialogEditDemo</a></b> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>,or compile and run it yourself by consulting the <a href="examples/index.html#TableDialogEditDemo">example index</a>.Here is the code,taken from <a class="SourceLink" target="_blank" href="examples/ColorEditor.java"><code>ColorEditor.java</code></a>,that implements the cell editor.<blockquote><pre>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;    }}</pre></blockquote>As you can see, the code is pretty simple.The only part that's a bit trickyis the call to <code>fireEditingStopped</code>at the end of the editor button's action handler.Without this call, the editor would remain active,even though the modal dialog is no longer visible.The call to <code>fireEditingStopped</code>lets the table knowthat it can deactivate the editor,letting the cell be handled by the renderer again.</blockquote><h3><a name="renderer">Using Custom Renderers</a></h3><blockquote>This section tells you how to create and specifya cell renderer.You can set a type-specific cell renderer usingthe <code>JTable</code> method <code>setDefaultRenderer</code>.To specify that cells in a particular column should use a renderer,you use the <code>TableColumn</code> method<code>setCellRenderer</code>.You can even specify acell-specific rendererby creating a <code>JTable</code> subclass,as we'll show later.<p>It's easy to customize the text or imagerendered by the default renderer,<code>DefaultTableCellRenderer</code>.You just create a subclassand implement the <code>setValue</code> methodso that it invokes <code>setText</code> or <code>setIcon</code>with the appropriate string or image.For example, here is how the default date renderer is implemented:<blockquote><pre>static class DateRenderer extends DefaultTableCellRenderer {    DateFormat formatter;    public DateRenderer() { super(); }    public void setValue(Object value) {        if (formatter==null) {            formatter = DateFormat.getDateInstance();        }        setText((value == null) ? "" : formatter.format(value));    }}</pre></blockquote><p>If extending <code>DefaultTableCellRenderer</code>doesn't do the trick,you can build a rendererusing another superclass.The easiest way is tocreate a subclass of an existingcomponent,making your subclass implement the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableCellRenderer.html"><code>TableCellRenderer</code></a> interface.<code>TableCellRenderer</code> requires just one method:<code>getTableCellRendererComponent</code>.Your implementation of this methodshould set up the rendering componentto reflect the passed-in state,and then return the component.<p>In the <a href="#colorRenderer">preceding snapshot</a>of TableDialogEditDemo, the rendererused for <b>Favorite Color</b> cellsis a subclass of <code>JLabel</code>called <code>ColorRenderer</code>.Here are excerpts from<a class="SourceLink" target="_blank" href="examples/ColorRenderer.java"><code>ColorRenderer.java</code></a> that show how it's implemented.<blockquote><pre>public class ColorRenderer extends JLabel                           implements TableCellRenderer {    ...    public ColorRenderer(boolean isBordered) {        this.isBordered = isBordered;        setOpaque(true); //MUST do this for background to show up.

⌨️ 快捷键说明

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