A catalog of swing components
Now that you understand layout managers and the event model, you're ready to see how Swing components can be used. This section is a non-exhaustive tour of the Swing components and features that you'll probably use most of the time. Each Example Is Intended to Be Reasoned SMALL SO That You Can Easily Lift The Code and Use IT IN Your Own Programs. Feedback
Keep in Mind:
You can Easily See What Each of these Examples Looks Like While Running by Viewing The Html Pages in The Downloadable Source Code for this Chapter (www.bruceeckel.com). Feedback
The JDK Documentation from Java.sun.com Contains All of The Swing Classes and Methods (ONLY A FEW Are Shown Here). Feedback
Because of the naming convention used for Swing events, it's fairly easy to guess how to write and install a handler for a particular type of event. Use the lookup program ShowAddListeners.java from earlier in this chapter to aid in your investigation of a particular component FEEDBACK
When Things Start To Get Complicated You Should Graduate To A Gui Builder. Feedback
Buttons
Swing includes a number of different types of buttons. All buttons, check boxes, radio buttons, and even menu items are inherited from AbstractButton (which, since menu items are included, would probably have been better named "AbstractSelector" or something equally general) You'll See The Use of Menu Items Shortly, But The Following Example Shows The Various Types of Buttons Available: Feedback
This begins with the BasicArrowButton from javax.swing.plaf.basic, then continues with the various specific types of buttons. When you run the example, you'll see that the toggle button holds its last position, in or out. But the check Boxes and Radio Buttons Behave Identical To Each Other, Just Clicking ON OR Off (They Are Inherited from Jtogglebutton). FeedbackButton Groups
If you want radio buttons to behave in an "exclusive or" fashion, you must add them to a "button group." But, as the following example demonstrates, any AbstractButton can be added to a ButtonGroup. Feedback
To avoid repeating a lot of code, this example uses reflection to generate the groups of different types of buttons. This is seen in makeBPanel (), which creates a button group and a JPanel. The second argument to makeBPanel () is an array of String. For each string, a button of the class represented by the first argument is added to the jPanel:
The title for the border is taken from the name of the class, stripping off all the path information. The AbstractButton is initialized to a JButton that has the label "Failed," so if you ignore the exception message, you'll still see the problem on screen. The getConstructor () method produces a Constructor object that takes the array of arguments of the types in the Class array passed to getConstructor (). Then all you do is call newInstance (), passing it an array of Object containing your Actual Arguments-in this case, just the string from the IDs array. feedback
This adds a little complexity to what is a simple process. To get "exclusive or" behavior with buttons, you create a button group and add each button for which you want that behavior to the group. When you run the program, you'll See That All The Buttons Except JButton EXHIBIT THIS "Exclusive or" Behavior. FeedBackicons
You can use an Icon inside a JLabel or anything that inherits from AbstractButton (including JButton, JCheckBox, JRadioButton, and the different kinds of JMenuItem). Using Icons with JLabels is quite straightforward (you'll see an example later). The following example Explores all the additional ways you can use icons with buttons and their descendants. feedback
You can use any gif files you want, but the ones used in this example are part of this book's code distribution, available at www.BruceEckel.com. To open a file and bring in the image, simply create an ImageIcon and hand it the Fer name. from kiln, you can use the resulting icon in Your Program. Feedback
An Icon can be used as an argument for many different Swing component constructors, but you can also use setIcon () to add or change an Icon. This example also shows how a JButton (or any AbstractButton) can set the various different sorts of icons That Appear When Things Happen That Button: When It's Pressed, Disabled, or "Rolled Over". You'll See THAS GIVES The Button A Nice Animated Feel. Feedback
Tool tips
The previous example added a "tool tip" to the button. Almost all of the classes that you'll be using to create your user interfaces are derived from JComponent, which contains a method called setToolTipText (String). So, for virtually anything you Place On Your Form, All You NEED To Do Is Say (for An Object JC of Any Jcomponent-Derived Class): JC.SetTooltiptext ("My TIP");
And when the mouse stays over That Jcomponent for a predetermined period of time, a tiny box containing your text will pop up next to the mouse. feedback
Text Fields
This Example Shows The Extra Behavior That JtextFields Are Capable of:
The JTextField t3 is included as a place to report when the action listener for the JTextField t1 is fired. You'll see that the action listener for a JTextField is fired only when you press the "enter" key. Feedback
The JTextField t1 has several listeners attached to it. The T1 listener addition is a DocumentListener that responds to any change in the "document" (the contents of the JTextField, in this case). It automatically copies all text from t1 into t2 In. , t1's document is set to a derived class of PlainDocument, called UpperCaseDocument, which forces all characters to uppercase. It automatically detects backspaces and performs the deletion, adjusting the caret and handling everything as you would expect. Feedback
Borders
JComponent contains a method called setBorder (), which allows you to place various interesting borders on any visible component. The following example demonstrates a number of the different borders that are available, using a method called showBorder () that creates a JPanel and puts on THE BORDER IN Each Case. Also, IT Uses Rtti To Find The Name of The Border That You're Using Off All The Path Information Your OWN BORDERS AND PUT THEM INSIDE button, labels, etc.-anything derived from jComponent. feedback
Jscrollpanes
Most of the Time You'llpane Do Its Job, But you can Also Control Which Scroll Bars Are Allowed-Vertical, Horizontal, Both, or Neither:
Using Different Arguments in The Jscrollpane Constructor Controls The Scrollbars That Are Available. This Example Also Dresses on a bit sale borders. Feedback
A mini-editor
The JtextPane Control Provides a Great DEAL OF Support for Editing, WITHOUT MUCH EFfort. The Following Example Makes Very Simple Use of this Component, Ignoring The Bulk of The FunctionAlicity of the class:
The button just adds randomly generated text. The intent of the JTextPane is to allow text to be edited in place, so you will see that there is no append () method. In this case (admittedly, a poor use of the capabilities of JTextPane ), the text must be capt, modified, and discount back intet (). Feedback
As mentioned before, the default layout behavior of an applet is to use the BorderLayout. If you add something to the pane without specifying any details, it just fills the center of the pane out to the edges. However, if you specify one of the surrounding regions (NORTH, SOUTH, EAST, or WEST) as is done here, the component will fit itself into that region;. in this case, the button will nest down at the bottom of the screen FeedbackNotice the built-in features of JTextPane Such as automatic line wrapping. There are lots of other features That You can look up using the jdk documentation. Feedback
Check Boxes
A CHECK BOX PROVIDES A WAY TO MAKE A SINGLE ON / OFF CHOICE. IT Consists Of A Tiny Box and a Label. The Box Typically Holds A Little "X" (OR SOME Other Indication That IT) or is Empty, Depending ON WHETER THAT ITEM WAS SELECTED. Feedback
You'll normally create a JCheckBox using a constructor that takes the label as an argument. You can get and set the state, and also get and set the label if you want to read or change it after the JCheckBox has been created. Feedback
Whenever a JCheckBox is set or cleared, an event occurs, which you can capture the same way you do a button:. By using an ActionListener The following example uses a JTextArea to enumerate all the check boxes that have been checked:
The trace () method sends the name of the selected JCheckBox and its current state to the JTextArea using append (), so you'll see a cumulative list of the checkboxes that were selected and what their state is. Feedback
Radio buttons
The concept of a radio button in GUI programming comes from pre-electronic car radios with mechanical buttons;.. When you push one in, any other button that was pressed pops out Thus, it allows you to force a single choice among many FeedbackAll you need to do to set up an associated group of JRadioButtons is to add them to a ButtonGroup (you can have any number of ButtonGroups on a form). One of the buttons can optionally have its starting state set to true (using the second argument in The constructor). if you try To Set More Than One Radio Button to True, The ONLY The Final One Set Will Be true. Feedback
Here's a Simple EXAMPLE of The Use of Radio Buttons. Note That You Capture Radio Button Events Like All Others:
To Display The State, A Text Field Is Used. This Field Is Set To Non-Editable Because It's Used Only To Display Data, Not To Collect It. Thus it is an alternative to use a jlabel. Feedback
Combo Boxes (Drop-Down Lists)
Like a group of radio buttons, a drop-down list is a way to force the user to select only one element from a group of possibilities. However, it's a more compact way to accomplish this, and it's easier to change the elements of the List without surprising the user. (You Chan Change Radio Buttons Dynamically, Buthat TENDS To BE Visibility Jarring). Feedback
By default, JComboBox box is not like the combo box in Windows, which lets you select from a list or type in your own selection. To produce this behavior you must call setEditable (). With a JComboBox box, you choose one and only one Element from the list. in The Following Example, The Jcombobox Box Starts with a Certain Number of Entries, And The New Entries Areadded to the Box When A Button IS Pressed. Feedback
THE JTEXTFIELD DISPLAYS The "SELECTED INDEX," SELECTED INDEX, "SELECTED INDEX, AS Well As The Text of The Selected Item in The Combo Box. Feedbacklist Boxes
List boxes are significantly different from JComboBox boxes, and not just in appearance. While a JComboBox box drops down when you activate it, a JList occupies some fixed number of lines on a screen all the time and does not change. If you want to See The item (), WHICH Produces An Array of String of the items there is since
A JList allows multiple selection;. If you control-click on more than one item (holding down the "control" key while performing additional mouse clicks), the original item stays highlighted and you can select as many as you want If you select an Item, Then Shift-Click ANOTHER ITEM, All The Two Are Span Between The Two Are Selected. To Remove An Item from A Group, You CAN Control-Click It. Feedback
You can see this borders have also been added to the lists. Feedback
If you just want to put an array of Strings into a JList, there's a much simpler solution;. You pass the array to the JList constructor, and it builds the list automatically The only reason for using the "list model" in the preceding example Is So That The List Could Be Manipulate During The Execution of The Program. Feedback
Jlists Do Not Automatically Provide Direct Support for Scrolling. Of Course, All You NEED TODO IS WRAP The Jlist In a Jscrollpane, And The Details Are Automatically Managed for you. Feedback
Tabbed Panes
The JTabbedPane allows you to create a "tabbed dialog," which has file-folder tabs running across one edge, and all you have to do is press a tab to bring forward a different dialog.In Java, the use of some sort of " tabbed panel "mechanism is quite important, because in applet programming the use of pop-up dialogs is discouraged by automatically adding a little warning to any dialog that pops up out of an applet. Feedback
When you run the program, you'll see that the JTabbedPane automatically stacks the tabs if there are too many of them to fit on one row. You can see this by resizing the window when you run the program from the console command line. Feedback
Message Boxes
Windowing environments commonly contain a standard set of message boxes that allow you to quickly post information to the user or to capture information from the user. In Swing, these message boxes are contained in JOptionPane. You have many different possibilities (some quite sophisticated), .. but the ones you'll most commonly use are probably the message dialog and confirmation dialog, invoked using the static JOptionPane.showMessageDialog () and JOptionPane showConfirmDialog () The following example shows a subset of the message boxes available with JOptionPane:
To be able to write a single ActionListener, I've used the somewhat risky approach of checking the String labels on the buttons. The problem with this is that it's easy to get the label a little bit wrong, typically in capitalization, and this bug Can Be Hard to Spot. Feedback
Note That ShowOptionDialog () and showinputdialog () Provide return Objects That Contain The value entered by the user. Feedback
Menus
Each component capable of holding a menu, including JApplet, JFrame, JDialog, and their descendants, has a setJMenuBar () method that accepts a JMenuBar (you can have only one JMenuBar on a particular component). You add JMenus to the JMenuBar, and JMenuItems to the JMenus. Each JMenuItem can have an ActionListener attached to it, to be fired when that menu item is selected. FeedbackUnlike a system that uses resources, with Java and Swing you must hand assemble all the menus in source code. Here is a Very Simple Menu EXAMPLE:
The use of the modulus operator in "i% 3" distributes the menu items among the three JMenus Each JMenuItem must have an ActionListener attached to it;. Here, the same ActionListener is used everywhere, but you'll usually need an individual one for Each Jmenuitem. Feedback
JMenuItem inherits AbstractButton, so it has some button-like behaviors By itself, it provides an item that can be placed on a drop-down menu There are also three types inherited from JMenuItem:.. JMenu to hold other JMenuItems (so you can have Cascading Menus; JCheckBoxMenuItem, Which Product WHETHER That Menu Item Is SETED; And JradiobuttonMenuItem, Which Contains a Radio Button. Feedback
As a more sophisticated example, here are the ice cream flavors again, used to create menus This example also shows cascading menus, keyboard mnemonics, JCheckBoxMenuItems, and the way you can dynamically change menus.:
In this Program I Placed The Menu Items Into Arrays and Then Stepped THROUGH Each Array Calling Add () for Each Jmenuitem. This Makes Adding or Subtracting a menu Item Somewhat Less Tedious. Feedback
This program creates not one but two JMenuBars to demonstrate that menu bars can be actively swapped while the program is running. You can see how a JMenuBar is made up of JMenus, and each JMenu is made up of JMenuItems, JCheckBoxMenuItems, or even other JMenus (which produce submenus). When a JMenuBar is assembled, it can be installed into the current program with the setJMenuBar () method. Note that when the button is pressed, it checks to see which menu is currently installed by calling getJMenuBar (), then it puts the other menu bar in its place. FeedbackWhen testing for "Open," notice that spelling and capitalization are critical, but Java signals no error if there is no match with "Open." This kind of string comparison is a source of Programming Errors. Feedback
The checking and unchecking of the menu items is taken care of automatically The code handling the JCheckBoxMenuItems shows two different ways to determine what was checked:. String matching (which, as mentioned above, is not a very safe approach although you'll see IT used) and matching on the evenet target. as shown, The getState () Method Can be used to reference. You can also change the state of a jcheckboxmenuItem with setState (). Feedback
The events for menus are a bit inconsistent and can lead to confusion:. JMenuItems use ActionListeners, but JCheckBoxMenuItems use ItemListeners The JMenu objects can also support ActionListeners, but that's not usually helpful In general, you'll attach listeners to each JMenuItem, JCheckBoxMenuItem. , or JradiobuttonMenuItem, But The Example Shows ItemListener And ActionListeners Attached to the Various Menu Components. Feedback
Swing supports mnemonics, or "keyboard shortcuts," so you can select anything derived from AbstractButton (button, menu item, etc.) by using the keyboard instead of the mouse These are quite simple;. For JmenuItem, you can use the overloaded constructor that takes as a second argument the identifier for the key. However, most AbstractButtons do not have constructors like this, so the more general way to solve the problem is to use the setMnemonic () method. The preceding example adds mnemonics to the button and some of the menu items;. shortcut indicators automatically appear on the components FeedbackYou can also see the use of setActionCommand () This seems a bit strange because in each case, the "action command" is exactly the same as the label on the menu. component. Why not just use the label instead of this alternative string? The problem is internationalization. If you retarget this program to another language, you want to change only the label in the menu, and not change the cod e (which would no doubt introduce new errors). So to make this easy for code that checks the text string associated with a menu component, the "action command" can be immutable, but the menu label can change. All the code works with the "action command," so it's unaffected by changes to the menu labels. Note that in this program, not all the menu components are examined for their action commands, so those that are not do not have their action command set. Feedback
The bulk of the work happens in the listeners. BL performs the JMenuBar swapping. In ML, the "figure out who rang" approach is taken by getting the source of the ActionEvent and casting it to a JMenuItem, then getting the action command string to pass it through a cascaded if statement. FeedbackThe FL listener is simple even though it's handling all the different flavors in the flavor menu. This approach is useful if you have enough simplicity in your logic, but in general, you'll want to take the approach used with FooL, BarL, and BazL, in which each is attached to only a single menu component, so no extra detection logic is necessary, and you know exactly who called the listener. Even with the profusion of classes generated this way, the Code Inside TENDS to Be Smaller, and The Process Is More FoolProof. Feedback
You can see that menu code quickly gets long-winded and messy. This is another case where the use of a GUI builder is the appropriate solution. A good tool will also handle the maintenance of the menus. Feedback
POP-UP MENUS
The most straightforward way to implement a JPopupMenu is to create an inner class that extends MouseAdapter, then add an object of that inner class to each component that you want to produce pop-up behavior:
The Same ActionListener Is Added to Each Jmenuitem, So That IT Fetches The Text From The Menu Label and Inserts It Into the JtextField. Feedback
Drawing
In a good GUI framework, drawing should be reasonably easy-and it is, in the Swing library. The problem with any drawing example is that the calculations that determine where things go are typically a lot more complicated that the calls to the drawing routines, and these calculations are often mixed together with the drawing calls, so it can seem that the interface is more complicated than it actually is. FeedbackFor simplicity, consider the problem of representing data on the screen-here, the data will be provided by the built -in Math.sin () method, that produces a mathematical sine function. to make things a little more interesting, and to further demonstrate how easy it is to use Swing components, a slider will be placed at the bottom of the form to dynamically Control The Number of Sine Wave Cycles That Are Displayed. In Addition, if You Resize The window Wave Refits itself to the new window size. feedback
Although any JComponent may be painted and thus used as a canvas, if you just want a straightforward drawing surface, you will typically inherit from a JPanel. The only method you need to override is paintComponent (), which is called whenever that component must be repainted (you normally do not need to worry about this, because the decision is managed by Swing). When it is called, Swing passes a Graphics object to the method, and you can then use this object to draw or paint on the surface FEEDBACK
In the following example, all the intelligence concerning painting is in the SineDraw class;. The SineWave class simply configures the program and the slider control Inside SineDraw, the setCycles () method provides a hook to allow another object-the slider control, in this case-to control the number of cycles.All of the fields and arrays are used in the calculation of the sine wave points; cycles indicates the number of complete sine waves desired, points contains the total number of points that will be graphed, sines contains the sine function values, and pts contains the y-coordinates of the points that will be drawn on the JPanel. The setCycles () method creates the arrays according to the number of points needed and fills the sines array with numbers. By calling repaint ( ), setcycles () forces PainTComponent () to be called so the rest of the calculation and redraw will take place. feedback
The first thing you must do when you override paintComponent () is to call the base-class version of the method Then you are free to do whatever you like;. Normally, this means using the Graphics methods that you can find in the documentation for . java.awt.Graphics (in the JDK documentation from java.sun.com) to draw and paint pixels onto the JPanel Here, you can see that almost all the code is involved in performing the calculations; the only two method calls that actually manipulate the screen are setColor () and drawLine () you will probably have a similar experience when creating your own program that displays graphical data;. you'll spend most of your time figuring out what it is you want to draw, but the actual Drawing Process Will Be Quite Simple. Feedback
When I created this program, the bulk of my time was spent in getting the sine wave to display. Once I did that, I thought it would be nice to be able to dynamically change the number of cycles. My programming experiences when trying to do such things in other languages made me a bit reluctant to try this, but it turned out to be the easiest part of the project. I created a JSlider (the arguments are the left-most value of the JSlider, the right-most value, and the starting value, respectively, but there are other constructors as well) and dropped it into the JApplet. Then I looked at the JDK documentation and noticed that the only listener was the addChangeListener, which was triggered whenever the slider was changed enough for it to produce a different value. The only method for this was the obviously named stateChanged (), which provided a ChangeEvent object so that I could look backward to the source of the change and find the new value. By calling the sines object's setCycles () , the new value was incorporated and the JPanel redrawn. FeedbackIn general, you will find that most of your Swing problems can be solved by following a similar process, and you'll find that it's generally quite simple, even if you have not used a Particular Component Before. Feedback
If your problem is more complex, there are other more sophisticated alternatives for drawing, including third-party JavaBeans components and the Java 2D API. These solutions are beyond the scope of this book, but you should look them up if your drawing code becomes too Oneerous. feedback
Dialog Boxes
A dialog box is a window that pops up out of another window. Its purpose is to deal with some specific issue without cluttering the original window with those details. Dialog boxes are heavily used in windowed programming environments, but less frequently used in applets. FeedbackTo create a dialog box, you inherit from JDialog, which is just another kind of Window, like a JFrame. A JDialog has a layout manager (which defaults to BorderLayout), and you add event listeners to deal with events. One significant difference when the Dialog Window Is Closed Is That You Don't Want To Shut Down The Application. INSTEAD, You Release The Resources Used by The Dialog's WINDOW BY CALLING DILOG'S. Here's a Very Simple Example:
Once the JDialog Is Created, The show () Method Must Be Called To Display and Activate It. For the Dialog To Close, It Must Call Dispose (). Feedback
You'll see that anything that pops up out of an applet, including dialog boxes, is "untrusted." That is, you get a warning in the window that's been popped up. This is because, in concept, it would be possible to fool users into thinking that they're dealing with a regular native application and to get them to type in their credit card number, which then goes across the Web. An applet is always attached to a Web page and visible within your Web browser, while A Dialog Box Is Detached-So Theoretical, It's Possible. As a result, it is not so common to see an applet what buyes a dialog box. feedback
The following example is more complex; the dialog box is made up of a grid (using GridLayout) of a special kind of button that is defined here as class ToeButton This button draws a frame around itself and, depending on its state, a blank. , an "x," o "in the middle. it starts out blank, and then depending on whose Turn it is, changes to an" x "OR AN" o. "HOWEVER, IT WILL ALSO FLIP Back and Forth Between "X" and "o" when You Click On The Button (this Makes The TiC-Tac-ToE Concept Only Slightly More Annoying Than IT Already IS.) In Addition, The Dialog Box Can Be Set Up for Any Number of Rows And Column By Changing Numbers in The Main Application Window.Because Statics Can Only Be at The Outer Level of The Class, Inner Classes Cannot Have Static Data or Nested Classes. Feedback
THE PAINTComponent () Method Draws The Square Around The Panel and The "x" or the "o." This is full of tedious cagculation, but it's straightforward. Feedingback
A mouse click is captured by the MouseListener, which first checks to see if the panel has anything written on it. If not, the parent window is queried to find out whose turn it is, which establishes the state of the ToeButton. Via the inner class mechanism, the ToeButton then reaches back into the parent and changes the turn. If the button is already displaying an "x" or an "o," then that is flopped. You can see in these calculations the convenient use of the ternary if -ELSE Described in Chapter 3.After a state change, The Toebutton Is Repainted. Feedback
THE CONSTRUCTOR for TOEDIALOG IS QUITE SIMPLE; IT Adds Into A GridLayout As Many Buttons As You Request, The Resizes It for 50 Pixels on a Side for Each Button. Feedback
TicTacToe sets up the whole application by creating the JTextFields (for inputting the rows and columns of the button grid) and the "go" button with its ActionListener. When the button is pressed, the data in the JTextFields must be fetched, and, since Turned INTO INTS Using The Static Integer.Parseint () Method. FeedbackFile Dialogs
Some operating systems have a number of special built-in dialog boxes to handle the selection of things such as fonts, colors, printers, and the like. Virtually all graphical operating systems support the opening and saving of files, so Java's JFileChooser encapsulates these for Easy Use. Feedback
The following application exercises two forms of JFileChooser dialogs, one for opening and one for saving Most of the code should by now be familiar, and all the interesting activities happen in the action listeners for the two different button clicks.:
Note That there is aful to jfilechooser, incruding filters to narrow the file names you will allow. Feedback
For an "open file" dialog, you call showOpenDialog (), and for a "save file" dialog, you call showSaveDialog (). These commands do not return until the dialog is closed. The JFileChooser object still exists, so you can read data from it. The methods getSelectedFile () and getCurrentDirectory () are two ways you can interrogate the results of the operation. If these return null, it means the user canceled out of the dialog. Feedback
HTML on Swing Components
Any Component Take HTML TEXT CAN Also Take Html Text, Which It Will Reformat According to HTML Rules. This Means You CAN VERY Easily Add Fancy Text To A Swing Component. For example:
You must start the text with "," and then you can use normal HTML tags. Note that you are not forced to include the normal closing tags. FeedbackThe ActionListener adds a new JLabel to the form, which also contains HTML text. However, this label is not added during init (), SO you must call the contact of forward a re-layout of the new label. Feedback
You can Also Use HTML Text for JTabbedpane, JMenuItem, JTooltip, Jradiobutton, and JCheckbox. Feedback
Sliders and Progress Bars
A slider (which has already been used in SineWave.java) allows the user to input data by moving a point back and forth, which is intuitive in some situations (volume controls, for example). A progress bar displays data in a relative fashion From "ful" to "Empty" so the user gets a persftive. My favorite example for these is to simply hook the slider to the program, the progress bar changes aciding--
THE Key to hooking the two components together is in sharing their model, in the line: feedback
Pb.SETMODEL (SB.GetModel ());
Of Course, You Could Also Control The Two Using A Listener, but this is more straightforward for Simple Situations.
The JProgressBar Is Fairly Straightforward, But The Jslider Has A Lot of Options, Such as The Orientation and Major and Minor Tick Marks. NOTICE How StraightForward It is to add A Titled Border. Feedback
TREES
Using a Jtree Can Be As Simple As Saying:
Add (New Object [] {"this", "That", "Other"});
This displays a primitive tree. The API for trees is vast, however-certainly one of the largest in Swing. It appears that you can do just about anything with trees, but more sophisticated tasks might require quite a bit of research and experimentation. FeedbackFortunately , there is a middle ground provided in the library: the "default" tree components, which generally do what you need So most of the time you can use these components, and only in special cases will you need to delve in and understand trees. More deeply. Feedback
. The following example uses the "default" tree components to display a tree in an applet When you press the button, a new subtree is added under the currently selected node (if no node is selected, the root node is used): Feedback
The first class, Branch, is a tool to take an array of String and build a DefaultMutableTreeNode with the first String as the root and the rest of the Strings in the array as leaves. Then node () can be called to produce the root of "Branch." Feedback
The Trees class contains a two-dimensional array of Strings, from which Branches can be made, and a static int i to count through this array. The DefaultMutableTreeNode objects hold the nodes, but the physical representation on screen is controlled by the JTree and its Associated Model, The Defaulttreemodel. Note That When THE JTREE IS ADDED TO The Applet, IT IS Wrapped In a Jscrollpane-this Is All It Takes To Provide Automatic Scrolling. Feedback
The JTree is controlled through its model. When you make a change to the model, the model generates an event that causes the JTree to perform any necessary updates to the visible representation of the tree. In init (), the model is captured by calling getModel (). When the button is pressed, a new "branch" is created. Then the currently selected component is found (or the root is used if nothing is selected) and the model's insertNodeInto () method does all the work of changing the tree and causing it to be updated. FeedbackAn example like the preceding one may give you what you need in a tree. However, trees have the power to do just about anything you can imagine-everywhere you see the word "default" in the preceding example, you can substitute your own class to get different behavior But beware:. Almost all of these classes have a large interface, so you could spend a lot of time struggling to understand the intricacies of trees Despite this, it's a good design,. And the alternative S Are USUALLY MUCH WORSE. FEEDBACK
Tables
Like trees, tables in Swing are vast and powerful. They are primarily intended to be the popular "grid" interface to databases via Java Database Connectivity (JDBC, discussed in Thinking in Enterprise Java), and thus they have a tremendous amount of flexibility, which you pay for in complexity. There's easily enough here to allow the creation of a full-blown spreadsheet application and could probably justify an entire book. However, it is also possible to create a relatively simple JTable if you understand the basics. Feedback
The JTable controls how the data is displayed, but the TableModel controls the data itself. So to create a JTable, you'll typically create a TableModel first. You can fully implement the TableModel interface, but it's simpler to inherit from the helper class AbstractTableModel :. DataModel contains an array of data, but you could also get the data from some other source such as a database The constructor adds a TableModelListener that prints the array every time the table is changed The rest of the methods follow the Beans naming convention. (using "get" and "set" methods, which will be described later in this chapter) and are used by JTable when it wants to present the information in DataModel. AbstractTableModel provides default methods for setValueAt () and isCellEditable () that prevent changes To the data, so if you want to be aable to edit the data, you must overrides. Feedback
Once you have a TableModel, you only need to hand it to the JTable constructor. All the details of displaying, editing, and updating will be taken care of for you. This example also puts the JTable in a JScrollPane. Feedback
Selecting Look & Feel
"Pluggable Look & Feel" allows your program to emulate the look and feel of various operating environments. You can even do all sorts of fancy things, like dynamically changing the look and feel while the program is executing. However, you generally just want to do one of two things: either select the "cross platform" look and feel (which is Swing's "metal"), or select the look and feel for the system you are currently on so your Java program looks like it was created specifically for that system (this is almost certainly the best choice in most cases, to avoid confounding the user). The code to select either of these behaviors is quite simple, but you must execute it before you create any visual components, because the components will be made based on the current look and feel, and will not be changed just because you happen to change the look and feel midway during the program (that process is more complicated and uncommon, and is relegated to Swing-specific books). FeedbackActually, if you want to use the cross-platform ( "metal") look and feel that is characteristic of Swing programs, you do not have to do anything-it's the default. But if you want instead to use the current operating environment's look and Feel, You Just Insert The Following Code, Typically At the Beginning of Your Main (), But at Least Before Any Components Areadded:
Try {
UIManager.SetLookAndfeel (UIManager.
GetsystemLookandfeelclassName ());
} catch (exception e) {
Throw new runtimeException (e);
}
You do not need anything in the catch clause because the UIManager will default to the cross-platform look and feel if your attempts to set up any of the alternatives fail. However, during debugging the exception can be quite useful, so you may at . least want see some results via the catch clause FeedbackHere is a program that takes a command-line argument to select a look and feel, and shows how several different components look under the chosen look and feel:
You can see that one option is to explicitly specify a string for a look and feel, as seen with MotifLookAndFeel However, that one and the default "metal" look and feel are the only ones that can legally be used on any platform;. Even though there are strings for Windows and Macintosh look and feels, those can only be used on their respective platforms (these are produced when you call getSystemLookAndFeelClassName () and you're on that particular platform). Feedback
It is also possible to create a custom look and feel package, for example, if you are building a framework for a company that wants a distinctive appearance. This is a big job and is far beyond the scope of this book (in fact, you 'll discover it is beyond the scope of many dedicated swing books!). Feedback
CLIPBOARD
The JFC supports limited operations with the system clipboard (in the java.awt.datatransfer package). You can copy String objects to the clipboard as text, and you can paste text from the clipboard into String objects. Of course, the clipboard is designed to hold any type of data, but how this data is represented on the clipboard is up to the program doing the cutting and pasting. The Java clipboard API provides for extensibility through the concept of a "flavor." When data comes off the clipboard, it has an associated set of flavors that it can be converted to (for example, a graph might be represented as a string of numbers or as an image), and you can see if that particular clipboard data supports the flavor you're interested in . FeedbackThe following program is a simple demonstration of cut, copy, and paste with String data in a JTextArea. One thing you'll notice is that the keyboard sequences you normally use for cutting, copying, and pasting also work. But if you look AT Any Jtex tField or JTextArea in any other program, you'll find that they also automatically support the clipboard key sequences. This example simply adds programmatic control of the clipboard, and you could use these techniques if you want to capture clipboard text into something other than a JtextComponent.
The creation and addition of the menu and jtextarea surplend. What's Different Is The Creation of The Clipboard Field Clipbd, Which Is Done Through The Toolkit. Feedback
All the action takes place in the listeners. The CopyL and CutL listeners are the same except for the last line of CutL, which erases the line that's been copied. The special two lines are the creation of a StringSelection object from the String and the call to setContents () with this StringSelection. That's all there is to putting a String on the clipboard. FeedbackIn PasteL, data is pulled off the clipboard using getContents (). What comes back is a fairly anonymous Transferable object, and you do not really know what it contains. One way to find out is to call getTransferDataFlavors (), which returns an array of DataFlavor objects indicating which flavors are supported by this particular object. you can also ask it directly with isDataFlavorSupported (), passing in the flavor you . 're interested in Here, however, the bold approach is taken: getTransferData () is called, assuming that the contents supports the String flavor, and if it does not, the problem is sorted out in the exceptio N Handler. Feedback
In The Future You Can Expect More Data Flavors to Be Supported