KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > TableDemo


1 /*
2  * @(#)TableDemo.java 1.23 05/11/30
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)TableDemo.java 1.23 05/11/30
39  */

40
41
42 import javax.swing.*;
43 import javax.swing.event.*;
44 import javax.swing.text.*;
45 import javax.swing.table.*;
46 import javax.swing.border.*;
47 import javax.swing.colorchooser.*;
48 import javax.swing.filechooser.*;
49 import javax.accessibility.*;
50
51 import java.awt.*;
52 import java.awt.event.*;
53 import java.awt.print.PrinterException JavaDoc;
54 import java.beans.*;
55 import java.util.*;
56 import java.io.*;
57 import java.applet.*;
58 import java.net.*;
59
60 import java.text.MessageFormat JavaDoc;
61
62 /**
63  * Table demo
64  *
65  * @version 1.23 11/30/05
66  * @author Philip Milne
67  * @author Steve Wilson
68  */

69 public class TableDemo extends DemoModule {
70     JTable tableView;
71     JScrollPane scrollpane;
72     Dimension origin = new Dimension(0, 0);
73     
74     JCheckBox isColumnReorderingAllowedCheckBox;
75     JCheckBox showHorizontalLinesCheckBox;
76     JCheckBox showVerticalLinesCheckBox;
77
78     JCheckBox isColumnSelectionAllowedCheckBox;
79     JCheckBox isRowSelectionAllowedCheckBox;
80
81     JLabel interCellSpacingLabel;
82     JLabel rowHeightLabel;
83
84     JSlider interCellSpacingSlider;
85     JSlider rowHeightSlider;
86
87     JComboBox selectionModeComboBox = null;
88     JComboBox resizeModeComboBox = null;
89
90     JLabel headerLabel;
91     JLabel footerLabel;
92
93     JTextField headerTextField;
94     JTextField footerTextField;
95
96     JCheckBox fitWidth;
97     JButton printButton;
98
99     JPanel controlPanel;
100     JScrollPane tableAggregate;
101
102     String JavaDoc path = "ImageClub/food/";
103
104     final int INITIAL_ROWHEIGHT = 33;
105
106     /**
107      * main method allows us to run as a standalone demo.
108      */

109     public static void main(String JavaDoc[] args) {
110     TableDemo demo = new TableDemo(null);
111     demo.mainImpl();
112     }
113
114     /**
115      * TableDemo Constructor
116      */

117     public TableDemo(SwingSet2 swingset) {
118     super(swingset, "TableDemo", "toolbar/JTable.gif");
119     
120     getDemoPanel().setLayout(new BorderLayout());
121     controlPanel = new JPanel();
122         controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS));
123     JPanel cbPanel = new JPanel(new GridLayout(3, 2));
124         JPanel labelPanel = new JPanel(new GridLayout(2, 1)) {
125             public Dimension getMaximumSize() {
126                 return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
127             }
128         };
129         JPanel sliderPanel = new JPanel(new GridLayout(2, 1)) {
130             public Dimension getMaximumSize() {
131                 return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
132             }
133         };
134     JPanel comboPanel = new JPanel(new GridLayout(2, 1));
135         JPanel printPanel = new JPanel(new ColumnLayout());
136
137     getDemoPanel().add(controlPanel, BorderLayout.NORTH);
138     Vector relatedComponents = new Vector();
139
140
141         // check box panel
142
isColumnReorderingAllowedCheckBox = new JCheckBox(getString("TableDemo.reordering_allowed"), true);
143         isColumnReorderingAllowedCheckBox.addActionListener(new ActionListener() {
144         public void actionPerformed(ActionEvent e) {
145             boolean flag = ((JCheckBox)e.getSource()).isSelected();
146                 tableView.getTableHeader().setReorderingAllowed(flag);
147                 tableView.repaint();
148         }
149         });
150
151         showHorizontalLinesCheckBox = new JCheckBox(getString("TableDemo.horz_lines"), true);
152         showHorizontalLinesCheckBox.addActionListener(new ActionListener() {
153         public void actionPerformed(ActionEvent e) {
154             boolean flag = ((JCheckBox)e.getSource()).isSelected();
155                 tableView.setShowHorizontalLines(flag); ;
156                 tableView.repaint();
157         }
158         });
159
160         showVerticalLinesCheckBox = new JCheckBox(getString("TableDemo.vert_lines"), true);
161         showVerticalLinesCheckBox.addActionListener(new ActionListener() {
162         public void actionPerformed(ActionEvent e) {
163             boolean flag = ((JCheckBox)e.getSource()).isSelected();
164                 tableView.setShowVerticalLines(flag); ;
165                 tableView.repaint();
166         }
167         });
168
169     // Show that showHorizontal/Vertical controls are related
170
relatedComponents.removeAllElements();
171     relatedComponents.add(showHorizontalLinesCheckBox);
172     relatedComponents.add(showVerticalLinesCheckBox);
173     buildAccessibleGroup(relatedComponents);
174
175         isRowSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.row_selection"), true);
176         isRowSelectionAllowedCheckBox.addActionListener(new ActionListener() {
177             public void actionPerformed(ActionEvent e) {
178                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
179                 tableView.setRowSelectionAllowed(flag); ;
180                 tableView.repaint();
181             }
182         });
183
184         isColumnSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.column_selection"), false);
185         isColumnSelectionAllowedCheckBox.addActionListener(new ActionListener() {
186             public void actionPerformed(ActionEvent e) {
187                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
188                 tableView.setColumnSelectionAllowed(flag); ;
189                 tableView.repaint();
190             }
191         });
192
193         // Show that row/column selections are related
194
relatedComponents.removeAllElements();
195         relatedComponents.add(isColumnSelectionAllowedCheckBox);
196         relatedComponents.add(isRowSelectionAllowedCheckBox);
197         buildAccessibleGroup(relatedComponents);
198
199         cbPanel.add(isColumnReorderingAllowedCheckBox);
200         cbPanel.add(isRowSelectionAllowedCheckBox);
201         cbPanel.add(showHorizontalLinesCheckBox);
202         cbPanel.add(isColumnSelectionAllowedCheckBox);
203         cbPanel.add(showVerticalLinesCheckBox);
204
205
206         // label panel
207
interCellSpacingLabel = new JLabel(getString("TableDemo.intercell_spacing_colon"));
208     labelPanel.add(interCellSpacingLabel);
209
210         rowHeightLabel = new JLabel(getString("TableDemo.row_height_colon"));
211         labelPanel.add(rowHeightLabel);
212
213
214         // slider panel
215
interCellSpacingSlider = new JSlider(JSlider.HORIZONTAL, 0, 10, 1);
216     interCellSpacingSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.intercell_spacing"));
217     interCellSpacingLabel.setLabelFor(interCellSpacingSlider);
218         sliderPanel.add(interCellSpacingSlider);
219         interCellSpacingSlider.addChangeListener(new ChangeListener() {
220         public void stateChanged(ChangeEvent e) {
221             int spacing = ((JSlider)e.getSource()).getValue();
222                 tableView.setIntercellSpacing(new Dimension(spacing, spacing));
223                 tableView.repaint();
224         }
225         });
226     
227         rowHeightSlider = new JSlider(JSlider.HORIZONTAL, 5, 100, INITIAL_ROWHEIGHT);
228     rowHeightSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.row_height"));
229     rowHeightLabel.setLabelFor(rowHeightSlider);
230         sliderPanel.add(rowHeightSlider);
231         rowHeightSlider.addChangeListener(new ChangeListener() {
232         public void stateChanged(ChangeEvent e) {
233             int height = ((JSlider)e.getSource()).getValue();
234                 tableView.setRowHeight(height);
235                 tableView.repaint();
236         }
237         });
238
239     // Show that spacing controls are related
240
relatedComponents.removeAllElements();
241     relatedComponents.add(interCellSpacingSlider);
242     relatedComponents.add(rowHeightSlider);
243     buildAccessibleGroup(relatedComponents);
244
245
246         // Create the table.
247
tableAggregate = createTable();
248         getDemoPanel().add(tableAggregate, BorderLayout.CENTER);
249
250
251         // ComboBox for selection modes.
252
JPanel selectMode = new JPanel();
253         selectMode.setLayout(new BoxLayout(selectMode, BoxLayout.X_AXIS));
254         selectMode.setBorder(new TitledBorder(getString("TableDemo.selection_mode")));
255
256
257         selectionModeComboBox = new JComboBox() {
258             public Dimension getMaximumSize() {
259                 return getPreferredSize();
260             }
261         };
262         selectionModeComboBox.addItem(getString("TableDemo.single"));
263         selectionModeComboBox.addItem(getString("TableDemo.one_range"));
264         selectionModeComboBox.addItem(getString("TableDemo.multiple_ranges"));
265         selectionModeComboBox.setSelectedIndex(tableView.getSelectionModel().getSelectionMode());
266         selectionModeComboBox.addItemListener(new ItemListener() {
267         public void itemStateChanged(ItemEvent e) {
268             JComboBox source = (JComboBox)e.getSource();
269                 tableView.setSelectionMode(source.getSelectedIndex());
270         }
271         });
272
273         selectMode.add(Box.createHorizontalStrut(2));
274     selectMode.add(selectionModeComboBox);
275         selectMode.add(Box.createHorizontalGlue());
276         comboPanel.add(selectMode);
277
278         // Combo box for table resize mode.
279
JPanel resizeMode = new JPanel();
280         resizeMode.setLayout(new BoxLayout(resizeMode, BoxLayout.X_AXIS));
281     resizeMode.setBorder(new TitledBorder(getString("TableDemo.autoresize_mode")));
282
283
284         resizeModeComboBox = new JComboBox() {
285             public Dimension getMaximumSize() {
286                 return getPreferredSize();
287             }
288         };
289         resizeModeComboBox.addItem(getString("TableDemo.off"));
290         resizeModeComboBox.addItem(getString("TableDemo.column_boundaries"));
291         resizeModeComboBox.addItem(getString("TableDemo.subsequent_columns"));
292         resizeModeComboBox.addItem(getString("TableDemo.last_column"));
293         resizeModeComboBox.addItem(getString("TableDemo.all_columns"));
294         resizeModeComboBox.setSelectedIndex(tableView.getAutoResizeMode());
295         resizeModeComboBox.addItemListener(new ItemListener() {
296         public void itemStateChanged(ItemEvent e) {
297             JComboBox source = (JComboBox)e.getSource();
298                 tableView.setAutoResizeMode(source.getSelectedIndex());
299         }
300         });
301
302         resizeMode.add(Box.createHorizontalStrut(2));
303     resizeMode.add(resizeModeComboBox);
304         resizeMode.add(Box.createHorizontalGlue());
305         comboPanel.add(resizeMode);
306
307         // print panel
308
printPanel.setBorder(new TitledBorder(getString("TableDemo.printing")));
309         headerLabel = new JLabel(getString("TableDemo.header"));
310         footerLabel = new JLabel(getString("TableDemo.footer"));
311         headerTextField = new JTextField(getString("TableDemo.headerText"), 15);
312         footerTextField = new JTextField(getString("TableDemo.footerText"), 15);
313         fitWidth = new JCheckBox(getString("TableDemo.fitWidth"), true);
314         printButton = new JButton(getString("TableDemo.print"));
315         printButton.addActionListener(new ActionListener() {
316             public void actionPerformed(ActionEvent ae) {
317                 printTable();
318             }
319         });
320
321         printPanel.add(headerLabel);
322         printPanel.add(headerTextField);
323         printPanel.add(footerLabel);
324         printPanel.add(footerTextField);
325         
326         JPanel buttons = new JPanel();
327         buttons.add(fitWidth);
328         buttons.add(printButton);
329
330         printPanel.add(buttons);
331
332         // Show that printing controls are related
333
relatedComponents.removeAllElements();
334         relatedComponents.add(headerTextField);
335         relatedComponents.add(footerTextField);
336         relatedComponents.add(printButton);
337         buildAccessibleGroup(relatedComponents);
338
339         // wrap up the panels and add them
340
JPanel sliderWrapper = new JPanel();
341         sliderWrapper.setLayout(new BoxLayout(sliderWrapper, BoxLayout.X_AXIS));
342         sliderWrapper.add(labelPanel);
343         sliderWrapper.add(sliderPanel);
344         sliderWrapper.add(Box.createHorizontalGlue());
345         sliderWrapper.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
346         
347         JPanel leftWrapper = new JPanel();
348         leftWrapper.setLayout(new BoxLayout(leftWrapper, BoxLayout.Y_AXIS));
349         leftWrapper.add(cbPanel);
350         leftWrapper.add(sliderWrapper);
351
352         // add everything
353
controlPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0));
354         controlPanel.add(leftWrapper);
355         controlPanel.add(comboPanel);
356         controlPanel.add(printPanel);
357
358     setTableControllers(); // Set accessibility information
359

