0
Java I--Copyright © 2000 Tom Hunter
Java I--Copyright © 2000 Tom HunterChapter 12BasicGraphical User InterfaceComponents,Part II
Java I--Copyright © 2000 Tom HunterJList
Java I--Copyright © 2000 Tom Hunter• This class presents a GUI list of selectable objects.• It supports three selection mo...
Java I--Copyright © 2000 Tom HunterRecall the Model-View-Controller architecture we learnedlast week…• The JList class del...
Java I--Copyright © 2000 Tom HunterView—list cell renderers are instances of:DefaultListCellRendererHow the DefaultListCel...
Java I--Copyright © 2000 Tom Hunter• A JList can display an Icon and a String—but notboth at the same time.• The DefaultLi...
Java I--Copyright © 2000 Tom Hunter• Right out of the box, the JList does not supportscrolling, but—just as with the JText...
Java I--Copyright © 2000 Tom HunterHow theJListReacts to aClick
Java I--Copyright © 2000 Tom Hunter• A JList displays a series of items from which the usermay choose.• When the user clic...
Java I--Copyright © 2000 Tom HunterJList list = new JList( items );list.setVisibleRowCount( 4 );list.setSelectionMode( Lis...
Java I--Copyright © 2000 Tom Hunter• Any complexity that arises in this object comes from thechance that multiple rows may...
Java I--Copyright © 2000 Tom Hunter• In practice, you would use the same getSource() thatyou have used for the ActionEvent...
Java I--Copyright © 2000 Tom Hunter• If you wish to see what values in the list were selectedwhen the ListSelectionEvent w...
Java I--Copyright © 2000 Tom Hunter• In a fully rigorous usage, this is the way aJList is implemented.JList: ListSelection...
Java I--Copyright © 2000 Tom Hunterpublic void valueChanged( ListSelectionEvent e ){String s = “”;if( e.getValueIsAdjustin...
Java I--Copyright © 2000 Tom HunterIf you’re really onlyinterested in thefinal selection point,you querye.getLastIndex()
Java I--Copyright © 2000 Tom Hunter• With a JList, you have many alternative ways todiscover what the user did:JList Selec...
Java I--Copyright © 2000 Tom Hunterint lead = list.getLeadSelectionIndex(),min = list.getMinSelectionIndex(),max = list.ge...
Java I--Copyright © 2000 Tom HunterUnder the Hoodwith theJList
Java I--Copyright © 2000 Tom Hunter• The JList component delegates three major jobs toother objects: data handling, item...
Java I--Copyright © 2000 Tom Hunterimport javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event...
Java I--Copyright © 2000 Tom HunterRemember, when we just addthe JList reference to theContainer, we do notautomatically g...
Java I--Copyright © 2000 Tom Hunterimport javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event...
Java I--Copyright © 2000 Tom Hunter• You recall, the JList delegates its labor to other classesthat actually do the work.—...
Java I--Copyright © 2000 Tom Hunter• To facilitate this model, you can construct instances of aJList using the following C...
Java I--Copyright © 2000 Tom Hunter• After you have constructed an instance of the classJList, you can change what is disp...
Java I--Copyright © 2000 Tom Hunter• Since the JList does not maintain its own data, itcannot help you change individual e...
Java I--Copyright © 2000 Tom Hunter“This interface defines the methods that components like JListuse to get the value of e...
Java I--Copyright © 2000 Tom HunterAdding or RemovingAn Itemfrom the JList
Java I--Copyright © 2000 Tom Hunter• Whenever you add or remove an item from yourlist, that is another type of event. To t...
Java I--Copyright © 2000 Tom Hunter• If you want to change an item in a JList, you have to getits model, and go through th...
Java I--Copyright © 2000 Tom Hunter• One of the three methods defined by theListDataListener interface class is invoked wh...
Java I--Copyright © 2000 Tom Hunter• This event object has three constants that define the changethat occurred.public stat...
Java I--Copyright © 2000 Tom Hunter• This method will tell you the number of rows or items in thelist.public abstract int ...
Java I--Copyright © 2000 Tom HunterJList: Getting a Reference to a Specific Object in theList• This method will give you a...
Java I--Copyright © 2000 Tom HunterJComboBox
Java I--Copyright © 2000 Tom Hunter• A JComboBox gets its name because it is a combinationof an editable area and a drop-d...
Java I--Copyright © 2000 Tom Hunter• However, there are differences:—List cells are not editable—but Combo Boxes can be gi...
Java I--Copyright © 2000 Tom Hunter• More differences:—Lists support three selection modes, and delegateselection control ...
Java I--Copyright © 2000 Tom Hunter• More differences:—On the other hand, combo boxes supportKey Selection, where a key pr...
Java I--Copyright © 2000 Tom HunterDelegate JList JComboBoxJComboBox: Comparison of Delegate Data TypesModel ListModel Com...
Java I--Copyright © 2000 Tom HunterDelegate JList JComboBoxJComboBox: Comparison of Delegate Data TypesModel ListModel Com...
Java I--Copyright © 2000 Tom HunterDelegate JList JComboBoxJComboBox: Comparison of Delegate Data TypesModel ListModel Com...
Java I--Copyright © 2000 Tom Hunter• Recall, the JList class does not provide methods foradding, inserting or removing ite...
Java I--Copyright © 2000 Tom Hunter• The JComboBox is the opposite:—It is made to have items added and removed fromit all ...
Java I--Copyright © 2000 Tom Hunter• Instances of the JComboBox are—by default—noteditable, so you just have to make a sim...
Java I--Copyright © 2000 Tom HunterCode Necessary for a JComboBoxprivate JComboBox comboBox = new JComboBox();…comboBox.ad...
Java I--Copyright © 2000 Tom HunterJComboBox:Classic EventHandling
Java I--Copyright © 2000 Tom Hunter• The most common way you will use a JComboBox isfor making another object react to the...
Java I--Copyright © 2000 Tom HunterString[] numbers = { ‘one’, ‘two’, ‘three’, ‘four’ };JComboBox cb = new JComboBox( numb...
Java I--Copyright © 2000 Tom Hunter• Event handling in a JComboBox is tricky for severalreasons.—When their selected item ...
Java I--Copyright © 2000 Tom HunterJComboBox:Combo Box Editors
Java I--Copyright © 2000 Tom Hunter• Because Combo Boxes can be edited, they can fireActionEvents that you can track with ...
Java I--Copyright © 2000 Tom Hunterpublic class Test extends JApplet{private JComboBox comboBox = new JComboBox();private ...
Java I--Copyright © 2000 Tom Hunter• As you might imagine, this is a highly customizablecomponent.JComboBox: Combo Box Edi...
Java I--Copyright © 2000 Tom HunterJTextArea
Java I--Copyright © 2000 Tom Hunter• This familiar component can display multiple lines.• Must be a single font, single co...
Java I--Copyright © 2000 Tom Hunter• Properties maintained by the JTextArea:—columns: int—the number of columns displayed—...
Java I--Copyright © 2000 Tom HunterJEditorPane
Java I--Copyright © 2000 Tom Hunter• Just like JTextAreas, these are capable of displayingmultiple lines of editable text....
Java I--Copyright © 2000 Tom Hunter• Hyperlink events are fired when a mouse pressed eventoccurs over a hyperlink in an ed...
Java I--Copyright © 2000 Tom Hunter• The HyperlinkEvent object offers the following methods:HyperlinkEvent:—public String ...
Java I--Copyright © 2000 Tom HunterJEditorPane editor = new JEditorPane();…editor.addHyperlinkListener(new HyperlinkListen...
Upcoming SlideShare
Loading in...5
×

Java i lecture_15

106

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
106
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • Transcript of "Java i lecture_15"

    1. 1. Java I--Copyright © 2000 Tom Hunter
    2. 2. Java I--Copyright © 2000 Tom HunterChapter 12BasicGraphical User InterfaceComponents,Part II
    3. 3. Java I--Copyright © 2000 Tom HunterJList
    4. 4. Java I--Copyright © 2000 Tom Hunter• This class presents a GUI list of selectable objects.• It supports three selection modes:—single selection: you choose only one thing at atime.—single intervalinterval selection: you choose severalthings in a row.—multiplemultiple interval selection: you choose severalclumps of items that are not continuous.This is the default setting.JList
    5. 5. Java I--Copyright © 2000 Tom HunterRecall the Model-View-Controller architecture we learnedlast week…• The JList class delegates the job of showing the listand handling its events.• Therefore, the list’s model keeps a list of objects,—that are rendered in list “cells” by the(VIEW), a “list cell renderer.”JList
    6. 6. Java I--Copyright © 2000 Tom HunterView—list cell renderers are instances of:DefaultListCellRendererHow the DefaultListCellRenderer handlesvarious objects:Object Type… is rendered (drawn) by…Icon as isObject with the string returnedfrom toString()String as isJList: How the JList is Drawn (Rendered)
    7. 7. Java I--Copyright © 2000 Tom Hunter• A JList can display an Icon and a String—but notboth at the same time.• The DefaultListCellRenderer can only display asingle object at one time.• If you implement your own custom subclass from theJList , you can make it do special things.JList: How the JList is Drawn (Rendered)
    8. 8. Java I--Copyright © 2000 Tom Hunter• Right out of the box, the JList does not supportscrolling, but—just as with the JTextArea—you canadd it to a JScrollPane object.• You place the JList inside a JScrollPane , andthe list will scroll.JList: How the JList is Normally ImplementedJScrollPaneJListMaking a JList scroll
    9. 9. Java I--Copyright © 2000 Tom HunterHow theJListReacts to aClick
    10. 10. Java I--Copyright © 2000 Tom Hunter• A JList displays a series of items from which the usermay choose.• When the user clicks on an item in the JList, aListSelectionEvent occurs.JList: Responding to A User’s Clicks
    11. 11. Java I--Copyright © 2000 Tom HunterJList list = new JList( items );list.setVisibleRowCount( 4 );list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );list.addListSelectionListener( this );… need to implement ListSelectionListenerObject[] items = { "item1", "item2", "item3", "item4" );Instantiate your JListSet parametersRegister the ListSelectionListener as your listener.Override the inherited abstract methodfrom the Listener interface, and use theinformation contained in theListSelectionEvent object.(Only one method to override)ListSelectionModel.SINGLE_INTERVAL );ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)public void valueChanged( ListSelectionEvent e ){}
    12. 12. Java I--Copyright © 2000 Tom Hunter• Any complexity that arises in this object comes from thechance that multiple rows may have been selected.Constructor:ListSelectionEvent( Object source,int firstIndex,int lastIndex,boolean isAdjusting);JList: ListSelectionEventObject that is changing.First item in rangeselected.If this index is thesame as the first,only one item hasbeen selected.This indicates that manyrapid changes arehappening in succession,so don’t necessarilyconsider this the last one.
    13. 13. Java I--Copyright © 2000 Tom Hunter• In practice, you would use the same getSource() thatyou have used for the ActionEvent object.• Both ActionEvent and ListSelectionEventinherit this samegetSource() method from EventObject.* * * However, you will need to cast this back into aJList object to really take advantage of the informationit contains. * * *JList: ListSelectionEvent
    14. 14. Java I--Copyright © 2000 Tom Hunter• If you wish to see what values in the list were selectedwhen the ListSelectionEvent was triggered, youuse either of two methods:public Object getSelectedValue()public Object[] getSelectedValues()JList: ListSelectionEventReturns a singleObjectReturns anarray ofObjects
    15. 15. Java I--Copyright © 2000 Tom Hunter• In a fully rigorous usage, this is the way aJList is implemented.JList: ListSelectionEventpublic void valueChanged( ListSelectionEvent e ){if( e.getValueIsAdjusting() )return;JList listEvent = (JList) e.getSource();if( listEvent.isSelectionEmpty() ){// This means nothing was selected.else{int index = listEvent.getSelectedIndex();// This returns the location of the single line// that was selected from the list.}}If the user is still choosing,this allows us to wait.We cast the eventfrom a generic objectinto a specific onethat we can probe.Nothing selected.Identify exactly what was selected.
    16. 16. Java I--Copyright © 2000 Tom Hunterpublic void valueChanged( ListSelectionEvent e ){String s = “”;if( e.getValueIsAdjusting() ){s = “Value is adjusting”;}else{s = “Selection from e.getFirstIndex() +“to” + e.getLastIndex();}showStatus( s );}For this example, we don’thave to cast it into aJList object. We can usethe methods in theListSelectionEventobject.When you movethrough a list, this isthe place you whereyou started.When you’re making a selection,this is the place where you stopped.
    17. 17. Java I--Copyright © 2000 Tom HunterIf you’re really onlyinterested in thefinal selection point,you querye.getLastIndex()
    18. 18. Java I--Copyright © 2000 Tom Hunter• With a JList, you have many alternative ways todiscover what the user did:JList Selection PropertiesProperty Meaninganchor —the index that most recently began aninterval selection.lead —the last index of the most recentselection interval.maximum —the highest index from the selected items.minimum —the lowest index from the selected items.JList: Fine-Grained Selection Properties
    19. 19. Java I--Copyright © 2000 Tom Hunterint lead = list.getLeadSelectionIndex(),min = list.getMinSelectionIndex(),max = list.getMaxSelectionIndex(),anchor = list.getAnchorSelectionIndex();int[] selected = list.getSelectedIndices();I clicked on item[0]and it made all themethods return 0.I clicked on item[2]and it made all themethods return 2.I clicked on item[4],while I held down theshift key and it shows:—the lead as 4,—anchor as 2 (whereI started), and—array of selectedindexes shows 2,3,4as you see.This button fires methodlist.clearSelection()It sets all these values to -1.
    20. 20. Java I--Copyright © 2000 Tom HunterUnder the Hoodwith theJList
    21. 21. Java I--Copyright © 2000 Tom Hunter• The JList component delegates three major jobs toother objects: data handling, item selection and cell renderingJList: How the Work is Delegated—to ListModel—to ListSelectionModel—to ListCellRendererAll three of theseare interfacesinterfaces.
    22. 22. Java I--Copyright © 2000 Tom Hunterimport javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;public class Test extends JApplet{public void init(){Container c = getContentPane();c.setLayout(new FlowLayout());Object[] items = { "item one", "item two","item three", "item four","item five", "item six","item seven", "item eight","item nine", "item ten" };JList list = new JList( items );list.setVisibleRowCount( 7 );c.add( list );}}Instantiate an array of anyObject. Then youinstantiate the JList objectwith your array.You usually decidehow many rows of thelist you want to see atany one time. Thedefault visible size is 8rows.
    23. 23. Java I--Copyright © 2000 Tom HunterRemember, when we just addthe JList reference to theContainer, we do notautomatically get scrolling. Forthat, you need to add theJList to a JScrollPane.Notice, although we specified avisible limit of 7 rows—we’reseeing 10. What gives?ThesetVisibleRowCount()method only takes effect whenthe list is in a scroll pane
    24. 24. Java I--Copyright © 2000 Tom Hunterimport javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;public class Test extends JApplet{public void init(){Container c = getContentPane();c.setLayout(new FlowLayout());Object[] items = { "item one", "item two","item three", "item four","item five", "item six","item seven", "item eight","item nine", "item ten" };JList list = new JList( items );list.setVisibleRowCount( 7 );JScrollPane sp = new JScrollPane( list );c.add( sp );}}Remember, the JListaccepts an Object.You can put any objectin a JList.
    25. 25. Java I--Copyright © 2000 Tom Hunter• You recall, the JList delegates its labor to other classesthat actually do the work.—For example, the JList does not manage thedata handling—the references—to the objectsit displays.—Instead, all instances of JList delegate themanagement of the data to an object thatimplements the ListModel interfaceinterface.JList
    26. 26. Java I--Copyright © 2000 Tom Hunter• To facilitate this model, you can construct instances of aJList using the following Constructors:• public JList( ListModel )• public JList( Object[] )• public JList( Vector )JList
    27. 27. Java I--Copyright © 2000 Tom Hunter• After you have constructed an instance of the classJList, you can change what is displayed with thefollowing:• public void setModel( ListModel )• public void setListData( Object[] )• public void setListData( Vector )• These methods allow you to change the entire contents ofthe list in one motion.• Changing individual elements is not so easy...JList
    28. 28. Java I--Copyright © 2000 Tom Hunter• Since the JList does not maintain its own data, itcannot help you change individual elements in the list.• To accomplish that, you have to go to where that data isstored.—You have to directly manipulate the list’s model.—All of these “models” must implement theListModel interface.JList
    29. 29. Java I--Copyright © 2000 Tom Hunter“This interface defines the methods that components like JListuse to get the value of each cell in a list and the length of the list.”—Logically the model is a vector.—Its indexes vary from 0 toListDataModel.getSize() - 1.—Any change to the contents or length of the data modelmust be reported to all of theListDataListeners—the controllerscontrollersJList
    30. 30. Java I--Copyright © 2000 Tom HunterAdding or RemovingAn Itemfrom the JList
    31. 31. Java I--Copyright © 2000 Tom Hunter• Whenever you add or remove an item from yourlist, that is another type of event. To track thatevent, you use the objectListDataListenerJList: Changes to the Items in the List
    32. 32. Java I--Copyright © 2000 Tom Hunter• If you want to change an item in a JList, you have to getits model, and go through the interfaceListDataListener—Methods the implementing classes must override:public abstract void addListDataListener( ListDataListener )public abstract void removeListDataListener( ListDataListener )—Classes that implement this interface are notifiedwhen the contents of the list changes.JList: Registering a Listener For Changes to the ListThis is the equivalent of the methodaddActionListener
    33. 33. Java I--Copyright © 2000 Tom Hunter• One of the three methods defined by theListDataListener interface class is invoked wheneverdata associated with a list is modified.—Methods the implementing classes must override:public abstract void contentsChanged( ListDataEvent )public abstract void intervalAdded( ListDataEvent )public abstract void intervalRemoved( ListDataEvent )—If just one item is changed, the first method is called.—When an “interval” or several contiguous objects inthe list are added, either of the last twomethods are called.JList: ListDataListener
    34. 34. Java I--Copyright © 2000 Tom Hunter• This event object has three constants that define the changethat occurred.public static final int CONTENTS_CHANGEDpublic static final int INTERVAL_ADDEDpublic static final int INTERVAL_REMOVED• Constructors:public ListDataEvent( Object source, int type, int index(), int index1 )JList: ListDataEventSource of the eventType of the event—using the constantsabove.Beginning and endingindexes of the items thatwere changed.
    35. 35. Java I--Copyright © 2000 Tom Hunter• This method will tell you the number of rows or items in thelist.public abstract int getSize()JList: Getting the Size—Number of Items in the List
    36. 36. Java I--Copyright © 2000 Tom HunterJList: Getting a Reference to a Specific Object in theList• This method will give you a reference to a specificObject in the list.public abstract Object getElementAt()
    37. 37. Java I--Copyright © 2000 Tom HunterJComboBox
    38. 38. Java I--Copyright © 2000 Tom Hunter• A JComboBox gets its name because it is a combinationof an editable area and a drop-down list of selectableitems.• In other words, a JComboBox is a more complexJList.• Because both display a list of items, they both havemodels that extend the ListModel interfaceinterface.• Likewise, both are components that that render list cellsby implementing the ListCellRenderer interfaceinterface.JComboBox: Similarities to JList
    39. 39. Java I--Copyright © 2000 Tom Hunter• However, there are differences:—List cells are not editable—but Combo Boxes can be given an editor.JComboBoxThe JComboBox component delegates editingto an object thatimplements the ComboBoxEditor interfaceinterface.
    40. 40. Java I--Copyright © 2000 Tom Hunter• More differences:—Lists support three selection modes, and delegateselection control responsibilities to an objectthat implements theListSelectionModel interfaceinterface.—Combo Boxes can only haveone item selected at one time.—Selection is handled by combo box models.JComboBox
    41. 41. Java I--Copyright © 2000 Tom Hunter• More differences:—On the other hand, combo boxes supportKey Selection, where a key press can selectan item.—List boxes do not supportdo not support Key Selection.JComboBox
    42. 42. Java I--Copyright © 2000 Tom HunterDelegate JList JComboBoxJComboBox: Comparison of Delegate Data TypesModel ListModel ComboBoxModelRemember,under theModel-View-Controllerarchitecture,the Modeltakes care ofhow the datais stored.This is also aninterfaceinterface, and itextends theListModelinterfaceinterface.This is an interfaceinterface thatextends theAbstractListModelinterfaceinterface.Object getSelectedItem()setSelectedItem(Object item)addListDataListener()getElementAt( int Index )getSize()removeListDataListener()
    43. 43. Java I--Copyright © 2000 Tom HunterDelegate JList JComboBoxJComboBox: Comparison of Delegate Data TypesModel ListModel ComboBoxModelRenderer ListCellRenderer ListCellRendererThis is an interfaceinterface, and it has a single method.The return value of this one method returns aComponent that will display anything thatimplements the interface, whether that is aListModel or a ComboBoxModel.
    44. 44. Java I--Copyright © 2000 Tom HunterDelegate JList JComboBoxJComboBox: Comparison of Delegate Data TypesModel ListModel ComboBoxModelRenderer ListCellRenderer ListCellRendererSelectionModel DefaultListSelectionModel —KeySelectionManager — JComboBox,DefaultKeySelectionManagerRemember, thedefault is multipleinterval selection.Combo boxes allow items to be selected with akey press. If a key is pressed when the box hasfocus, a search is initiated for a match betweenthe key and the item in the list.If there is a hithit, the item is selected.A hithit is when the first letter of the list stringmatches.
    45. 45. Java I--Copyright © 2000 Tom Hunter• Recall, the JList class does not provide methods foradding, inserting or removing items from the list directly.—After the JList is constructed, the only way tomodify list data after it has been constructedis with the:JList.setListData() method.—This method permits all of the list items to bespecified at once.JComboBox: Additional Differences
    46. 46. Java I--Copyright © 2000 Tom Hunter• The JComboBox is the opposite:—It is made to have items added and removed fromit all day long.—But the only way to reset all of the data at oncefor a combo box is using the method:JComboBox.setModel( ComboBoxModel )JComboBox: Additional DifferencesDon’t forget, this is aninterfaceinterface that managesJComboBox’s data.
    47. 47. Java I--Copyright © 2000 Tom Hunter• Instances of the JComboBox are—by default—noteditable, so you just have to make a simple call to:JComboBox.setEditable( true )and you can edit to your heart’s content.JComboBoxShowing listThis example is not editable, asyou can see by the graybackground in the JComboBox.The behavior of these twovariants—editable and noteditable—is significantlydifferent.Editable
    48. 48. Java I--Copyright © 2000 Tom HunterCode Necessary for a JComboBoxprivate JComboBox comboBox = new JComboBox();…comboBox.addItem( “Top” );comboBox.addItem( “Center” );comboBox.addItem( “Bottom” );comboBox.setEditable( true );comboBox.getEditor().addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){System.out.println("here" + comboBox.getSelectedItem() );}});This example uses a default constructor.You could also have used:public JComboBox( ComboBoxModel )public JComboBox( Object[] )public JComboBox( Vector )This returns the editor used to paint and edit the selecteditem in the JComboBox field.
    49. 49. Java I--Copyright © 2000 Tom HunterJComboBox:Classic EventHandling
    50. 50. Java I--Copyright © 2000 Tom Hunter• The most common way you will use a JComboBox isfor making another object react to the choices expressedby the user.• For this purpose, you implement theItemListener interfaceinterface.JComboBox: Classic Event Handling
    51. 51. Java I--Copyright © 2000 Tom HunterString[] numbers = { ‘one’, ‘two’, ‘three’, ‘four’ };JComboBox cb = new JComboBox( numbers );cb.setMaximumRowCount( 3 );cb.addItemListener( new Itemlistener(){});public void itemStateChanged( ItemEvent e ){someJLabel.setText( numbers[ cb.getSelectedIndex() ] );}cb.getSelectedIndex()• This method returns an int, which becomes a subscriptfor the array, which returns a String, which becomes thetext.
    52. 52. Java I--Copyright © 2000 Tom Hunter• Event handling in a JComboBox is tricky for severalreasons.—When their selected item changes—either bybeing selected, or by having them be edited—every JComboBox fires two events.1.) For deselecting the previous item.2.) For selecting the current item.Also, whenever an item event is fired, anaction event is alsoalso fired right away.JComboBox: Classic Event Handling
    53. 53. Java I--Copyright © 2000 Tom HunterJComboBox:Combo Box Editors
    54. 54. Java I--Copyright © 2000 Tom Hunter• Because Combo Boxes can be edited, they can fireActionEvents that you can track with anActionListener.• In fact, whenever the currently displayed value is edited,the combo box fires an action event.JComboBox: Combo Box Editors
    55. 55. Java I--Copyright © 2000 Tom Hunterpublic class Test extends JApplet{private JComboBox comboBox = new JComboBox();private ComboBoxEditor editor = comboBox.getEditor();public void init(){Container c = getContentPane();comboBox.setEditable(true);comboBox.addItem("Top");comboBox.addItem("Center");comboBox.addItem("Bottom");c.setLayout(new FlowLayout());c.add(comboBox);editor.addActionListener( new ActionListener(){public void actionPerformed(ActionEvent e){String s = (String) editor.getItem();showStatus("Item Edited: " + s);}});}}This is an interfaceinterface, it hasmethod getItem(),which returns anObject.Once we get an Object out of the editor,we cast it into type String, and discoverwhat the edit was that triggered the event.
    56. 56. Java I--Copyright © 2000 Tom Hunter• As you might imagine, this is a highly customizablecomponent.JComboBox: Combo Box Editors
    57. 57. Java I--Copyright © 2000 Tom HunterJTextArea
    58. 58. Java I--Copyright © 2000 Tom Hunter• This familiar component can display multiple lines.• Must be a single font, single color.• This is basic in its function. For complex abilities, choosethe JEditorPane and JTextPane.• Does not implement scrolling by itself.• You can specify its word wrapping behavior.JTextArea txt = new JTextArea();txt.setLineWrap( true );JTextArea
    59. 59. Java I--Copyright © 2000 Tom Hunter• Properties maintained by the JTextArea:—columns: int—the number of columns displayed—line count: int—the number of lines of textcontained in the text area.—line wrap: boolean—determines whether or notlines of text are wrapped at theright edge of a text area.—rows: int—the number of lines of text displayedin a text area.—tabSize: int—number of characters inserted whenthe tab key is pressed.—wrapStyleWord:boolean—when true, causeswords to be wrapped on words.If false, wrap is on characters.JTextArea
    60. 60. Java I--Copyright © 2000 Tom HunterJEditorPane
    61. 61. Java I--Copyright © 2000 Tom Hunter• Just like JTextAreas, these are capable of displayingmultiple lines of editable text.• Unlike text areas, JEditorPanes can display HTML andRTF formats.JEditorPaneJEditorPane editor = new JEditorPane();editor.setPage( url );
    62. 62. Java I--Copyright © 2000 Tom Hunter• Hyperlink events are fired when a mouse pressed eventoccurs over a hyperlink in an editor pane that is displayingan HTML document.• Naturally, Swing defines a HyperLinkListener interfaceand HyperLinkEvent class that permits hyperlink events tobe handled.public abstract voidhyperlinkUpdate( HyperlinkEvent h )JEditorPane
    63. 63. Java I--Copyright © 2000 Tom Hunter• The HyperlinkEvent object offers the following methods:HyperlinkEvent:—public String getDescription()—public HyperlinkEvent.EventTypegetEventType()—public URL getURL()JEditorPane
    64. 64. Java I--Copyright © 2000 Tom HunterJEditorPane editor = new JEditorPane();…editor.addHyperlinkListener(new HyperlinkListener(){public void hyperlinkUpadate( HyperLinkEvent e ){editor.setPane( e.getURL() );}});
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×