Archive for July, 2007

Web and email hosting - Java Swing O Reilly Of course, you should

Tuesday, July 31st, 2007

Java Swing O Reilly Of course, you should be sure to import javax.swing.event.* to get access to the TreeSelectionListener and TreeSelectionEvent classes. 17.1.1 Tree Terminology Let’s look at a simple tree made up of the letters A-Z, shown in Figure 17.3. Figure 17.3. A simple tree Here are a few definitions for terms used to work with trees. We’ll be using them throughout this chapter. Node Any entry in the tree. A, J, and T are all nodes. Root The top-level entry of the tree. A root cannot have a parent, and a tree can have only one root. The root in this example is A. Child Any of the nodes attached below a given node. M is a child of G. Parent The node attached above a given node. Any typical node has only one parent, but the root of the tree is the only node with no parent. G is the parent of M and C is the parent of G. Sibling Any child of a node’s parent. A node is also its own sibling. B’s siblings are B, C, and D. Descendant Any child, or child of a child, or child of a child of a child, etc. A node is also its own descendant. L, S, W, and X are the descendants of L. - 469 -
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Web server - Java Swing O Reilly treeModel.insertNodeInto(subroot, root, 0); treeModel.insertNodeInto(leaf1,

Tuesday, July 31st, 2007

Java Swing O Reilly treeModel.insertNodeInto(subroot, root, 0); treeModel.insertNodeInto(leaf1, subroot, 0); treeModel.insertNodeInto(leaf2, root, 1); // And display it getContentPane().add(tree, BorderLayout.CENTER); } public static void main(String args[]) { TestTree tt = new TestTree(); tt.init(); tt.setVisible(true); } } As you can see here, all of the action happens in the init() method. We create several nodes using the DefaultMutableTreeNode class. The DefaultTreeModel class provides us with a basis for working with the tree, and we add our nodes into that model. All of the trees we will look at in this chapter contain the same basic steps gathering nodes, creating a tree, and populating the tree though again, not necessarily in that order. We will also look at the other types of things you can do with trees, including how to catch selection events and how to change the presentation of the nodes and leaves. And just to prove that it’s not hard to listen to selections from a tree, Figure 17.2 shows an expanded example that displays the most recently selected item in a JLabel at the bottom of the application. Figure 17.2. The TestTree program with a TreeSelectionListener label active To make this work, we add a listener directly to the JTree object. The listener looks and behaves much like a ListSelectionListener, but is slightly modified to handle the specifics of tree selections. (For example, selection intervals may have to cross over an expanded node, and all the nodes under the expanded entry must also be selected.) Even though we allow multiple entries to be selected, we only show the lead entry of the selection, to keep output simple. Here’s the chunk of code we need to add to the init() method in the TestTree class: // Create and add our message label for the selection outputfinal JLabel messageLabel = new JLabel(”Nothing selected.”); add(messageLabel, BorderLayout.SOUTH); // Add in our selection listener and have it report to // our messageLabel tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent tse) { TreePath tp = tse.getNewLeadSelectionPath(); messageLabel.setText(”Selected: ” + tp.getLastPathComponent()); } } ); - 468 -
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

Web proxy server - Java Swing O Reilly javax.swing.DefaultMutableTreeNode class serves as

Monday, July 30th, 2007

Java Swing O Reilly javax.swing.DefaultMutableTreeNode class serves as our node class. You don’t have to worry about specifically making a node a leaf. If the node has no references to other nodes by the time you display it, it’s a leaf. [1] The appearance of an internal frame in the Metal look-and-feel has changed slightly since these screen shots were taken. Figure 17.1. A simple JTree in the Metal, Motif, and Windows look-and-feels This example works by building up a series of unconnected nodes (using the DefaultMutableTreeNode class) and then connecting them. As long as we stick to the default classes provided with the tree package, we can build a regular model out of our nodes quite quickly. In this example, we build the model based on an empty root node, and then populate the tree by attaching the other nodes to the root or to each other. You can also build the tree first, and then create the model from the root node. Both methods have the same result. With a valid tree model in place, we can make a real JTree object and display it. // TestTree.java // A Simple test to see how we can build a tree and populate it. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; public class TestTree extends JFrame { JTree tree; DefaultTreeModel treeModel; public TestTree() { super(”Tree Test Example”); setSize(400, 300); addWindowListener(new BasicWindowMonitor()); } public void init() { // Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the// DefaultTreeModel can use that to build a complete tree. DefaultMutableTreeNode root = new DefaultMutableTreeNode(”Root”); DefaultMutableTreeNode subroot = new DefaultMutableTreeNode(”SubRoot”); DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode(”Leaf 1″); DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode(”Leaf 2″); // Build our tree model starting at the root node, and then make a JTree out // of that. treeModel = new DefaultTreeModel(root); tree = new JTree(treeModel); // Build the tree up from the nodes we created - 467 -
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Web hosting mysql - Java Swing O Reilly TableChartPopup.java // import java.awt.*;

Monday, July 30th, 2007

Java Swing O Reilly TableChartPopup.java // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class TableChartPopup extends JFrame { public TableChartPopup(TableModel tm) { super(”Table Chart”); setSize(300,200); TableChart tc = new TableChart(tm); getContentPane().add(tc, BorderLayout.CENTER); // Turn on the tooltips, we can use any string to get going. tc.setToolTipText(”Demo Chart”); } } As you can see, the TableChart component can be used on its own without a JTable. We just need a model to base it on. You could expand this example to chart only selected rows or columns, but we’ll leave that as an exercise for the reader. Chapter 17. Trees One crucial component that found its way into the Swing set is the tree. Tree components help you visualize hierarchical information and make traversal and manipulation of that information much more manageable. A tree consists of nodes, which can contain either a user-defined object along with references to other nodes, or a user-defined object only. (The nodes that have no references to other nodes are commonly called leaves.) In modern windowing environments, the directory list is an excellent example of a tree. The top of the component is the root directory or drive, and under that is a list of subdirectories. If the subdirectories contain further subdirectories, you can look at those as well. The actual files found in any directory in this component are the leaves of the tree. Any data that contains parent-child relationships between chunks of information can be displayed as a tree. Another common example is an organizational chart. In such a chart, every management position is a node, with child nodes representing the employees under the manager. The organizational chart’s leaves are the employees who are not in management positions, and its root is the president or CEO. Of course, real organization don’t always adhere to a strict tree structure. In a tree, each node has exactly one parent node, with the exception of the root node, which cannot have a parent (so trees are not cyclic). This means two managers cannot manage the same employee. In short, whenever you have a clearly defined hierarchy, you can express that hierarchy as a tree. Swing implements trees with the JTree class and its related models. With trees, as with tables, it’s particularly important to understand the models. The JTree itself merely coordinates the tree’s display. 17.1 A Simple Tree Before we look at the models supporting the JTree class, let’s look at a very simple example of a tree built with the default implementations in the Swing package (as shown in Figure 17.1).[1] The - 466 -
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Java Swing O Reilly (Web hosting) } return -1; }

