1 /*
2  *
3  * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  *   - Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  *
12  *   - Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  *
16  *   - Neither the name of Oracle nor the names of its
17  *     contributors may be used to endorse or promote products derived
18  *     from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
21  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 
34 import javax.swing.*;
35 import javax.swing.event.*;
36 import javax.swing.text.*;
37 import javax.swing.table.*;
38 import javax.swing.border.*;
39 import javax.swing.colorchooser.*;
40 import javax.swing.filechooser.*;
41 import javax.accessibility.*;
42 
43 import java.awt.*;
44 import java.awt.event.*;
45 import java.awt.print.PrinterException;
46 import java.beans.*;
47 import java.util.*;
48 import java.io.*;
49 import java.applet.*;
50 import java.net.*;
51 
52 import java.text.MessageFormat;
53 
54 /**
55  * Table demo
56  *
57  * @author Philip Milne
58  * @author Steve Wilson
59  */
60 public class TableDemo extends DemoModule {
61     JTable      tableView;
62     JScrollPane scrollpane;
63     Dimension   origin = new Dimension(0, 0);
64 
65     JCheckBox   isColumnReorderingAllowedCheckBox;
66     JCheckBox   showHorizontalLinesCheckBox;
67     JCheckBox   showVerticalLinesCheckBox;
68 
69     JCheckBox   isColumnSelectionAllowedCheckBox;
70     JCheckBox   isRowSelectionAllowedCheckBox;
71 
72     JLabel      interCellSpacingLabel;
73     JLabel      rowHeightLabel;
74 
75     JSlider     interCellSpacingSlider;
76     JSlider     rowHeightSlider;
77 
78     JComboBox   selectionModeComboBox = null;
79     JComboBox   resizeModeComboBox = null;
80 
81     JLabel      headerLabel;
82     JLabel      footerLabel;
83 
84     JTextField  headerTextField;
85     JTextField  footerTextField;
86 
87     JCheckBox   fitWidth;
88     JButton     printButton;
89 
90     JPanel      controlPanel;
91     JScrollPane tableAggregate;
92 
93     String path = "food/";
94 
95     final int INITIAL_ROWHEIGHT = 33;
96 
97     /**
98      * main method allows us to run as a standalone demo.
99      */
main(String[] args)100     public static void main(String[] args) {
101         TableDemo demo = new TableDemo(null);
102         demo.mainImpl();
103     }
104 
105     /**
106      * TableDemo Constructor
107      */
TableDemo(SwingSet2 swingset)108     public TableDemo(SwingSet2 swingset) {
109         super(swingset, "TableDemo", "toolbar/JTable.gif");
110 
111         getDemoPanel().setLayout(new BorderLayout());
112         controlPanel = new JPanel();
113         controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS));
114         JPanel cbPanel = new JPanel(new GridLayout(3, 2));
115         JPanel labelPanel = new JPanel(new GridLayout(2, 1)) {
116             public Dimension getMaximumSize() {
117                 return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
118             }
119         };
120         JPanel sliderPanel = new JPanel(new GridLayout(2, 1)) {
121             public Dimension getMaximumSize() {
122                 return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
123             }
124         };
125         JPanel comboPanel = new JPanel(new GridLayout(2, 1));
126         JPanel printPanel = new JPanel(new ColumnLayout());
127 
128         getDemoPanel().add(controlPanel, BorderLayout.NORTH);
129         Vector relatedComponents = new Vector();
130 
131 
132         // check box panel
133         isColumnReorderingAllowedCheckBox = new JCheckBox(getString("TableDemo.reordering_allowed"), true);
134         isColumnReorderingAllowedCheckBox.addActionListener(new ActionListener() {
135             public void actionPerformed(ActionEvent e) {
136                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
137                 tableView.getTableHeader().setReorderingAllowed(flag);
138                 tableView.repaint();
139             }
140         });
141 
142         showHorizontalLinesCheckBox = new JCheckBox(getString("TableDemo.horz_lines"), true);
143         showHorizontalLinesCheckBox.addActionListener(new ActionListener() {
144             public void actionPerformed(ActionEvent e) {
145                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
146                 tableView.setShowHorizontalLines(flag); ;
147                 tableView.repaint();
148             }
149         });
150 
151         showVerticalLinesCheckBox = new JCheckBox(getString("TableDemo.vert_lines"), true);
152         showVerticalLinesCheckBox.addActionListener(new ActionListener() {
153             public void actionPerformed(ActionEvent e) {
154                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
155                 tableView.setShowVerticalLines(flag); ;
156                 tableView.repaint();
157             }
158         });
159 
160         // Show that showHorizontal/Vertical controls are related
161         relatedComponents.removeAllElements();
162         relatedComponents.add(showHorizontalLinesCheckBox);
163         relatedComponents.add(showVerticalLinesCheckBox);
164         buildAccessibleGroup(relatedComponents);
165 
166         isRowSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.row_selection"), true);
167         isRowSelectionAllowedCheckBox.addActionListener(new ActionListener() {
168             public void actionPerformed(ActionEvent e) {
169                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
170                 tableView.setRowSelectionAllowed(flag); ;
171                 tableView.repaint();
172             }
173         });
174 
175         isColumnSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.column_selection"), false);
176         isColumnSelectionAllowedCheckBox.addActionListener(new ActionListener() {
177             public void actionPerformed(ActionEvent e) {
178                 boolean flag = ((JCheckBox)e.getSource()).isSelected();
179                 tableView.setColumnSelectionAllowed(flag); ;
180                 tableView.repaint();
181             }
182         });
183 
184         // Show that row/column selections are related
185         relatedComponents.removeAllElements();
186         relatedComponents.add(isColumnSelectionAllowedCheckBox);
187         relatedComponents.add(isRowSelectionAllowedCheckBox);
188         buildAccessibleGroup(relatedComponents);
189 
190         cbPanel.add(isColumnReorderingAllowedCheckBox);
191         cbPanel.add(isRowSelectionAllowedCheckBox);
192         cbPanel.add(showHorizontalLinesCheckBox);
193         cbPanel.add(isColumnSelectionAllowedCheckBox);
194         cbPanel.add(showVerticalLinesCheckBox);
195 
196 
197         // label panel
198         interCellSpacingLabel = new JLabel(getString("TableDemo.intercell_spacing_colon"));
199         labelPanel.add(interCellSpacingLabel);
200 
201         rowHeightLabel = new JLabel(getString("TableDemo.row_height_colon"));
202         labelPanel.add(rowHeightLabel);
203 
204 
205         // slider panel
206         interCellSpacingSlider = new JSlider(JSlider.HORIZONTAL, 0, 10, 1);
207         interCellSpacingSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.intercell_spacing"));
208         interCellSpacingLabel.setLabelFor(interCellSpacingSlider);
209         sliderPanel.add(interCellSpacingSlider);
210         interCellSpacingSlider.addChangeListener(new ChangeListener() {
211             public void stateChanged(ChangeEvent e) {
212                 int spacing = ((JSlider)e.getSource()).getValue();
213                 tableView.setIntercellSpacing(new Dimension(spacing, spacing));
214                 tableView.repaint();
215             }
216         });
217 
218         rowHeightSlider = new JSlider(JSlider.HORIZONTAL, 5, 100, INITIAL_ROWHEIGHT);
219         rowHeightSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.row_height"));
220         rowHeightLabel.setLabelFor(rowHeightSlider);
221         sliderPanel.add(rowHeightSlider);
222         rowHeightSlider.addChangeListener(new ChangeListener() {
223             public void stateChanged(ChangeEvent e) {
224                 int height = ((JSlider)e.getSource()).getValue();
225                 tableView.setRowHeight(height);
226                 tableView.repaint();
227             }
228         });
229 
230         // Show that spacing controls are related
231         relatedComponents.removeAllElements();
232         relatedComponents.add(interCellSpacingSlider);
233         relatedComponents.add(rowHeightSlider);
234         buildAccessibleGroup(relatedComponents);
235 
236 
237         // Create the table.
238         tableAggregate = createTable();
239         getDemoPanel().add(tableAggregate, BorderLayout.CENTER);
240 
241 
242         // ComboBox for selection modes.
243         JPanel selectMode = new JPanel();
244         selectMode.setLayout(new BoxLayout(selectMode, BoxLayout.X_AXIS));
245         selectMode.setBorder(new TitledBorder(getString("TableDemo.selection_mode")));
246 
247 
248         selectionModeComboBox = new JComboBox() {
249             public Dimension getMaximumSize() {
250                 return getPreferredSize();
251             }
252         };
253         selectionModeComboBox.addItem(getString("TableDemo.single"));
254         selectionModeComboBox.addItem(getString("TableDemo.one_range"));
255         selectionModeComboBox.addItem(getString("TableDemo.multiple_ranges"));
256         selectionModeComboBox.setSelectedIndex(tableView.getSelectionModel().getSelectionMode());
257         selectionModeComboBox.addItemListener(new ItemListener() {
258             public void itemStateChanged(ItemEvent e) {
259                 JComboBox source = (JComboBox)e.getSource();
260                 tableView.setSelectionMode(source.getSelectedIndex());
261             }
262         });
263 
264         selectMode.add(Box.createHorizontalStrut(2));
265         selectMode.add(selectionModeComboBox);
266         selectMode.add(Box.createHorizontalGlue());
267         comboPanel.add(selectMode);
268 
269         // Combo box for table resize mode.
270         JPanel resizeMode = new JPanel();
271         resizeMode.setLayout(new BoxLayout(resizeMode, BoxLayout.X_AXIS));
272         resizeMode.setBorder(new TitledBorder(getString("TableDemo.autoresize_mode")));
273 
274 
275         resizeModeComboBox = new JComboBox() {
276             public Dimension getMaximumSize() {
277                 return getPreferredSize();
278             }
279         };
280         resizeModeComboBox.addItem(getString("TableDemo.off"));
281         resizeModeComboBox.addItem(getString("TableDemo.column_boundaries"));
282         resizeModeComboBox.addItem(getString("TableDemo.subsequent_columns"));
283         resizeModeComboBox.addItem(getString("TableDemo.last_column"));
284         resizeModeComboBox.addItem(getString("TableDemo.all_columns"));
285         resizeModeComboBox.setSelectedIndex(tableView.getAutoResizeMode());
286         resizeModeComboBox.addItemListener(new ItemListener() {
287             public void itemStateChanged(ItemEvent e) {
288                 JComboBox source = (JComboBox)e.getSource();
289                 tableView.setAutoResizeMode(source.getSelectedIndex());
290             }
291         });
292 
293         resizeMode.add(Box.createHorizontalStrut(2));
294         resizeMode.add(resizeModeComboBox);
295         resizeMode.add(Box.createHorizontalGlue());
296         comboPanel.add(resizeMode);
297 
298         // print panel
299         printPanel.setBorder(new TitledBorder(getString("TableDemo.printing")));
300         headerLabel = new JLabel(getString("TableDemo.header"));
301         footerLabel = new JLabel(getString("TableDemo.footer"));
302         headerTextField = new JTextField(getString("TableDemo.headerText"), 15);
303         footerTextField = new JTextField(getString("TableDemo.footerText"), 15);
304         fitWidth = new JCheckBox(getString("TableDemo.fitWidth"), true);
305         printButton = new JButton(getString("TableDemo.print"));
306         printButton.addActionListener(new ActionListener() {
307             public void actionPerformed(ActionEvent ae) {
308                 printTable();
309             }
310         });
311 
312         printPanel.add(headerLabel);
313         printPanel.add(headerTextField);
314         printPanel.add(footerLabel);
315         printPanel.add(footerTextField);
316 
317         JPanel buttons = new JPanel();
318         buttons.add(fitWidth);
319         buttons.add(printButton);
320 
321         printPanel.add(buttons);
322 
323         // Show that printing controls are related
324         relatedComponents.removeAllElements();
325         relatedComponents.add(headerTextField);
326         relatedComponents.add(footerTextField);
327         relatedComponents.add(printButton);
328         buildAccessibleGroup(relatedComponents);
329 
330         // wrap up the panels and add them
331         JPanel sliderWrapper = new JPanel();
332         sliderWrapper.setLayout(new BoxLayout(sliderWrapper, BoxLayout.X_AXIS));
333         sliderWrapper.add(labelPanel);
334         sliderWrapper.add(sliderPanel);
335         sliderWrapper.add(Box.createHorizontalGlue());
336         sliderWrapper.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
337 
338         JPanel leftWrapper = new JPanel();
339         leftWrapper.setLayout(new BoxLayout(leftWrapper, BoxLayout.Y_AXIS));
340         leftWrapper.add(cbPanel);
341         leftWrapper.add(sliderWrapper);
342 
343         // add everything
344         controlPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0));
345         controlPanel.add(leftWrapper);
346         controlPanel.add(comboPanel);
347         controlPanel.add(printPanel);
348 
349         setTableControllers(); // Set accessibility information
350 
351         getDemoPanel().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
352             .put(KeyStroke.getKeyStroke("ctrl P"), "print");
353 
354         getDemoPanel().getActionMap().put("print", new AbstractAction() {
355             public void actionPerformed(ActionEvent ae) {
356                 printTable();
357             }
358         });
359 
360     } // TableDemo()
361 
362     /**
363      * Sets the Accessibility MEMBER_OF property to denote that
364      * these components work together as a group. Each object
365      * is set to be a MEMBER_OF an array that contains all of
366      * the objects in the group, including itself.
367      *
368      * @param components The list of objects that are related
369      */
buildAccessibleGroup(Vector components)370     void buildAccessibleGroup(Vector components) {
371 
372         AccessibleContext context = null;
373         int numComponents = components.size();
374         Object[] group = components.toArray();
375         Object object = null;
376         for (int i = 0; i < numComponents; ++i) {
377             object = components.elementAt(i);
378             if (object instanceof Accessible) {
379                 context = ((Accessible)components.elementAt(i)).
380                                                  getAccessibleContext();
381                 context.getAccessibleRelationSet().add(
382                     new AccessibleRelation(
383                         AccessibleRelation.MEMBER_OF, group));
384             }
385         }
386     } // buildAccessibleGroup()
387 
388     /**
389      * This sets CONTROLLER_FOR on the controls that manipulate the
390      * table and CONTROLLED_BY relationships on the table to point
391      * back to the controllers.
392      */
setTableControllers()393     private void setTableControllers() {
394 
395         // Set up the relationships to show what controls the table
396         setAccessibleController(isColumnReorderingAllowedCheckBox,
397                                 tableAggregate);
398         setAccessibleController(showHorizontalLinesCheckBox,
399                                 tableAggregate);
400         setAccessibleController(showVerticalLinesCheckBox,
401                                 tableAggregate);
402         setAccessibleController(isColumnSelectionAllowedCheckBox,
403                                 tableAggregate);
404         setAccessibleController(isRowSelectionAllowedCheckBox,
405                                 tableAggregate);
406         setAccessibleController(interCellSpacingSlider,
407                                 tableAggregate);
408         setAccessibleController(rowHeightSlider,
409                                 tableAggregate);
410         setAccessibleController(selectionModeComboBox,
411                                 tableAggregate);
412         setAccessibleController(resizeModeComboBox,
413                                 tableAggregate);
414     } // setTableControllers()
415 
416     /**
417      * Sets up accessibility relationships to denote that one
418      * object controls another. The CONTROLLER_FOR property is
419      * set on the controller object, and the CONTROLLED_BY
420      * property is set on the target object.
421      */
setAccessibleController(JComponent controller, JComponent target)422     private void setAccessibleController(JComponent controller,
423                                         JComponent target) {
424         AccessibleRelationSet controllerRelations =
425             controller.getAccessibleContext().getAccessibleRelationSet();
426         AccessibleRelationSet targetRelations =
427             target.getAccessibleContext().getAccessibleRelationSet();
428 
429         controllerRelations.add(
430             new AccessibleRelation(
431                 AccessibleRelation.CONTROLLER_FOR, target));
432         targetRelations.add(
433             new AccessibleRelation(
434                 AccessibleRelation.CONTROLLED_BY, controller));
435     } // setAccessibleController()
436 
createTable()437     public JScrollPane createTable() {
438 
439         // final
440         final String[] names = {
441           getString("TableDemo.first_name"),
442           getString("TableDemo.last_name"),
443           getString("TableDemo.favorite_color"),
444           getString("TableDemo.favorite_movie"),
445           getString("TableDemo.favorite_number"),
446           getString("TableDemo.favorite_food")
447         };
448 
449         ImageIcon apple        = createImageIcon("food/apple.jpg",      getString("TableDemo.apple"));
450         ImageIcon asparagus    = createImageIcon("food/asparagus.gif",  getString("TableDemo.asparagus"));
451         ImageIcon banana       = createImageIcon("food/banana.gif",     getString("TableDemo.banana"));
452         ImageIcon broccoli     = createImageIcon("food/broccoli.gif",   getString("TableDemo.broccoli"));
453         ImageIcon cantaloupe   = createImageIcon("food/cantaloupe.gif", getString("TableDemo.cantaloupe"));
454         ImageIcon carrot       = createImageIcon("food/carrot.gif",     getString("TableDemo.carrot"));
455         ImageIcon corn         = createImageIcon("food/corn.gif",       getString("TableDemo.corn"));
456         ImageIcon grapes       = createImageIcon("food/grapes.gif",     getString("TableDemo.grapes"));
457         ImageIcon grapefruit   = createImageIcon("food/grapefruit.gif", getString("TableDemo.grapefruit"));
458         ImageIcon kiwi         = createImageIcon("food/kiwi.gif",       getString("TableDemo.kiwi"));
459         ImageIcon onion        = createImageIcon("food/onion.gif",      getString("TableDemo.onion"));
460         ImageIcon pear         = createImageIcon("food/pear.gif",       getString("TableDemo.pear"));
461         ImageIcon peach        = createImageIcon("food/peach.gif",      getString("TableDemo.peach"));
462         ImageIcon pepper       = createImageIcon("food/pepper.gif",     getString("TableDemo.pepper"));
463         ImageIcon pickle       = createImageIcon("food/pickle.gif",     getString("TableDemo.pickle"));
464         ImageIcon pineapple    = createImageIcon("food/pineapple.gif",  getString("TableDemo.pineapple"));
465         ImageIcon raspberry    = createImageIcon("food/raspberry.gif",  getString("TableDemo.raspberry"));
466         ImageIcon sparegrass   = createImageIcon("food/asparagus.gif",  getString("TableDemo.sparegrass"));
467         ImageIcon strawberry   = createImageIcon("food/strawberry.gif", getString("TableDemo.strawberry"));
468         ImageIcon tomato       = createImageIcon("food/tomato.gif",     getString("TableDemo.tomato"));
469         ImageIcon watermelon   = createImageIcon("food/watermelon.gif", getString("TableDemo.watermelon"));
470 
471         NamedColor aqua        = new NamedColor(new Color(127, 255, 212), getString("TableDemo.aqua"));
472         NamedColor beige       = new NamedColor(new Color(245, 245, 220), getString("TableDemo.beige"));
473         NamedColor black       = new NamedColor(Color.black, getString("TableDemo.black"));
474         NamedColor blue        = new NamedColor(new Color(0, 0, 222), getString("TableDemo.blue"));
475         NamedColor eblue       = new NamedColor(Color.blue, getString("TableDemo.eblue"));
476         NamedColor jfcblue     = new NamedColor(new Color(204, 204, 255), getString("TableDemo.jfcblue"));
477         NamedColor jfcblue2    = new NamedColor(new Color(153, 153, 204), getString("TableDemo.jfcblue2"));
478         NamedColor cybergreen  = new NamedColor(Color.green.darker().brighter(), getString("TableDemo.cybergreen"));
479         NamedColor darkgreen   = new NamedColor(new Color(0, 100, 75), getString("TableDemo.darkgreen"));
480         NamedColor forestgreen = new NamedColor(Color.green.darker(), getString("TableDemo.forestgreen"));
481         NamedColor gray        = new NamedColor(Color.gray, getString("TableDemo.gray"));
482         NamedColor green       = new NamedColor(Color.green, getString("TableDemo.green"));
483         NamedColor orange      = new NamedColor(new Color(255, 165, 0), getString("TableDemo.orange"));
484         NamedColor purple      = new NamedColor(new Color(160, 32, 240),  getString("TableDemo.purple"));
485         NamedColor red         = new NamedColor(Color.red, getString("TableDemo.red"));
486         NamedColor rustred     = new NamedColor(Color.red.darker(), getString("TableDemo.rustred"));
487         NamedColor sunpurple   = new NamedColor(new Color(100, 100, 255), getString("TableDemo.sunpurple"));
488         NamedColor suspectpink = new NamedColor(new Color(255, 105, 180), getString("TableDemo.suspectpink"));
489         NamedColor turquoise   = new NamedColor(new Color(0, 255, 255), getString("TableDemo.turquoise"));
490         NamedColor violet      = new NamedColor(new Color(238, 130, 238), getString("TableDemo.violet"));
491         NamedColor yellow      = new NamedColor(Color.yellow, getString("TableDemo.yellow"));
492 
493         // Create the dummy data (a few rows of names)
494         final Object[][] data = {
495           {"Mike", "Albers",      green,       getString("TableDemo.brazil"), new Double(44.0), strawberry},
496           {"Mark", "Andrews",     blue,        getString("TableDemo.curse"), new Double(3), grapes},
497           {"Brian", "Beck",       black,       getString("TableDemo.bluesbros"), new Double(2.7182818285), raspberry},
498           {"Lara", "Bunni",       red,         getString("TableDemo.airplane"), new Double(15), strawberry},
499           {"Roger", "Brinkley",   blue,        getString("TableDemo.man"), new Double(13), peach},
500           {"Brent", "Christian",  black,       getString("TableDemo.bladerunner"), new Double(23), broccoli},
501           {"Mark", "Davidson",    darkgreen,   getString("TableDemo.brazil"), new Double(27), asparagus},
502           {"Jeff", "Dinkins",     blue,        getString("TableDemo.ladyvanishes"), new Double(8), kiwi},
503           {"Ewan", "Dinkins",     yellow,      getString("TableDemo.bugs"), new Double(2), strawberry},
504           {"Amy", "Fowler",       violet,      getString("TableDemo.reservoir"), new Double(3), raspberry},
505           {"Hania", "Gajewska",   purple,      getString("TableDemo.jules"), new Double(5), raspberry},
506           {"David", "Geary",      blue,        getString("TableDemo.pulpfiction"), new Double(3), watermelon},
507 //        {"James", "Gosling",    pink,        getString("TableDemo.tennis"), new Double(21), donut},
508           {"Eric", "Hawkes",      blue,        getString("TableDemo.bladerunner"), new Double(.693), pickle},
509           {"Shannon", "Hickey",   green,       getString("TableDemo.shawshank"), new Double(2), grapes},
510           {"Earl", "Johnson",     green,       getString("TableDemo.pulpfiction"), new Double(8), carrot},
511           {"Robi", "Khan",        green,       getString("TableDemo.goodfellas"), new Double(89), apple},
512           {"Robert", "Kim",       blue,        getString("TableDemo.mohicans"), new Double(655321), strawberry},
513           {"Janet", "Koenig",     turquoise,   getString("TableDemo.lonestar"), new Double(7), peach},
514           {"Jeff", "Kesselman",   blue,        getString("TableDemo.stuntman"), new Double(17), pineapple},
515           {"Onno", "Kluyt",       orange,      getString("TableDemo.oncewest"), new Double(8), broccoli},
516           {"Peter", "Korn",       sunpurple,   getString("TableDemo.musicman"), new Double(12), sparegrass},
517 
518           {"Rick", "Levenson",    black,       getString("TableDemo.harold"), new Double(1327), raspberry},
519           {"Brian", "Lichtenwalter", jfcblue,  getString("TableDemo.fifthelement"), new Double(22), pear},
520           {"Malini", "Minasandram", beige,     getString("TableDemo.joyluck"), new Double(9), corn},
521           {"Michael", "Martak",   green,       getString("TableDemo.city"), new Double(3), strawberry},
522           {"David", "Mendenhall", forestgreen, getString("TableDemo.schindlerslist"), new Double(7), peach},
523           {"Phil", "Milne",       suspectpink, getString("TableDemo.withnail"), new Double(3), banana},
524           {"Lynn", "Monsanto",    cybergreen,  getString("TableDemo.dasboot"), new Double(52), peach},
525           {"Hans", "Muller",      rustred,     getString("TableDemo.eraserhead"), new Double(0), pineapple},
526           {"Joshua", "Outwater",  blue,        getString("TableDemo.labyrinth"), new Double(3), pineapple},
527           {"Tim", "Prinzing",     blue,        getString("TableDemo.firstsight"), new Double(69), pepper},
528           {"Raj", "Premkumar",    jfcblue2,    getString("TableDemo.none"), new Double(7), broccoli},
529           {"Howard", "Rosen",     green,       getString("TableDemo.defending"), new Double(7), strawberry},
530           {"Ray", "Ryan",         black,       getString("TableDemo.buckaroo"),
531            new Double(3.141592653589793238462643383279502884197169399375105820974944), banana},
532           {"Georges", "Saab",     aqua,        getString("TableDemo.bicycle"), new Double(290), cantaloupe},
533           {"Tom", "Santos",       blue,        getString("TableDemo.spinaltap"), new Double(241), pepper},
534           {"Rich", "Schiavi",     blue,        getString("TableDemo.repoman"), new Double(0xFF), pepper},
535           {"Nancy", "Schorr",     green,       getString("TableDemo.fifthelement"), new Double(47), watermelon},
536           {"Keith", "Sprochi",    darkgreen,   getString("TableDemo.2001"), new Double(13), watermelon},
537           {"Matt", "Tucker",      eblue,       getString("TableDemo.starwars"), new Double(2), broccoli},
538           {"Dmitri", "Trembovetski", red,      getString("TableDemo.aliens"), new Double(222), tomato},
539           {"Scott", "Violet",     violet,      getString("TableDemo.raiders"), new Double(-97), banana},
540           {"Kathy", "Walrath",    darkgreen,   getString("TableDemo.thinman"), new Double(8), pear},
541           {"Nathan", "Walrath",   black,       getString("TableDemo.chusingura"), new Double(3), grapefruit},
542           {"Steve", "Wilson",     green,       getString("TableDemo.raiders"), new Double(7), onion},
543           {"Kathleen", "Zelony",  gray,        getString("TableDemo.dog"), new Double(13), grapes}
544         };
545 
546         // Create a model of the data.
547         TableModel dataModel = new AbstractTableModel() {
548             public int getColumnCount() { return names.length; }
549             public int getRowCount() { return data.length;}
550             public Object getValueAt(int row, int col) {return data[row][col];}
551             public String getColumnName(int column) {return names[column];}
552             public Class getColumnClass(int c) {return getValueAt(0, c).getClass();}
553             public boolean isCellEditable(int row, int col) {return col != 5;}
554             public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; }
555          };
556 
557 
558         // Create the table
559         tableView = new JTable(dataModel);
560         TableRowSorter sorter = new TableRowSorter(dataModel);
561         tableView.setRowSorter(sorter);
562 
563         // Show colors by rendering them in their own color.
564         DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {
565             public void setValue(Object value) {
566                 if (value instanceof NamedColor) {
567                     NamedColor c = (NamedColor) value;
568                     setBackground(c);
569                     setForeground(c.getTextColor());
570                     setText(c.toString());
571                 } else {
572                     super.setValue(value);
573                 }
574             }
575         };
576 
577         // Create a combo box to show that you can use one in a table.
578         JComboBox comboBox = new JComboBox();
579         comboBox.addItem(aqua);
580         comboBox.addItem(beige);
581         comboBox.addItem(black);
582         comboBox.addItem(blue);
583         comboBox.addItem(eblue);
584         comboBox.addItem(jfcblue);
585         comboBox.addItem(jfcblue2);
586         comboBox.addItem(cybergreen);
587         comboBox.addItem(darkgreen);
588         comboBox.addItem(forestgreen);
589         comboBox.addItem(gray);
590         comboBox.addItem(green);
591         comboBox.addItem(orange);
592         comboBox.addItem(purple);
593         comboBox.addItem(red);
594         comboBox.addItem(rustred);
595         comboBox.addItem(sunpurple);
596         comboBox.addItem(suspectpink);
597         comboBox.addItem(turquoise);
598         comboBox.addItem(violet);
599         comboBox.addItem(yellow);
600 
601         TableColumn colorColumn = tableView.getColumn(getString("TableDemo.favorite_color"));
602         // Use the combo box as the editor in the "Favorite Color" column.
603         colorColumn.setCellEditor(new DefaultCellEditor(comboBox));
604 
605         colorRenderer.setHorizontalAlignment(JLabel.CENTER);
606         colorColumn.setCellRenderer(colorRenderer);
607 
608         tableView.setRowHeight(INITIAL_ROWHEIGHT);
609 
610         scrollpane = new JScrollPane(tableView);
611         return scrollpane;
612     }
613 
printTable()614     private void printTable() {
615         MessageFormat headerFmt;
616         MessageFormat footerFmt;
617         JTable.PrintMode printMode = fitWidth.isSelected() ?
618                                      JTable.PrintMode.FIT_WIDTH :
619                                      JTable.PrintMode.NORMAL;
620 
621         String text;
622         text = headerTextField.getText();
623         if (text != null && text.length() > 0) {
624             headerFmt = new MessageFormat(text);
625         } else {
626             headerFmt = null;
627         }
628 
629         text = footerTextField.getText();
630         if (text != null && text.length() > 0) {
631             footerFmt = new MessageFormat(text);
632         } else {
633             footerFmt = null;
634         }
635 
636         try {
637             boolean status = tableView.print(printMode, headerFmt, footerFmt);
638 
639             if (status) {
640                 JOptionPane.showMessageDialog(tableView.getParent(),
641                                               getString("TableDemo.printingComplete"),
642                                               getString("TableDemo.printingResult"),
643                                               JOptionPane.INFORMATION_MESSAGE);
644             } else {
645                 JOptionPane.showMessageDialog(tableView.getParent(),
646                                               getString("TableDemo.printingCancelled"),
647                                               getString("TableDemo.printingResult"),
648                                               JOptionPane.INFORMATION_MESSAGE);
649             }
650         } catch (PrinterException pe) {
651             String errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"),
652                                                        new Object[] {pe.getMessage()});
653             JOptionPane.showMessageDialog(tableView.getParent(),
654                                           errorMessage,
655                                           getString("TableDemo.printingResult"),
656                                           JOptionPane.ERROR_MESSAGE);
657         } catch (SecurityException se) {
658             String errorMessage = MessageFormat.format(getString("TableDemo.printingFailed"),
659                                                        new Object[] {se.getMessage()});
660             JOptionPane.showMessageDialog(tableView.getParent(),
661                                           errorMessage,
662                                           getString("TableDemo.printingResult"),
663                                           JOptionPane.ERROR_MESSAGE);
664         }
665     }
666 
667     class NamedColor extends Color {
668         String name;
NamedColor(Color color, String name)669         public NamedColor(Color color, String name) {
670             super(color.getRGB());
671             this.name = name;
672         }
673 
getTextColor()674         public Color getTextColor() {
675             int r = getRed();
676             int g = getGreen();
677             int b = getBlue();
678             if(r > 240 || g > 240) {
679                 return Color.black;
680             } else {
681                 return Color.white;
682             }
683         }
684 
toString()685         public String toString() {
686             return name;
687         }
688     }
689 
690     class ColumnLayout implements LayoutManager {
691         int xInset = 5;
692         int yInset = 5;
693         int yGap = 2;
694 
addLayoutComponent(String s, Component c)695         public void addLayoutComponent(String s, Component c) {}
696 
layoutContainer(Container c)697         public void layoutContainer(Container c) {
698             Insets insets = c.getInsets();
699             int height = yInset + insets.top;
700 
701             Component[] children = c.getComponents();
702             Dimension compSize = null;
703             for (int i = 0; i < children.length; i++) {
704                 compSize = children[i].getPreferredSize();
705                 children[i].setSize(compSize.width, compSize.height);
706                 children[i].setLocation( xInset + insets.left, height);
707                 height += compSize.height + yGap;
708             }
709 
710         }
711 
minimumLayoutSize(Container c)712         public Dimension minimumLayoutSize(Container c) {
713             Insets insets = c.getInsets();
714             int height = yInset + insets.top;
715             int width = 0 + insets.left + insets.right;
716 
717             Component[] children = c.getComponents();
718             Dimension compSize = null;
719             for (int i = 0; i < children.length; i++) {
720                 compSize = children[i].getPreferredSize();
721                 height += compSize.height + yGap;
722                 width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2);
723             }
724             height += insets.bottom;
725             return new Dimension( width, height);
726         }
727 
preferredLayoutSize(Container c)728         public Dimension preferredLayoutSize(Container c) {
729             return minimumLayoutSize(c);
730         }
731 
removeLayoutComponent(Component c)732         public void removeLayoutComponent(Component c) {}
733     }
734 
updateDragEnabled(boolean dragEnabled)735     void updateDragEnabled(boolean dragEnabled) {
736         tableView.setDragEnabled(dragEnabled);
737         headerTextField.setDragEnabled(dragEnabled);
738         footerTextField.setDragEnabled(dragEnabled);
739     }
740 
741 }
742