Section 10.7. Swing and AWT

   

10.7 Swing and AWT

In this section, we will take a cursory look at writing GUI applications. A graphical user interface is the portion of your program that a user interacts with directly. The Abstract Windowing Toolkit and Swing extension classes are what you use to create GUIs in Java.

Swing and AWT are very large topics. In fact, these two packages alone define more than half of the Java API. They can be difficult to work with, because their class hierarchies are complex. We do not have world enough and time here to cover these topics closely, as this book is more geared toward Java for the Web programmer.

We will look at these topics briefly , however, for two reasons. First, they are an important part of the Java world. Any program you write in Java Standard Edition will run from one of three primary places:

  • The command line, as most of our programs have thus far

  • Via a Web-based client such as a .jsp , a .cfm page, or a Web service

  • With a graphical user interface

Even if you are not interested in becoming a software engineer, there is a second reason to understand the AWT and Swing APIs: using them is often a requirement for writing applets. So this section will test our ability to use what we already know about Java's object-oriented structures to put an unfamiliar package to use.

You already know that there are other ColdFusion form controls that require the 5-MB Java plugin to run, because they run as applets on the client, and they are written in Java. These are not written entirely from scratch, however. With a little knowledge of the API and some effort, you can write your own < cfslider > control, for instance. Think of the < cftextinput > control ”you'll find its corresponding Swing class in JTextField . We are all familiar with the wonder and excitement that is < cftree > . These controls were rewritten for ColdFusion 5 to implement new Swing libraries.

In this section, we will create our own version of the <cftree> control, using the libraries already available in javax.Swing and java.awt .