Sunday, July 29th, 2007

Java Swing O Reilly } return -1; } public void paint(Graphics g, JComponent c) { Dimension size = c.getSize(); originX = size.width / 2; originY = size.height / 2; int diameter = (originX < originY ? size.width - 40 : size.height - 40); radius = (diameter / 2) + 1; int cornerX = (originX - (diameter / 2)); int cornerY = (originY - (diameter / 2)); int startAngle = 0; int arcAngle = 0; for (int i = 0; i < values.length; i++) { arcAngle = (int)(i < values.length - 1 ? Math.round(values[i] * 360) : 360 - startAngle); g.setColor(colors[i % colors.length]); g.fillArc(cornerX, cornerY, diameter, diameter, startAngle, arcAngle); drawLabel(g, labels[i], startAngle + (arcAngle / 2)); startAngle += arcAngle; } g.setColor(Color.black); g.drawOval(cornerX, cornerY, diameter, diameter); // cap the circle } public void drawLabel(Graphics g, String text, double angle) { g.setFont(textFont); g.setColor(textColor); double radians = angle * d2r; int x = (int) ((radius + 5) * Math.cos(radians)); int y = (int) ((radius + 5) * Math.sin(radians)); if (x < 0) { x -= SwingUtilities.computeStringWidth(g.getFontMetrics(), text); } if (y < 0) { y -= g.getFontMetrics().getHeight(); } g.drawString(text, x + originX, originY - y); } public static ComponentUI createUI(JComponent c) { return chartUI; } } There's nothing really complex here; it's just a lot of trigonometry and a little bit of simple AWT drawing. paint() is called with a graphics context and a JComponent as arguments; the JComponent allows you to figure out the size of the area we have to work with. And here's the code for the popup containing the chart: // - 465 -
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

Java Swing O Reilly There’s (Ecommerce web host) not much mystery

Sunday, July 29th, 2007

Java Swing O Reilly There’s not much mystery here. Except for the two abstract methods, these methods just maintain various simple properties of ChartPainter: the colors used for painting, the font, and the labels and values for the chart. The real work takes place in the PieChartPainter class, which provides the implementation of the indexOfEntryAt() and paint() methods. The indexOfEntryAt() method allows our TableChart class to figure out which tooltip to show. The paint() method allows us to draw a pie chart of our data. // PieChartPainter.java // A pie chart implementation of the ChartPainter class. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.plaf.*; public class PieChartPainter extends ChartPainter { protected static PieChartPainter chartUI = new PieChartPainter(); protected int originX, originY; protected int radius; private static double piby2 = Math.PI / 2.0; private static double twopi = Math.PI * 2.0; private static double d2r = Math.PI / 180.0; // degrees to radians. public int indexOfEntryAt(MouseEvent me) { int x = me.getX() - originX; int y = originY - me.getY(); // upside down coordinate system. // is (x,y) in the circle? if (Math.sqrt(x*x + y*y) > radius) { return -1; } double percent = Math.atan2(Math.abs(y), Math.abs(x)); if (x >= 0) { if (y <= 0) { // (IV) percent = (piby2 - percent) + 3 * piby2; // (IV) } } else { if (y >= 0) { // (II) percent = Math.PI - percent; } else { // (III) percent = Math.PI + percent; } } percent /= twopi; double t = 0.0; if (values != null) { for (int i = 0; i < values.length; i++) { if (t + values[i] > percent) { return i; } t += values[i]; } - 464 -
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

Java Swing O Reilly updateLocalValues(); calculatePercentages() and createLabelsAnd-Tips() (Most popular web site)

Saturday, July 28th, 2007

Java Swing O Reilly updateLocalValues(); calculatePercentages() and createLabelsAnd-Tips() are helper methods that keep the work modular. If up-dateLocalValues() is called with its argument set to true, it finds out the new number of rows for the table and creates new arrays to hold the component’s view of the data. It calculates percentages, retrieves labels, makes up tool tips, and calls the ChartPainter (the user interface object) to give it the new information. It ends by calling repaint() to redraw the screen with updated data. ChartPainter is the actual user interface class. It is abstract; we subclass it to implement specific kinds of charts. It extends the ComponentUI class, which makes it sound rather complex. But in fact, it isn’t. We’ve made one tremendously simplifying assumption: the chart will look the same for any look-and-feel. (The component in which the chart is embedded will change its appearance, but that’s another issue and one we don’t have to worry about.) All our ComponentUI has to do is implement paint(), which we leave abstract, forcing the subclass to implement it. Our other abstract method, indexOfEntryAt(), is required by TableChart. // ChartPainter.java // A simple chart-drawing UI base class. This class tracks the basic fonts // and colors for various types of charts including pie and bar. The paint() // method is abstract and must be implemented by subclasses for each type. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.plaf.*; public abstract class ChartPainter extends ComponentUI { protected Font textFont = new Font(”Serif”, Font.PLAIN, 12); protected Color textColor = Color.black; protected Color colors[] = new Color[] { Color.red, Color.blue, Color.yellow, Color.black, Color.green, Color.white, Color.gray, Color.cyan, Color.magenta, Color.darkGray }; protected double values[] = new double[0]; protected String labels[] = new String[0]; public void setTextFont(Font f) { textFont = f; } public Font getTextFont() { return textFont; } public void setColor(Color[] clist) { colors = clist; } public Color[] getColor() { return colors; } public void setColor(int index, Color c) { colors[index] = c; } public Color getColor(int index) { return colors[index]; } public void setTextColor(Color c) { textColor = c; } public Color getTextColor() { return textColor; } public void setLabels(String[] l) { labels = l; } public void setValues(double[] v) { values = v; } public abstract int indexOfEntryAt(MouseEvent me); public abstract void paint(Graphics g, JComponent c); } - 463 -
You want to have a cheap webhost for your apache application, then check apache web hosting services.

Java Swing O Reilly } runningTotal += percentages[i]; (Web hosting india)

