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

📄 combobox.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 3 页
字号:
or click the button to display a drop-down list.Here's what the two forms of combo boxes look likein the Java look and feel:<p align=center><table summary="layout"><tr><td><p><center><IMG SRC="../../figures/uiswing/components/UneditableComboMenuMetal.png" WIDTH="177" HEIGHT="25" ALIGN="BOTTOM" ALT="An uneditable combo box"></center></p><td><p><center><IMG SRC="../../figures/uiswing/components/EditableComboBoxMenuMetal.png" WIDTH="211" HEIGHT="25" ALIGN="BOTTOM" ALT="An editable combo box"></center></p><tr valign=top><td><p><center><IMG SRC="../../figures/uiswing/components/UneditableComboMenu2Metal.png" WIDTH="177" HEIGHT="117" ALIGN="BOTTOM" ALT="An uneditable combo box"></center></p><td><p><center><IMG SRC="../../figures/uiswing/components/EditableComboBoxMenuMetal2.png" WIDTH="211" HEIGHT="171" ALIGN="BOTTOM" ALT="An editable combo box"></center></p><tr><td> <b>Uneditable combo box, before (top)     <br>and after the button is clicked</b><td> <b>Editable combo box, before and after     <br>the arrow button is clicked</b></table><p>Combo boxes require little screen space,and their editable (text field) formis useful for letting the user quickly choose a valuewithout limiting the user to the displayed values.Other components that can display one-of-many choices aregroups of <a href="button.html#radiobutton">radio buttons</a>and<a href="list.html">lists</a>.Groups of radio buttons are generally the easiest for users to understand,but combo boxes can be more appropriatewhen space is limited or more than a few choices are available.Lists are not terribly attractive,but they're more appropriate than combo boxeswhen the number of items is large (say, over 20)or when selecting multiple items might be valid.<p>Because editable and uneditable combo boxes are so different,this section treats them separately.This section covers these topics:<ul><li><a href="#uneditable">Using an Uneditable Combo Box</a><li><a href="#listeners">Handling Events on a Combo Box</a><li><a href="#editable">Using an Editable Combo Box</a><li><a href="#renderer">Providing a Custom Renderer</a><li><a href="#api">The Combo Box API</a><li><a href="#eg">Examples that Use Combo Boxes</a></ul><a name="uneditable"></blockquote><h3>Using an Uneditable Combo Box</h3></a><blockquote>The application shown hereuses an uneditable combo boxfor choosing a pet picture:<p><center><IMG SRC="../../figures/uiswing/components/ComboBoxDemoMetal.png" WIDTH="225" HEIGHT="231" ALIGN="BOTTOM" ALT="An uneditable combo box"></center></p><a name="trythis"><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ComboBoxDemo.jnlp">Run ComboBoxDemo</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#ComboBoxDemo">example index</a>.<li> Choose an animal name from the combo box to view its picture.<li> Compare the operation and GUI of this program     to one that uses radio buttons:     <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/RadioButtonDemo.jnlp">run RadioButtonDemo</a> (it requires release 6).     You might want to compare the source code as well:<a class="SourceLink" target="_blank" href="examples/ComboBoxDemo.java"><code>ComboBoxDemo.java</code></a>     vs.<a class="SourceLink" target="_blank" href="examples/RadioButtonDemo.java"><code>RadioButtonDemo.java</code></a>.</ol><hr></blockquote></a>The following code, taken from<a class="SourceLink" target="_blank" href="examples/ComboBoxDemo.java"><code>ComboBoxDemo.java</code></a>,creates an uneditable combo boxand sets it up:<blockquote><pre>String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };//Create the combo box, select item at index 4.//Indices start at 0, so 4 specifies the pig.JComboBox petList = new JComboBox(petStrings);petList.setSelectedIndex(4);petList.addActionListener(this);</pre></blockquote>This combo box contains an array of strings,but you could just as easily use icons instead.To put anything else into a combo boxor to customize how the items in a combo box look,you need to write a custom renderer.An editable combo box would also need a custom editor.Refer to<a href="#renderer">Providing a Custom Renderer</a>for information and an example.<p>The preceding code registers an action listener on the combo box.To see the action listener implementationand learn about other types of listenerssupported by combo box, refer to<a href="#listeners">Handling Events on a Combo Box</a>.<p>No matter which constructor you use,a combo box uses a combo box modelto contain and manage the items in its menu.When you initialize a combo box with an array or a vector,the combo box creates a default model object for you.As with other Swing components,you can customize a combo boxin part by implementing a custom model &#151; an object that implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ComboBoxModel.html"><code>ComboBoxModel</code></a> interface.<a name="datsun">&nbsp;</a><blockquote><hr><strong>Note:</strong>&nbsp;Be careful when implementing a custom model for a combo box.The <code>JComboBox</code> methods that changethe items in the combo box's menu,such as <code>insertItemAt</code>,work only if the data model implements the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/MutableComboBoxModel.html"><code>MutableComboBoxModel</code></a> interface(a subinterface of <code>ComboBoxModel</code>).Refer to the<a href="#api">API</a> tables to see which methods are affected.<p>Something else to watch out for &#151;even for uneditable combo boxes &#151;is ensuring that your custom model fires<a class="TutorialLink" target="_top" href="../events/listdatalistener.html">list data events</a> when the combo box's data or state changes.Even immutable combo box models,whose data never changes,must fire a list data event(a <code>CONTENTS_CHANGED</code> event)when the selection changes.One way to get the list data event firing code for freeis to make your combo box model a subclass of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/AbstractListModel.html"><code>AbstractListModel</code></a>.<hr></blockquote></blockquote><a name="listeners"><h3>Handling Events on a Combo Box</h3></a><blockquote>Here's the code from <code>ComboBoxDemo.java</code>that registers and implements an action listener on the combo box:<blockquote><pre>public class ComboBoxDemo ... implements ActionListener {    . . .        petList.addActionListener(this) {    . . .    public void actionPerformed(ActionEvent e) {        JComboBox cb = (JComboBox)e.getSource();        String petName = (String)cb.getSelectedItem();        updateLabel(petName);    }    . . .}</pre></blockquote>This action listener gets the newly selected item fromthe combo box, uses it to compute the name of an image file,and updates a label to display the image.The combo box fires an action eventwhen the user selects an item fromthe combo box's menu.See<a class="TutorialLink" target="_top" href="../events/actionlistener.html">How to Write an Action Listener</a>, for general information about implementing action listeners.<p>Combo boxes also generate item events,which are fired when any of the items' selection state changes.Only one item at a time can be selected ina combo box, so when the user makes a new selectionthe previously selected item becomes unselected.Thus two item events are fired each time the userselects a different item from the menu.If the user chooses the same item,no item events are fired.Use <code>addItemListener</code> to register an item listeneron a combo box.<a class="TutorialLink" target="_top" href="../events/itemlistener.html">How to Write an Item Listener</a> gives general information about implementing item listeners.<p>Although <code>JComboBox</code> inherits methodsto register listeners forlow-level events &#151;focus, key, and mouse events, for example &#151;we recommend thatyou don't listen for low-level events on a combo box.Here's why:A combo box is a <em>compound component</em> &#151;it is comprised of two or more other components.The combo box itself fires high-level events such as action events.Its subcomponents fire low-level events such as mouse,key, and focus events.The low-level events and the subcomponent that firesthem are look-and-feel-dependent.To avoid writing look-and-feel-dependent code,you should listen only for high-level eventson a compound component such as a combo box.For information about events, including a discussion abouthigh- and low-level events, refer to<a class="TutorialLink" target="_top" href="../events/index.html">Writing Event Listeners</a>.</blockquote><a name="editable"><h3>Using an Editable Combo Box</h3></a><blockquote>Here's a picture of a demo applicationthat uses an editable combo box to enter a patternwith which to format dates.<p><center><IMG SRC="../../figures/uiswing/components/ComboBoxDemo2Metal.png" WIDTH="239" HEIGHT="177" ALIGN="BOTTOM" ALT="An editable combo box"></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ComboBoxDemo2.jnlp">Run ComboBoxDemo2</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#ComboBoxDemo2">example index</a>.<li> Enter a new pattern by choosing one from the combo box's menu.     The program reformats the current date and time.<li> Enter a new pattern by typing one in and pressing Enter.     Again the program reformats the current date and time.</ol><hr></blockquote><p>The following code, taken from<a class="SourceLink" target="_blank" href="examples/ComboBoxDemo2.java"><code>ComboBoxDemo2.java</code></a>,creates and sets up the combo box:<blockquote><pre>String[] patternExamples = {         "dd MMMMM yyyy",         "dd.MM.yy",         "MM/dd/yy",         "yyyy.MM.dd G 'at' hh:mm:ss z",         "EEE, MMM d, ''yy",         "h:mm a",         "H:mm:ss:SSS",         "K:mm a,z",         "yyyy.MMMMM.dd GGG hh:mm aaa"};. . .JComboBox patternList = new JComboBox(patternExamples);<strong>patternList.setEditable(true);</strong>patternList.addActionListener(this);</pre></blockquote>This code is very similar to the previous example, but warrantsa few words of explanation.The bold line of code explicitly turns on editingto allow the user to type values in.This is necessary because, by default, a combo box is not editable.This particular example allows editing on the combo box becauseits menu does not provide all possible date formatting patterns,just shortcuts to frequently used patterns.<p>An editable combo box fires an action eventwhen the user chooses an item from the menuand when the user types Enter.Note that the menu remains unchangedwhen the user enters a value into the combo box.If you want,you can easily write an action listener thatadds a new item to the combo box's menueach time the user types in a unique value.<p>See<a class="TutorialLink" target="_top" href="../../i18n/index.html">Internationalization</a> to learn more about formatting datesand other types of data.</blockquote><a name="renderer"><h3>Providing a Custom Renderer</h3><blockquote>A combo box uses a <em>renderer</em> to display each item in its menu.If the combo box is uneditable,it also uses the renderer to display the currently selected item.An editable combo box, on the other hand,uses an <em>editor</em> to display the selected item.A renderer for a combo box must implement the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html"><code>ListCellRenderer</code></a> interface.A combo box's editor must implement<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ComboBoxEditor.html"><code>ComboBoxEditor</code></a>.This section shows how to providea custom renderer for an uneditable combo box.<p>The default renderer knows how to render strings and icons.If you put other objects in a combo box,the default renderer calls the <code>toString</code>method to provide a string to display.You can customize the way a combo box renders itselfand its itemsby implementing your own <code>ListCellRenderer</code>.<p>Here's a picture of an applicationthat uses a combo box with a custom renderer:<p><center><IMG SRC="../../figures/uiswing/components/CustomComboBoxDemoMetal.png" WIDTH="274" HEIGHT="211" ALIGN="BOTTOM" ALT="A combo box with a custom renderer"></center></p><p>You can <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/CustomComboBoxDemo.jnlp">run CustomComboBoxDemo</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>.The full source code for this example is in<a class="SourceLink" target="_blank" href="examples/CustomComboBoxDemo.java"><code>CustomComboBoxDemo.java</code></a>.To get the image files it requires,consult the<a href="examples/index.html#CustomComboBoxDemo">example index</a>.<p>The following statements from the examplecreate an instance of <code>ComboBoxRenderer</code>(a custom class)and set up the instance as the combo box's renderer:<blockquote><pre>JComboBox petList = new JComboBox(intArray);. . .ComboBoxRenderer renderer = new ComboBoxRenderer();renderer.setPreferredSize(new Dimension(200, 130));petList.setRenderer(renderer);petList.setMaximumRowCount(3);</pre></blockquote><p>The last line sets the combo box's maximum row count,which determines the number of items visible whenthe menu is displayed.If the number of items in the combo box is larger thanits maximum row count, the menu has a scroll bar.The icons are pretty big for a menu,so our code limits the number of rows to 3.Here's the implementation of <code>ComboBoxRenderer</code>,a renderer that puts an icon and text side-by-side:<blockquote><pre>

⌨️ 快捷键说明

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