360         getDemoPanel().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
361             .put(KeyStroke.getKeyStroke("ctrl P"), "print");
362
363         getDemoPanel().getActionMap().put("print", new AbstractAction() {
364             public void actionPerformed(ActionEvent ae) {
365                 printTable();
366             }
367         });
368                 
369     } // TableDemo()
370

371     /**
372      * Sets the Accessibility MEMBER_OF property to denote that
373      * these components work together as a group. Each object
374      * is set to be a MEMBER_OF an array that contains all of
375      * the objects in the group, including itself.
376      *
377      * @param components The list of objects that are related
378      */

379     void buildAccessibleGroup(Vector components) {
380
381     AccessibleContext context = null;
382     int numComponents = components.size();
383     Object JavaDoc[] group = components.toArray();
384     Object JavaDoc object = null;
385     for (int i = 0; i < numComponents; ++i) {
386         object = components.elementAt(i);
387         if (object instanceof Accessible) {
388             context = ((Accessible)components.elementAt(i)).
389                          getAccessibleContext();
390         context.getAccessibleRelationSet().add(
391             new AccessibleRelation(
392             AccessibleRelation.MEMBER_OF, group));
393         }
394     }
395     } // buildAccessibleGroup()
396

397     /**
398      * This sets CONTROLLER_FOR on the controls that manipulate the
399      * table and CONTROLLED_BY relationships on the table to point
400      * back to the controllers.
401      */

