Web hosting ecommerce - Java Swing - O Reilly // SelectableTest.java // A
Java Swing - O Reilly // SelectableTest.java // A test of the SelectableTextArea class. // import javax.swing.*; import java.awt.BorderLayout; public class SelectableTest extends JFrame { public SelectableTest() { super(”Selectable Text Area Test”); setSize(400, 300); addWindowListener(new BasicWindowMonitor()); SelectableTextArea sta = new SelectableTextArea(”Starter text”, 8, 40); getContentPane().add(sta, BorderLayout.CENTER); } public static void main(String args[]) { SelectableTest st = new SelectableTest(); st.setVisible(true); } } 27.3.2.1 Properties The KeyStroke class contains the properties shown in Table 27.7. The keyChar property is the character this keystroke represents, such as A or $. The keyCode property is the int value associated with a particular key on your keyboard. This might be the ASCII value of a letter, or some other value associated with a function key. The modifiers property contains information on whether or not any of the modifier keys (Control, Alt, Meta, Shift) are attached to this keystroke. The acceptable key codes come from the java.awt.event. KeyEvent class and are shown in Table 27.8. The onKeyRelease property determines when events associated with this keystroke should be triggered. A true value treats the keystroke as a keyTyped() event, while a false value behaves like keyPressed() event. Table 27.7, KeyStroke Properties Property Data Type get is set bound Default Value keyChar char ” ” keyCode int 0 modifiers int 0 onKeyRelease boolean false 27.3.2.2 Key Codes Just for your reference, here’s a table of the valid key codes from the java.awt.event.KeyEventclass. You’ll notice that many of the key code values correspond to the ASCII value of the character associated with the key. This facilitates coding for the common keys, because you can use shortcuts like ‘R’ instead of KeyEvent.VK_R wherever a key code is expected. Of course, as a good programmer, you always use the constant, right? (We left out character equivalents that were not related to the VK key.) Table 27.8, Valid Key Codes for Use with KeyStroke KeyEvent Decimal Hexadecimal char KeyEvent Constant Decimal Hexadecimal char - 932 #BREAK# Java Swing - O Reilly Constant Value Value equivalent Value Value equivalent VK_0 48 0×30 “0″ VK_X 88 0×58 “X” VK_1 49 0×31 “1″ VK_Y 89 0×59 “Y” VK_2 50 0×32 “2″ VK_Z 90 0×5a “Z” VK_3 51 0×33 “3″ VK_ACCEPT 30 0×1e VK_4 52 0×34 “4″ VK_ADD 107 0×6b VK_5 53 0×35 “5″ VK_ALT 18 0×12 VK_6 54 0×36 “6″ VK_BACK_QUOTE 192 0xc0 VK_7 55 0×37 “7″ VK_BACK_SLASH 92 0×5c “\” VK_8 56 0×38 “8″ VK_BACK_SPACE 8 0×08 “b” VK_9 57 0×39 “9″ VK_CANCEL 3 0×03 VK_A 65 0×41 “A” VK_CAPS_LOCK 20 0×14 VK_B 66 0×42 “B” VK_CLEAR 12 0×0c VK_C 67 0×43 “C” VK_CLOSE_BRACKET 93 0×5d “]” VK_D 68 0×44 “D” VK_COMMA 44 0×2c “,” VK_E 69 0×45 “E” VK_CONTROL 17 0×11 VK_F 70 0×46 “F” VK_CONVERT 28 0×1c VK_G 71 0×47 “G” VK_DECIMAL 110 0×6e VK_H 72 0×48 “H” VK_DELETE 127 0×7f VK_I 73 0×49 “I” VK_DIVIDE 111 0×6f VK_J 74 0×4a “J” VK_DOWN 40 0×28 VK_K 75 0×4b “K” VK_END 35 0×23 VK_L 76 0×4c “L” VK_ENTER 10 0×0a “n” VK_M 77 0×4d “M” VK_EQUALS 61 0×3d “=” VK_N 78 0×4e “N” VK_ESCAPE 27 0×1b VK_O 79 0×4f “O” VK_F1 112 0×70 VK_P 80 0×50 “P” VK_F2 113 0×71 VK_Q 81 0×51 “Q” VK_F3 114 0×72 VK_R 82 0×52 “R” VK_F4 115 0×73 VK_S 83 0×53 “S” VK_F5 116 0×74 VK_T 84 0×54 “T” VK_F6 117 0×75 VK_U 85 0×55 “U” VK_F7 118 0×76 VK_V 86 0×56 “V” VK_F8 119 0×77 VK_W 87 0×57 “W” VK_F9 120 0×78 VK_F10 121 0×79 VK_NUMPAD7 103 0×67 VK_F11 122 0×7a VK_NUMPAD8 104 0×68 VK_F12 123 0×7b VK_NUMPAD9 105 0×69 VK_FINAL 24 0×18 VK_OPEN_BRACKET 91 0×5b “[” VK_HELP 156 0×9c VK_PAGE_DOWN 34 0×22 VK_HOME 36 0×24 VK_PAGE_UP 33 0×21 VK_INSERT 155 0×9b VK_PAUSE 19 0×13 VK_KANA 21 0×15 VK_PERIOD 46 0×2e “.” VK_KANJI 25 0×19 VK_PRINTSCREEN 154 0×9a - 933 #BREAK# Java Swing - O Reilly VK_LEFT 37 0×25 VK_QUOTE 222 0xde VK_META 157 0×9d VK_RIGHT 39 0×27 VK_MODECHANGE 31 0×1f VK_SCROLL_LOCK 145 0×91 VK_MULTIPLY 106 0×6a VK_SEMICOLON 59 0×3b “;” VK_NONCONVERT 29 0×1d VK_SEPARATER 108 0×6c VK_NUM_LOCK 144 0×90 VK_SHIFT 16 0×10 VK_NUMPAD0 96 0×60 VK_SLASH 47 0×2f “/” VK_NUMPAD1 97 0×61 VK_SPACE 32 0×20 ” ” VK_NUMPAD2 98 0×62 VK_SUBTRACT 109 0×6d VK_NUMPAD3 99 0×63 VK_TAB 9 0×09 “t” VK_NUMPAD4 100 0×64 VK_UNDEFINED 0 0×00 VK_NUMPAD5 101 0×65 VK_UP 38 0×26 VK_NUMPAD6 102 0×66 27.3.2.3 Instantiation Methods The KeyStroke class does not have a constructor. All keystrokes are cached for you. You can use any of the following static methods (listed after the table) to retrieve the appropriate instance you’re looking for. public static KeyStroke getKeyStroke(char keyChar) public static KeyStroke getKeyStroke(char keyChar, boolean onKeyRelease) Return the KeyStroke that represents a character, such as ‘A’. The onKeyRelease argument determines whether actions associated with this keystroke are triggered when the key is pressed (false) or when it is released (true). public static KeyStroke getKeyStroke(int keyCode, int modifiers) public static KeyStroke getKeyStroke(int keyCode, int modifiers, boolean onKeyRelease) Return the KeyStroke that represents a given key code and modifier combination. As with the previous getKeyStroke() methods, the onKeyRelease argument determines when to fire associated actions. public static KeyStroke getKeyStroke(String representation) Returns a KeyStroke from the given representation of the keystroke. This has not been implemented as of the JDK 1.2 beta 4 release. public static KeyStroke getKeyStrokeForEvent(KeyEvent anEvent) Extracts a KeyStroke from anEvent. 27.3.2.4 Overriden Object Methods KeyStroke overrides the following methods from Object to make them more suitable to the KeyStroke class: public int hashCode() - 934 #BREAK# Java Swing - O Reilly This method provides, as the documentation puts it, a “reasonably unique” hash code for putting KeyStroke objects into hash tables. public boolean equals(Object anObject) Compares all of the KeyStroke properties to determine if two keystrokes are equivalent. public String toString() Produces a string equivalent of the KeyStroke object. The modifiers and onKeyRelease properties are represented as appropriate. 27.3.3 The MouseInputAdapter Class This simple implementation of the MouseInputListener interface (which is itself just a conglomeration of the MouseListener and MouseMotionListener interfaces) provides empty methods for each of the mouse event handlers. You can use this abstract convenience class like any other adapter, extending it and overriding only the methods that interest you. This one simply has the benefit of handling both mouse and mouse motion events. 27.3.3.1 Methods public void mouseClicked(MouseEvent e) public void mousePressed(MouseEvent e) public void mouseReleased(MouseEvent e) public void mouseEntered(MouseEvent e) public void mouseExited(MouseEvent e) These methods come from the MouseListener interface. All have empty implementations. public void mouseDragged(MouseEvent e) public void mouseMoved(MouseEvent e) These methods come from the MouseMotionListener interface. Both have empty implementations. 27.3.3.2 The SwingPropertyChangeSupport Class Many Swing components support bound properties as defined by the JavaBeans specification. In the java.beans package, a utility class called PropertyChangeSupport is defined to help you register property change listeners and fire property change events. The PropertyChangeSupport class does this work in a thread-safe manner that consumes a good bit of memory. The SwingPropertyChangeSupport class provides exactly the same set of features, but does so without thread-safety to reduce memory usage and increase performance. If you’re building your own components, you can use this class instead of PropertyChangeSupport. (For more information on JavaBeans and bound properties, check out O’Reilly’s Developing Java Beans, by Robert Englander.) 27.3.3.3 Constructor public SwingPropertyChangeSupport(Object sourceBean) - 935 #BREAK# Java Swing - O Reilly This constructor creates a new SwingPropertyChangeSupport object with a reference to sourceBean kept for use in reporting events. The sourceBean will be listed as the source for all property change events coming from this support object. 27.3.3.4 Methods public void addPropertyChangeListener(PropertyChangeListener listener) public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) public void removePropertyChangeListener(PropertyChangeListener listener) public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) Add and remove PropertyChangeListener objects interested in receiving property change events. If you give a propertyName, only changes to the specified property will be reported. public void firePropertyChange(String propertyName, Object oldValue, Object newValue) Creates a new PropertyChangeEvent object from propertyName, oldValue and newValue, then it fires it to any registered listeners. public void firePropertyChange(PropertyChangeEvent evt) Fires an existing PropertyChangeEvent, evt, to any registered listeners. public boolean hasListeners(String propertyName) Returns true if there are any listeners registered for the given propertyName. If a generic listener is present, this method returns true, regardless of whether or not any specific property listeners exist. 27.4 Image Utilities The last category of utility classes to look at is image utilities. The Swing package contains a class that can come in handy for generating images. 27.4.1 The GrayFilter Class The GrayFilter class is an extension of the java.awt.image.RGBImageFilter class. This class contains a static method that returns a “disabled” version of an image passed in. The image is converted to a grayscale version, and some lighter parts of the image are amplified to ensure the image is recognizable. All of the components that can display images use this class to present a default disabled version of the image if an explicit disabled image was not provided. 27.4.1.1 Constructors public GrayFilter(boolean brighter, int percent) Creates an instance of the GrayFilter class that you can use to do your own filtering. (Normally you don’t call this, but use createDisabledImage() instead.) Both the brighter and percent arguments are used to convert color pixels to appropriately shaded gray pixels. - 936 #BREAK# Java Swing - O Reilly 27.4.1.2 Image Methods public static Image createDisabledImage(Image i) Use this method to retrieve a grayed-out version of the image i. This method creates an instance of the GrayFilter class with brighter turned on and a gray percent of 50. public int filterRGB(int x, int y, int rgb) Overrides the filterRGB() method in RGBImageFilter, converts the rgb pixel to a gray pixel, and returns that. 27.4.2 The Renderer Interface The Swing package includes a Renderer interface with the following methods: public Component getComponent() Returns a Component you can use with something like the SwingUtilities.paintComponent() method to draw the component. public void setValue(Object aValue, boolean isSelected) This method can initialize the rendering component to reflect the state of the object aValue. This interface could be useful if you were to create a library of renderers for use with your own applications; however, it is not implemented anywhere in the Swing package as of the JDK1.2 beta4 release. 28.1 Creating Your Own Component So you’ve been bitten by the bug. There isn’t a component anywhere in the Swing library that fits your needs, and you’ve decided that it’s time to write your own. Unfortunately, you’re dreading the prospect of creating one, because either you’ve heard somewhere that it is a complex task, or your jaw is still bouncing on the floor after browsing through some of the Swing component source code. This section helps to dispel those fears. Creating your own component isn’t hard just extend the JComponent class with one of your own and away you go! On the other hand, getting it to behave or even display itself correctly can take a bit of patience and fine tuning. As such, we’ve provided a step-by-step guide below as an aid to wary programmers that keep running into those hidden “gotchas” when creating their own components. Remember that when creating Swing components, it’s always preferable to create one that adheres to the JavaBeans standards. Not only can your component be used programmatically, but it can also be inserted into one of a variety of GUI-builder tools that are prevalent in the market. Therefore, whenever possible, we try to highlight areas that you can work on to make your components more JavaBeans friendly. 28.1.1 Creating the Component First things first. If you haven’t already, you should read through the JComponent section of Chapter 3. This will help you get a feel of what sort of features you can expect in a Swing component, and - 937 #BREAK# Java Swing - O Reilly which ones you might want to use (or even disable) in your own component. If you are creating a component that is intended as a container, be sure to glance at the overview sections on focus managers and layout managers as well.[1] Remember that you can use any layout manager with a Swing component, including those from AWT as well as a few new layout managers exclusively in Swing. [1] This is sort of confusing. Because of the class hierarchy of JComponent, all classes that extend it are capable of acting as containers. For example, it is legal to add a JProgressBarto a JSlider. Clearly, the slider is not meant to act as a container, but Swing will allow it nevertheless…with undefined results. After you’ve done that, you’re ready to start. Let’s go through some steps that will help you pound out that component idea into workable Swing code. 28.1.1.1 You Should Have a Model and a UI Delegate If you really want to develop your idea into a true Swing component, you should adhere to the MVC-based architecture of Swing. This means defining models and UI delegates for each component. Recall that the model is in charge of storing the state information for the component. Models typically implement their own model interface, which outlines the accessors and methods that the model must support. The UI delegate is responsible for painting the component and handling any input events that are generated. The UI-delegate object always extends the ComponentUI class, which is the base class for all UI-delegate objects. Finally, the component class itself extends the abstract JComponent, and ties together the model and the delegate. Figure 28.1. The three parts of a Swing component Figure 28.1 shows the key classes and interfaces that are involved in creating a Swing component. The shaded boxes indicate items that the programmer must provide. This includes the model, the basic UI delegate and its type class, and an implementation of the component to bundle the model and UI delegate pieces together. Finally, you may need to create your own model interface if one does not exist that is suitable to your needs. If you wish to support multiple look-and-feels with your component, you may consider breaking your UI-delegate class down into an abstract implementation of functionality that is independent of look-and-feel (such as those classes found in javax.swing.plaf.basic), as well as functionality specific to each look-and-feel (such as those in the javax.swing.plaf.metal package or the com.sun.java.swing.plaf.motif package). Some common functionality that you might find in - 938 #BREAK# Java Swing - O Reilly the former is the ability to handle various mouse or keyboard events, while painting and sizing the component is typically the domain of the latter. See Chapter 26, for more details on look-and-feels. So now that we know what we have to build, let’s continue our discussion with a look at each one, starting with the model. 28.1.2 Creating a Model The model of the object is responsible for storing the state data of the component. Models are not hard to build, but they are not necessarily easy either. Here are some important tips to think about when working with models. 28.1.2.1 Reuse or Extend Existing Models Whenever Possible This is sound advice. Creating a data model from scratch looks trivial, but it typically takes more time and effort than most people think. Remember that good models are abstractions of component state, and are often capable of representing more than one type of component. For example, the BoundedRangeModel serves the JSlider, JProgressBar, and JScrollBar components. In addition, models are responsible for storing event listeners, handling synchronization issues, and firing property change events to the components that use them. A great deal of time was spent in creating the individual models for the Swing components. And because they are central to the functionality of the Swing components, you can be assured that they’re well tested. For example, with the jog shuttle example that we’ve created, shown later, we decided to reuse the BoundedRangeModel. This model does an excellent job with any component that contains a value within a closed range. Chances are that there might already be a model that will suit your needs, and you can either reuse or extend it to your liking. Table 28.1 summarizes the Swing component models that we cover in this book. This should give you a good feel for whether a certain data model can be reused or extended in your own component. For an example of a component built with an existing model, take a look at Chapter 16. Table 28.1, Swing Models Model Chapter Description ButtonModel 5 Holds the state of a button (like JButton), including its value, whether or not it is enabled, armed, selected, or pressed, and supports “rollover” images BoundedRangeModel 6 Holds a value that can vary between fixed maximum and minimum limits; used for JSlider, JProgressBar, JScrollBar, and their relatives ComboBoxModel 7 Holds the elements of a list, and a single selected element; used for JComboBox ListModel 7 Holds the elements of a list (as in a JList) ListSelectionModel 7 Holds one or more elements selected from a list SingleSelectionModel 14 Holds an index into an array of possible selections; used by JMenuBar and JPopupMenu TableModel 15 Holds a two-dimensional array of data; the basis for JTable TableColumnModel 15 Controls the manipulation of columns in a table TreeModel 17 Holds items that can be displayed with branches; used by JTree TreeSelectionModel 17 Holds one or more elements selected from a tree Document 20 Holds the content (i.e., text) of a document that might be displayed in an editor; used by the text components 28.1.2.2 Decide on Properties and Create the Model Interface - 939 #BREAK# Java Swing - O Reilly This is the fun part. You should decide which properties will be located in the model and how to access them. Properties can be read-write, read-only, or write-only. They can be any type of object or primitive data type. Also, according to the JavaBeans standard, properties can be indexed, as well as bound or constrained. For an explanation of these qualifiers, see Table 28.2. Table 28.2, Property Types Property Type Description Bound The property must send a PropertyChangeEvent to all registered listeners when it changes state Indexed The property is an array of objects or values. Accessors must provide an index to determine which element they want to set or retrieve Constrained The property must fire a VetoableChangeEvent to all registered listeners before it changes state. Any one listener is allowed to veto the state change, at which point the original property state is preserved As you are probably aware, there are three types of accessors that you will commonly use for object properties: “get,” “set,” and “is.” You can use the “get” accessor to retrieve an object or primitive property, the “set” accessor to reset the value of an object or primitive property, and the “is” accessor to retrieve a boolean property from a component. (For boolean properties, developers tend to provide an “is” accessor and omit the “get,” but it’s not necessary to follow that convention.) The JavaBeans standard states that property accessors should adhere to the method signatures shown in Table 28.3. The italicized PropertyType in the table should reflect the object or primitive type of the property. Table 28.3, Method Signatures for Property Accessors Type “get” Accessor “set” Accessor “is” Accessor
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.