Saturday, July 28th, 2007

Java Swing O Reilly } runningTotal += percentages[i]; } // make each entry a percentage of the total // make each entry a percentage of the total for (int i = model.getRowCount() - 1; i >= 0; i–) { percentages[i] /= runningTotal; } } // This method just takes the percentages and formats them for use as // tooltips protected void createLabelsAndTips() { for (int i = model.getRowCount() - 1; i >= 0; i–) { labels[i] = (String)model.getValueAt(i, 0); tips[i] = formatter.format(percentages[i]); } } // Call this method to update the chart. We try to be a bit efficient here// in that we only allocate new storage arrays if the new table has a// different number of rowsprotected void updateLocalValues(boolean freshStart) { if (freshStart) { int count = model.getRowCount(); if ((tips == null) || (count != tips.length)) { percentages = new double[count]; labels = new String[count]; tips = new String[count]; } } calculatePercentages(); createLabelsAndTips(); // Now that everything’s up-to-date, reset the chart painter with the new // values cp.setValues(percentages); cp.setLabels(labels); // and finally, repaint the chart. repaint(); } } The constructor for TableChart sets the user interface for this class to be the PieChartPainter that we’ll discuss later in this chapter. It also saves the TableModel for the component by calling our setModel() method; providing a separate setModel() (rather than saving the model in the constructor) lets us change the model at a later time a nice feature for a real component, though we don’t take advantage of it. We also override getToolTipText() that is called with a MouseEvent as an argument. This method calls the ChartPainter’s indexOfEntryAt() method to figure out which of the model’s entries corresponds to the current mouse position, looks up the appropriate tooltip, and returns it. tableChanged() is the method we implement to listen for TableModelEvents. It just delegates the call to another method, updateLocalValues(), with an argument of true if the table’s structure has changed (e.g., rows added or deleted), and false if only the values have changed. The rest of TableChart takes care of updating the data when the change occurs. The focal point of this work is - 462 -
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Professional web hosting - Java Swing O Reilly } public void setTextFont(Font

Friday, July 27th, 2007

Java Swing O Reilly } public void setTextFont(Font f) { cp.setTextFont(f); } public Font getTextFont() { return cp.getTextFont(); } public void setTextColor(Color c) { cp.setTextColor(c); } public Color getTextColor() { return cp.getTextColor(); } public void setColor(Color[] clist) { cp.setColor(clist); } public Color[] getColor() { return cp.getColor(); } public void setColor(int index, Color c) { cp.setColor(index, c); } public Color getColor(int index) { return cp.getColor(index); } public String getToolTipText(MouseEvent me) { if (tips != null) { int whichTip = cp.indexOfEntryAt(me); if (whichTip != -1) { return tips[whichTip]; } } return null; } public void tableChanged(TableModelEvent tme) { // only rebuild the arrays if the structure changed. updateLocalValues(tme.getType() != TableModelEvent.UPDATE); } public void setModel(TableModel tm) { // get listener code correct. if (tm != model) { if (model != null) { model.removeTableModelListener(this); } model = tm; model.addTableModelListener(this); updateLocalValues(true); } } public TableModel getModel() { return model; } // Run through the model and count every cell (except the very first column// which we assume is the slice label columnprotected void calculatePercentages() { double runningTotal = 0.0; for (int i = model.getRowCount() - 1; i >= 0; i–) { percentages[i] = 0.0; for (int j = model.getColumnCount() - 1; j >=0; j–) { // First try the cell as a Number object try { percentages[i] += ((Number)model.getValueAt(i, j)).doubleValue(); } catch(ClassCastException cce) { // oops, it wasn’t numeric… // Ok, so try it as a stringtry { percentages[i]+=Double.valueOf(model.getValueAt(i,j).toString()) .doubleValue(); } catch (Exception e) { // give up. } } - 461 -
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Java Swing O Reilly (Ipower web hosting) public int getRowCount() {

Friday, July 27th, 2007

Java Swing O Reilly public int getRowCount() { return data.length; } public String getColumnName(int col) { return headers[col]; } public Class getColumnClass(int col) { return (col == 0) ? String.class : Number.class; } public boolean isCellEditable(int row, int col) { return true; } public Object getValueAt(int row, int col) { return data[row][col]; } public void setValueAt(Object value, int row, int col) { data[row][col] = (String)value; fireTableRowsUpdated(row,row); } }; JTable jt = new JTable(tm); JScrollPane jsp = new JScrollPane(jt); getContentPane().add(jsp, BorderLayout.CENTER); final TableChartPopup tcp = new TableChartPopup(tm); JButton button = new JButton(”Show me a chart of this table”); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { tcp.setVisible(true); } } ); getContentPane().add(button, BorderLayout.SOUTH); } public static void main(String args[]) { ChartTester ct = new ChartTester(); ct.setVisible(true); } } The TableChart object is actually made of three pieces. The TableChart class extends JComponent, which provides all the machinery for getting a new component on the screen. It implements TableModelListener because it has to register and respond to TableModelEvents. // TableChart.java // A chart-generating class that uses the TableModel interface to get // its data. // import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class TableChart extends JComponent implements TableModelListener { protected TableModel model; protected ChartPainter cp; protected double[] percentages; // pie slices protected String[] labels; // labels for slices protected String[] tips; // tooltips for slices protected java.text.NumberFormat formatter = java.text.NumberFormat.getPercentInstance(); public TableChart(TableModel tm) { setUI(cp = new PieChartPainter()); setModel(tm); - 460 -
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.