402     private void setTableControllers() {
403
404     // Set up the relationships to show what controls the table
405
setAccessibleController(isColumnReorderingAllowedCheckBox,
406                 tableAggregate);
407     setAccessibleController(showHorizontalLinesCheckBox,
408                 tableAggregate);
409     setAccessibleController(showVerticalLinesCheckBox,
410                 tableAggregate);
411     setAccessibleController(isColumnSelectionAllowedCheckBox,
412                 tableAggregate);
413     setAccessibleController(isRowSelectionAllowedCheckBox,
414                 tableAggregate);
415     setAccessibleController(interCellSpacingSlider,
416                 tableAggregate);
417     setAccessibleController(rowHeightSlider,
418                 tableAggregate);
419     setAccessibleController(selectionModeComboBox,
420                 tableAggregate);
421     setAccessibleController(resizeModeComboBox,
422                 tableAggregate);
423     } // setTableControllers()
424

425     /**
426      * Sets up accessibility relationships to denote that one
427      * object controls another. The CONTROLLER_FOR property is
428      * set on the controller object, and the CONTROLLED_BY
429      * property is set on the target object.
430      */

431     private void setAccessibleController(JComponent controller,
432                     JComponent target) {
433     AccessibleRelationSet controllerRelations =
434         controller.getAccessibleContext().getAccessibleRelationSet();
435     AccessibleRelationSet targetRelations =
436         target.getAccessibleContext().getAccessibleRelationSet();
437
438     controllerRelations.add(
439         new AccessibleRelation(
440         AccessibleRelation.CONTROLLER_FOR, target));
441     targetRelations.add(
442         new AccessibleRelation(
443         AccessibleRelation.CONTROLLED_BY, controller));
444     } // setAccessibleController()
445