10.7.1 MakeTree.java

 package javaforcf.chp10;  /* uses TreeConrol and TreeFrame   to create a tree control similar   to <cftree>.   Requires classes from AWT and Swing   libraries.   */ import javax.swing.UIManager; public class MakeTree {     // main   public static void main(String[] args) {     try {         // sets the look of the icons used         // this is the JLF (Java Look and Feel),         // and it might look familiar from the Forte IDE       String s = UIManager.getCrossPlatformLookAndFeelClassName();       // alternatively, you can get the look and feel       //  for user's system like this:       // String s = UIManager.getSystemLookAndFeelClassName()             UIManager.setLookAndFeel(s);     }     catch(Exception e) {       e.printStackTrace();     }       // instantiate the object     new TreeControl();   }  } 

10.7.2 TreeControl.java

 package javaforcf.chp10;    // abstract window toolkit   // we need this for the Frame class import java.awt.*;   // swing libraries allow complex user interfaces   // that are easy to use import javax.swing.UIManager; public class TreeControl {   boolean packFrame = false;   // public constructor   public TreeControl() {     TreeFrame frame = new TreeFrame();     /* a java.awt.Frame makes a top-level     window with a title and a border */     //Validate frames that have preset sizes     //Pack frames that have useful preferred size info, e.g., from their layout     /*     if (packFrame) {       frame.pack();     }     else {       frame.validate();     }     */     /*       here we center the window. To do this       we need to get the screen size, then       get the size of our frame.     */     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();     Dimension frameSize = frame.getSize();       /* next subtract the width of the frame        from the width of screen, and divide by two.        do the same for height        that centers your frame.       */     frame.setLocation((screenSize.width - frameSize.width) / 2,            (screenSize.height - frameSize.height) / 2);            // you must show the frame explicitly     frame.setVisible(true);   } } 

10.7.3 TreeFrame.java

[View full width]
 
[View full width]
package javaforcf.chp10; // tools for making windows, // controls, and event listeners // and handlers import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; // API's built in tree control import javax.swing.tree.*; public class TreeFrame extends JFrame { /* FIELDS */ // container to hold controls JPanel contentPane; // tree DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root Directory"); JTree jTree1 = new JTree(top); JScrollPane treeView = new JScrollPane(jTree1); DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer(); // menu bar and items JMenuBar jMenuBar1 = new JMenuBar(); JMenu menuFile = new JMenu(); // "Close" item in File menu JMenuItem menuFileClose = new JMenuItem(); //create the editor pane JEditorPane jEditorPane1 = new JEditorPane(); JButton jButton1 = new JButton(); // items for tree // directory DefaultMutableTreeNode dir1 = null; // files DefaultMutableTreeNode file1 = null; DefaultMutableTreeNode file1_sub1 = null; // second directory DefaultMutableTreeNode dir2 = null; // files DefaultMutableTreeNode file2 = null; DefaultMutableTreeNode file2_sub1 = null; /* CONSTRUCTOR */ public TreeFrame() { // root event class for selecting AWT events enableEvents(AWTEvent.WINDOW_EVENT_MASK); try { initialize(); } catch(Exception e) { e.printStackTrace(); } } /* METHODS */ // initialize components public void initialize() throws Exception { // our container for UI controls contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(null); // sets the title in the window // like HTML <title> tag this.setTitle("Start of <cftree>"); // set window size (width, height) this.setSize(new Dimension(525, 200)); // add menu bar this.setJMenuBar(jMenuBar1); // make tree and add event listeners makeNodes(top); jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel .SINGLE_TREE_SELECTION); // show the handle on directories? jTree1.setShowsRootHandles(true); // allow editing of (typing over) the labels? jTree1.setEditable(false); jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { jTree1_valueChanged(e); } }); // set specs on tree viewing pane treeView.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // in the javax.swing.BorderFactory treeView.setViewportBorder(BorderFactory.createRaisedBevelBorder()); // coordinates for drawing the tree viewer rectangle pan // start from left, from top, width, height treeView.setBounds(new Rectangle(10, 10, 235, 110)); //initializes menu items and creates event listeners menuFile.setText("File"); menuFileClose.setText("Close"); menuFileClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { menuFileExit_actionPerformed(e); } }); // set up message panel jEditorPane1.setBorder(BorderFactory.createEtchedBorder()); // coordinates for message panel jEditorPane1.setBounds(new Rectangle(250, 20, 260, 50)); jEditorPane1.setFont(new java.awt.Font("Dialog", 1, 10)); jEditorPane1.setBackground(Color.white); //add items to content pane jMenuBar1.add(menuFile); // add "Close" option under File menu menuFile.add(menuFileClose); contentPane.add(treeView, null); contentPane.add(jEditorPane1, null); } // add nodes to tree // to make this like <cftree> // we would read in the directory structure // from the system public void makeNodes(DefaultMutableTreeNode top) { dir1 = new DefaultMutableTreeNode("Directory 1"); top.add(dir1); file1 = new DefaultMutableTreeNode("Dir 1, File 1"); dir1.add(file1); file1 = new DefaultMutableTreeNode("SubDirectory"); dir1.add(file1); file1_sub1 = new DefaultMutableTreeNode("SubDir 1, File 1"); file1.add(file1_sub1); dir2 = new DefaultMutableTreeNode("Directory 2"); top.add(dir2); file2 = new DefaultMutableTreeNode("Dir 1, File 1"); dir2.add(file2); file2 = new DefaultMutableTreeNode("Dir 2, File 2"); dir2.add(file2); file2 = new DefaultMutableTreeNode("Dir 2, File 3"); dir2.add(file2); } //FileExit event void menuFileExit_actionPerformed(ActionEvent e) { System.exit(0); } // make text appear when item is selected void jTree1_valueChanged(TreeSelectionEvent e) { String rootText = "The root Directory"; String nodeText = "This is a Directory"; String childText = "This is a File"; // find last selected. DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1. graphics/ccc.gif getLastSelectedPathComponent (); TreePath pathnode = (TreePath)jTree1.getLeadSelectionPath(); if (jTree1.isVisible(pathnode)) { // display the if (node.isRoot()) { jEditorPane1.setText(rootText + " level: " + node.getLevel() + " parent: " + node.getParent()); } // isLeaf is a method of // javax.swing.tree.DefaultMutableTreeNode else if (node.isLeaf()) { jEditorPane1.setText(childText + " level: " + node.getLevel() + " parent: " + node.getParent()); } else if (node.isNodeAncestor(top)) { jEditorPane1.setText(nodeText + " level: " + node.getLevel() + " parent: " + node.getParent()); } } } // allows us to shut down program // overide this method of JFrame // constant integers represent different states protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { // shuts down program System.exit(0); } } } // eof

Running the MakeTree class calls the controls that make the frame and the Swing classes that make the tree. The files are commented inline to help clarify how the tree gets constructed (see Figure 10.8). As you may have inferred, perhaps the best thing you can do at this point to excel at Java programming is to become familiar with the API. Knowing your way around the API will help you determine quickly what kinds of structures are already available to you and what kinds of things you have to build yourself.

Figure 10.8. Running the proto- <cftree> application.

graphics/10fig08.gif


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net