446     public JScrollPane createTable() {
447
448         // final
449
final String JavaDoc[] names = {
450       getString("TableDemo.first_name"),
451       getString("TableDemo.last_name"),
452       getString("TableDemo.favorite_color"),
453       getString("TableDemo.favorite_movie"),
454       getString("TableDemo.favorite_number"),
455       getString("TableDemo.favorite_food")
456     };
457
458     ImageIcon apple = createImageIcon("ImageClub/food/apple.jpg", getString("TableDemo.apple"));
459     ImageIcon asparagus = createImageIcon("ImageClub/food/asparagus.jpg", getString("TableDemo.asparagus"));
460     ImageIcon banana = createImageIcon("ImageClub/food/banana.jpg", getString("TableDemo.banana"));
461     ImageIcon broccoli = createImageIcon("ImageClub/food/broccoli.jpg", getString("TableDemo.broccoli"));
462     ImageIcon cantaloupe = createImageIcon("ImageClub/food/cantaloupe.jpg", getString("TableDemo.cantaloupe"));
463     ImageIcon carrot = createImageIcon("ImageClub/food/carrot.jpg", getString("TableDemo.carrot"));
464     ImageIcon corn = createImageIcon("ImageClub/food/corn.jpg", getString("TableDemo.corn"));
465     ImageIcon grapes = createImageIcon("ImageClub/food/grapes.jpg", getString("TableDemo.grapes"));
466     ImageIcon grapefruit = createImageIcon("ImageClub/food/grapefruit.jpg", getString("TableDemo.grapefruit"));
467     ImageIcon kiwi = createImageIcon("ImageClub/food/kiwi.jpg", getString("TableDemo.kiwi"));
468     ImageIcon onion = createImageIcon("ImageClub/food/onion.jpg", getString("TableDemo.onion"));
469     ImageIcon pear = createImageIcon("ImageClub/food/pear.jpg", getString("TableDemo.pear"));
470     ImageIcon peach = createImageIcon("ImageClub/food/peach.jpg", getString("TableDemo.peach"));
471     ImageIcon pepper = createImageIcon("ImageClub/food/pepper.jpg", getString("TableDemo.pepper"));
472     ImageIcon pickle = createImageIcon("ImageClub/food/pickle.jpg", getString("TableDemo.pickle"));
473     ImageIcon pineapple = createImageIcon("ImageClub/food/pineapple.jpg", getString("TableDemo.pineapple"));
474     ImageIcon raspberry = createImageIcon("ImageClub/food/raspberry.jpg", getString("TableDemo.raspberry"));
475     ImageIcon sparegrass = createImageIcon("ImageClub/food/asparagus.jpg", getString("TableDemo.sparegrass"));
476     ImageIcon strawberry = createImageIcon("ImageClub/food/strawberry.jpg", getString("TableDemo.strawberry"));
477     ImageIcon tomato = createImageIcon("ImageClub/food/tomato.jpg", getString("TableDemo.tomato"));
478     ImageIcon watermelon = createImageIcon("ImageClub/food/watermelon.jpg", getString("TableDemo.watermelon"));
479
480     NamedColor aqua = new NamedColor(new Color(127, 255, 212), getString("TableDemo.aqua"));
481     NamedColor beige = new NamedColor(new Color(245, 245, 220), getString("TableDemo.beige"));
482     NamedColor black = new NamedColor(Color.black, getString("TableDemo.black"));
483     NamedColor blue = new NamedColor(new Color(0, 0, 222), getString("TableDemo.blue"));
484     NamedColor eblue = new NamedColor(Color.blue, getString("TableDemo.eblue"));
485     NamedColor jfcblue = new NamedColor(new Color(204, 204, 255), getString("TableDemo.jfcblue"));
486     NamedColor jfcblue2 = new NamedColor(new Color(153, 153, 204), getString("TableDemo.jfcblue2"));
487     NamedColor cybergreen = new NamedColor(Color.green.darker().brighter(), getString("TableDemo.cybergreen"));
488     NamedColor darkgreen = new NamedColor(new Color(0, 100, 75), getString("TableDemo.darkgreen"));
489     NamedColor forestgreen = new NamedColor(Color.green.darker(), getString("TableDemo.forestgreen"));
490     NamedColor gray = new NamedColor(Color.gray, getString("TableDemo.gray"));
491     NamedColor green = new NamedColor(Color.green, getString("TableDemo.green"));
492     NamedColor orange = new NamedColor(new Color(255, 165, 0), getString("TableDemo.orange"));
493     NamedColor purple = new NamedColor(new Color(160, 32, 240), getString("TableDemo.purple"));
494     NamedColor red = new NamedColor(Color.red, getString("TableDemo.red"));
495     NamedColor rustred = new NamedColor(Color.red.darker(), getString("TableDemo.rustred"));
496     NamedColor sunpurple = new NamedColor(new Color(100, 100, 255), getString("TableDemo.sunpurple"));
497     NamedColor suspectpink = new NamedColor(new Color(255, 105, 180), getString("TableDemo.suspectpink"));
498     NamedColor turquoise = new NamedColor(new Color(0, 255, 255), getString("TableDemo.turquoise"));
499     NamedColor violet = new NamedColor(new Color(238, 130, 238), getString("TableDemo.violet"));
500     NamedColor yellow = new NamedColor(Color.yellow, getString("TableDemo.yellow"));
501
502         // Create the dummy data (a few rows of names)
503
final Object JavaDoc[][] data = {
504       {"Mike", "Albers", green, getString("TableDemo.brazil"), new Double JavaDoc(44.0), strawberry},
505       {"Mark", "Andrews", blue, getString("TableDemo.curse"), new Double JavaDoc(3), grapes},
506       {"Brian", "Beck", black, getString("TableDemo.bluesbros"), new Double JavaDoc(2.7182818285), raspberry},
507       {"Lara", "Bunni", red, getString("TableDemo.airplane"), new Double JavaDoc(15), strawberry},
508       {"Roger", "Brinkley", blue, getString("TableDemo.man"), new Double JavaDoc(13), peach},
509       {"Brent", "Christian", black, getString("TableDemo.bladerunner"), new Double JavaDoc(23), broccoli},
510       {"Mark", "Davidson", darkgreen, getString("TableDemo.brazil"), new Double JavaDoc(27), asparagus},
511       {"Jeff", "Dinkins", blue, getString("TableDemo.ladyvanishes"), new Double JavaDoc(8), kiwi},
512       {"Ewan", "Dinkins", yellow, getString("TableDemo.bugs"), new Double JavaDoc(2), strawberry},
513       {"Amy", "Fowler", violet, getString("TableDemo.reservoir"), new Double JavaDoc(3), raspberry},
514       {"Hania", "Gajewska", purple, getString("TableDemo.jules"), new Double JavaDoc(5), raspberry},
515       {"David", "Geary", blue, getString("TableDemo.pulpfiction"), new Double JavaDoc(3), watermelon},
516 // {"James", "Gosling", pink, getString("TableDemo.tennis"), new Double(21), donut},
517
{"Eric", "Hawkes", blue, getString("TableDemo.bladerunner"), new Double JavaDoc(.693), pickle},
518           {"Shannon", "Hickey", green, getString("TableDemo.shawshank"), new Double JavaDoc(2), grapes},
519       {"Earl", "Johnson", green, getString("TableDemo.pulpfiction"), new Double JavaDoc(8), carrot},
520       {"Robi", "Khan", green, getString("TableDemo.goodfellas"), new Double JavaDoc(89), apple},
521       {"Robert", "Kim", blue, getString("TableDemo.mohicans"), new Double JavaDoc(655321), strawberry},
522       {"Janet", "Koenig", turquoise, getString("TableDemo.lonestar"), new Double JavaDoc(7), peach},
523       {"Jeff", "Kesselman", blue, getString("TableDemo.stuntman"), new Double JavaDoc(17), pineapple},
524       {"Onno", "Kluyt", orange, getString("TableDemo.oncewest"), new Double JavaDoc(8), broccoli},
525       {"Peter", "Korn", sunpurple, getString("TableDemo.musicman"), new Double JavaDoc(12), sparegrass},
526
527       {"Rick", "Levenson", black, getString("TableDemo.harold"), new Double JavaDoc(1327), raspberry},
528       {"Brian", "Lichtenwalter", jfcblue, getString("TableDemo.fifthelement"), new Double JavaDoc(22), pear},
529       {"Malini", "Minasandram", beige, getString("TableDemo.joyluck"), new Double JavaDoc(9), corn},
530       {"Michael", "Martak", green, getString("TableDemo.city"), new Double JavaDoc(3), strawberry},
531       {"David", "Mendenhall", forestgreen, getString("TableDemo.schindlerslist"), new Double JavaDoc(7), peach},
532       {"Phil", "Milne", suspectpink, getString("TableDemo.withnail"), new Double JavaDoc(3), banana},
533       {"Lynn", "Monsanto", cybergreen, getString("TableDemo.dasboot"), new Double JavaDoc(52), peach},
534       {"Hans", "Muller", rustred, getString("TableDemo.eraserhead"), new Double JavaDoc(0), pineapple},
535           {"Joshua", "Outwater", blue, getString("TableDemo.labyrinth"), new Double JavaDoc(3), pineapple},
536       {"Tim", "Prinzing", blue, getString("TableDemo.firstsight"), new Double JavaDoc(69), pepper},
537       {"Raj", "Premkumar", jfcblue2, getString("TableDemo.none"), new Double JavaDoc(7), broccoli},
538       {"Howard", "Rosen", green, getString("TableDemo.defending"), new Double JavaDoc(7), strawberry},
539       {"Ray", "Ryan", black, getString("TableDemo.buckaroo"),
540        new Double JavaDoc(3.141592653589793238462643383279502884197169399375105820974944), banana},
541       {"Georges", "Saab", aqua, getString("TableDemo.bicycle"), new Double JavaDoc(290), cantaloupe},
542       {"Tom", "Santos", blue, getString("TableDemo.spinaltap"), new Double JavaDoc(241), pepper},
543       {"Rich", "Schiavi", blue, getString("TableDemo.repoman"), new Double JavaDoc(0xFF), pepper},
544       {"Nancy", "Schorr", green, getString("TableDemo.fifthelement"), new Double JavaDoc(47), watermelon},
545       {"Keith", "Sprochi", darkgreen, getString("TableDemo.2001"), new Double JavaDoc(13), watermelon},
546       {"Matt", "Tucker", eblue, getString("TableDemo.starwars"), new Double JavaDoc(2), broccoli},
547       {"Dmitri", "Trembovetski", red, getString("TableDemo.aliens"), new Double JavaDoc(222), tomato},
548       {"Scott", "Violet", violet, getString("TableDemo.raiders"), new Double JavaDoc(-97), banana},
549       {"Kathy", "Walrath", darkgreen, getString("TableDemo.thinman"), new Double JavaDoc(8), pear},
550       {"Nathan", "Walrath", black, getString("TableDemo.chusingura"), new Double JavaDoc(3), grapefruit},
551       {"Steve", "Wilson", green, getString("TableDemo.raiders"), new Double JavaDoc(7), onion},
552       {"Kathleen", "Zelony", gray, getString("TableDemo.dog"), new Double JavaDoc(13), grapes}
553         };
554
555         // Create a model of the data.
556
TableModel dataModel = new AbstractTableModel() {
557             public int getColumnCount() { return names.length; }
558             public int getRowCount() { return data.length;}
559             public Object JavaDoc getValueAt(int row, int col) {return data[row][col];}
560             public String JavaDoc getColumnName(int column) {return names[column];}
561             public Class JavaDoc getColumnClass(int c) {return getValueAt(0, c).getClass();}
562         public boolean isCellEditable(int row, int col) {return col != 5;}
563             public void setValueAt(Object JavaDoc aValue, int row, int column) { data[row][column] = aValue; }
564          };
565
566
567         // Create the table
568
tableView = new JTable(dataModel);
569         TableRowSorter sorter = new TableRowSorter(dataModel);
570         tableView.setRowSorter(sorter);
571
572         // Show colors by rendering them in their own color.
573
DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {
574         public void setValue(Object JavaDoc value) {
575             if (value instanceof NamedColor) {
576             NamedColor c = (NamedColor) value;
577                 setBackground(c);
578                 setForeground(c.getTextColor());
579                 setText(c.toString());
580         } else {
581             super.setValue(value);
582         }
583         }
584         };
585
586     // Create a combo box to show that you can use one in a table.
587
JComboBox comboBox = new JComboBox();
588     comboBox.addItem(aqua);
589     comboBox.addItem(beige);
590     comboBox.addItem(black);
591     comboBox.addItem(blue);
592     comboBox.addItem(eblue);
593     comboBox.addItem(jfcblue);
594     comboBox.addItem(jfcblue2);
595     comboBox.addItem(cybergreen);
596     comboBox.addItem(darkgreen);
597     comboBox.addItem(forestgreen);
598     comboBox.addItem(gray);
599     comboBox.addItem(green);
600     comboBox.addItem(orange);
601     comboBox.addItem(purple);
602     comboBox.addItem(red);
603     comboBox.addItem(rustred);
604     comboBox.addItem(sunpurple);
605     comboBox.addItem(suspectpink);
606     comboBox.addItem(turquoise);
607     comboBox.addItem(violet);
608     comboBox.addItem(yellow);
609
610         TableColumn colorColumn = tableView.getColumn(getString("TableDemo.favorite_color"));
611         // Use the combo box as the editor in the "Favorite Color" column.
612
colorColumn.setCellEditor(new DefaultCellEditor(comboBox));
613
614         colorRenderer.setHorizontalAlignment(JLabel.CENTER);
615         colorColumn.setCellRenderer(colorRenderer);
616
617         tableView.setRowHeight(INITIAL_ROWHEIGHT);
618
619         scrollpane = new JScrollPane(tableView);
620         return scrollpane;
621     }
622
623     private void printTable() {
624         MessageFormat JavaDoc headerFmt;
625         MessageFormat JavaDoc footerFmt;
626         JTable.PrintMode printMode = fitWidth.isSelected() ?
627                                      JTable.PrintMode.FIT_WIDTH :
628                                      JTable.PrintMode.NORMAL;
629
630         String JavaDoc text;
631         text = headerTextField.getText();
632         if (text != null && text.length() > 0) {
633             headerFmt = new MessageFormat JavaDoc(text);
634         } else {
635             headerFmt = null;
636         }
637
638         text = footerTextField.getText();
639         if (text != null && text.length() > 0) {
640             footerFmt = new MessageFormat JavaDoc(text);
641         } else {
642             footerFmt = null;
643         }
644
645         try {
646             boolean status = tableView.print(printMode, headerFmt, footerFmt);
647
648             if (status) {
649                 JOptionPane.showMessageDialog(tableView.getParent(),
650                                               getString("TableDemo.printingComplete"),
651                                               getString("TableDemo.printingResult"),
652                                               JOptionPane.INFORMATION_MESSAGE);
653             } else {
654                 JOptionPane.showMessageDialog(tableView.getParent(),
655                                               getString("TableDemo.printingCancelled"),
656                                               getString("TableDemo.printingResult"),
657                                               JOptionPane.INFORMATION_MESSAGE);
658             }
659         } catch (PrinterException JavaDoc pe) {
660             String JavaDoc errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"),
661                                                        new Object JavaDoc[] {pe.getMessage()});
662             JOptionPane.showMessageDialog(tableView.getParent(),
663                                           errorMessage,
664                                           getString("TableDemo.printingResult"),
665                                           JOptionPane.ERROR_MESSAGE);
666         } catch (SecurityException JavaDoc se) {
667             String JavaDoc errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"),
668                                                        new Object JavaDoc[] {se.getMessage()});
669             JOptionPane.showMessageDialog(tableView.getParent(),
670                                           errorMessage,
671                                           getString("TableDemo.printingResult"),
672                                           JOptionPane.ERROR_MESSAGE);
673         }
674     }
675
676     class NamedColor extends Color {
677     String JavaDoc name;
678     public NamedColor(Color color, String JavaDoc name) {
679         super(color.getRGB());
680         this.name = name;
681     }
682     
683     public Color getTextColor() {
684         int r = getRed();
685         int g = getGreen();
686         int b = getBlue();
687         if(r > 240 || g > 240) {
688         return Color.black;
689         } else {
690         return Color.white;
691         }
692     }
693     
694     public String JavaDoc toString() {
695         return name;
696     }
697     }
698         
699     class ColumnLayout implements LayoutManager {
700     int xInset = 5;
701     int yInset = 5;
702     int yGap = 2;
703     
704     public void addLayoutComponent(String JavaDoc s, Component c) {}
705     
706     public void layoutContainer(Container c) {
707         Insets insets = c.getInsets();
708         int height = yInset + insets.top;
709         
710         Component[] children = c.getComponents();
711         Dimension compSize = null;
712         for (int i = 0; i < children.length; i++) {
713         compSize = children[i].getPreferredSize();
714         children[i].setSize(compSize.width, compSize.height);
715         children[i].setLocation( xInset + insets.left, height);
716         height += compSize.height + yGap;
717         }
718         
719     }
720     
721     public Dimension minimumLayoutSize(Container c) {
722         Insets insets = c.getInsets();
723         int height = yInset + insets.top;
724         int width = 0 + insets.left + insets.right;
725         
726         Component[] children = c.getComponents();
727         Dimension compSize = null;
728         for (int i = 0; i < children.length; i++) {
729         compSize = children[i].getPreferredSize();
730         height += compSize.height + yGap;
731         width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2);
732         }
733         height += insets.bottom;
734         return new Dimension( width, height);
735     }
736     
737     public Dimension preferredLayoutSize(Container c) {
738         return minimumLayoutSize(c);
739     }
740     
741     public void removeLayoutComponent(Component c) {}
742     }
743     
744     void updateDragEnabled(boolean dragEnabled) {
745         tableView.setDragEnabled(dragEnabled);
746         headerTextField.setDragEnabled(dragEnabled);
747         footerTextField.setDragEnabled(dragEnabled);
748     }
749
750 }
751
Popular Tags