~ubuntu-branches/ubuntu/natty/libswingx-java/natty

« back to all changes in this revision

Viewing changes to src/demo/org/jdesktop/swingx/renderer/AnimatedRendererDemo.java

  • Committer: Bazaar Package Importer
  • Author(s): Damien Raude-Morvan
  • Date: 2010-07-26 12:11:27 UTC
  • mfrom: (4.1.4 sid)
  • Revision ID: james.westby@ubuntu.com-20100726121127-k0d3b21nhja0dn93
Tags: 1:1.6.1-1
* New upstream release.
* Switch to 3.0 (quilt) format.
* Bump Standards-Version to 3.9.1: no changes needed.
* Drop Depends on JRE: not requested anymore by new Java Policy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * $Id: AnimatedRendererDemo.java 3471 2009-08-27 13:10:39Z kleopatra $
3
 
 *
4
 
 * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle,
5
 
 * Santa Clara, California 95054, U.S.A. All rights reserved.
6
 
 *
7
 
 * This library is free software; you can redistribute it and/or
8
 
 * modify it under the terms of the GNU Lesser General Public
9
 
 * License as published by the Free Software Foundation; either
10
 
 * version 2.1 of the License, or (at your option) any later version.
11
 
 * 
12
 
 * This library is distributed in the hope that it will be useful,
13
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 
 * Lesser General Public License for more details.
16
 
 * 
17
 
 * You should have received a copy of the GNU Lesser General Public
18
 
 * License along with this library; if not, write to the Free Software
19
 
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
 
 *
21
 
 */
22
 
package org.jdesktop.swingx.renderer;
23
 
 
24
 
import java.awt.AlphaComposite;
25
 
import java.awt.Component;
26
 
import java.awt.Graphics2D;
27
 
import java.awt.event.ActionEvent;
28
 
import java.awt.event.ActionListener;
29
 
import java.awt.image.BufferedImage;
30
 
import java.io.BufferedReader;
31
 
import java.io.IOException;
32
 
import java.io.InputStream;
33
 
import java.io.InputStreamReader;
34
 
import java.util.ArrayList;
35
 
import java.util.List;
36
 
import java.util.StringTokenizer;
37
 
import java.util.logging.Logger;
38
 
 
39
 
import javax.imageio.ImageIO;
40
 
import javax.swing.AbstractListModel;
41
 
import javax.swing.JScrollPane;
42
 
import javax.swing.JSplitPane;
43
 
import javax.swing.JTabbedPane;
44
 
import javax.swing.ListModel;
45
 
import javax.swing.SwingUtilities;
46
 
import javax.swing.Timer;
47
 
import javax.swing.UIManager;
48
 
import javax.swing.UnsupportedLookAndFeelException;
49
 
import javax.swing.table.AbstractTableModel;
50
 
import javax.swing.table.TableModel;
51
 
import javax.swing.tree.DefaultMutableTreeNode;
52
 
import javax.swing.tree.DefaultTreeModel;
53
 
 
54
 
import org.jdesktop.swingx.JXFrame;
55
 
import org.jdesktop.swingx.JXList;
56
 
import org.jdesktop.swingx.JXTable;
57
 
import org.jdesktop.swingx.JXTree;
58
 
import org.jdesktop.swingx.decorator.ComponentAdapter;
59
 
import org.jdesktop.swingx.decorator.CompoundHighlighter;
60
 
import org.jdesktop.swingx.decorator.HighlightPredicate;
61
 
import org.jdesktop.swingx.decorator.PainterHighlighter;
62
 
import org.jdesktop.swingx.decorator.HighlightPredicate.AndHighlightPredicate;
63
 
import org.jdesktop.swingx.decorator.HighlightPredicate.TypeHighlightPredicate;
64
 
import org.jdesktop.swingx.graphics.GraphicsUtilities;
65
 
import org.jdesktop.swingx.painter.AbstractLayoutPainter;
66
 
import org.jdesktop.swingx.painter.ImagePainter;
67
 
import org.jdesktop.swingx.painter.Painter;
68
 
import org.jdesktop.swingx.painter.AbstractLayoutPainter.HorizontalAlignment;
69
 
import org.jdesktop.swingx.util.WindowUtils;
70
 
 
71
 
/**
72
 
 * A simple example about how to configure SwingX renderers.
73
 
 * 
74
 
 * @author Jeanette Winzenburg
75
 
 */
76
 
public final class AnimatedRendererDemo {
77
 
    @SuppressWarnings("unused")
78
 
    private static final Logger LOG = Logger.getLogger(AnimatedRendererDemo.class
79
 
            .getName());
80
 
    private String dataSource = "resources/contributors.txt";
81
 
    private List<Contributor> contributors;
82
 
    private ListModel listModel;
83
 
    private TableModel tableModel;
84
 
    private DefaultMutableTreeNode rootNode;
85
 
 
86
 
    public AnimatedRendererDemo() {
87
 
        try {
88
 
            initData();
89
 
        } catch (IOException e) {
90
 
            e.printStackTrace();
91
 
        }
92
 
    }
93
 
 
94
 
    /**
95
 
     * Configure the given collection components with the same
96
 
     * rendering representation.
97
 
     * 
98
 
     * Note: this method is extracted for emphasis only :-)
99
 
     */
100
 
    private void configureRendering(JXTable table, JXList list, JXTree tree) {
101
 
        StringValue stringValue = new StringValue() {
102
 
            
103
 
            public String getString(Object value) {
104
 
                if (!(value instanceof Contributor)) return StringValues.TO_STRING.getString(value);
105
 
                Contributor contributor = (Contributor) value;
106
 
                return contributor.lastName + ", " + contributor.firstName;
107
 
            }
108
 
            
109
 
        };
110
 
        table.setDefaultRenderer(Contributor.class, new DefaultTableRenderer(stringValue));
111
 
        list.setCellRenderer(new DefaultListRenderer(stringValue));
112
 
        tree.setCellRenderer(new DefaultTreeRenderer(stringValue));
113
 
        
114
 
    }
115
 
 
116
 
    private void configureHighlighting(JXTable table, JXList list, JXTree tree) {
117
 
        CompoundHighlighter stars = new CompoundHighlighter(
118
 
                new AndHighlightPredicate(
119
 
                        HighlightPredicate.ROLLOVER_ROW, 
120
 
                        new TypeHighlightPredicate(Contributor.class)));
121
 
        PainterHighlighter silverHL = getRangeHighlighter("silver-star.gif", 50, 80);
122
 
        stars.addHighlighter(silverHL);
123
 
        PainterHighlighter goldHL = getRangeHighlighter("gold-star.gif", 80, 100);
124
 
        stars.addHighlighter(goldHL);
125
 
        table.addHighlighter(stars);
126
 
        list.addHighlighter(stars);
127
 
        list.setRolloverEnabled(true);
128
 
        final RelativePainter<?> silver = (RelativePainter<?>) silverHL.getPainter();
129
 
        silver.setXFactor(1.);
130
 
        final RelativePainter<?> gold = (RelativePainter<?>) goldHL.getPainter();
131
 
        gold.setXFactor(1.0);
132
 
        ActionListener l = new ActionListener() {
133
 
            public void actionPerformed(ActionEvent e) {
134
 
                double fraction = silver.getXFactor();
135
 
                fraction = fraction < 0 ? 1.0 : fraction - 0.1;
136
 
                silver.setXFactor(fraction);
137
 
                gold.setXFactor(fraction);
138
 
            }
139
 
            
140
 
        };
141
 
        new Timer(500, l).start();
142
 
    }
143
 
 
144
 
 
145
 
    private PainterHighlighter getRangeHighlighter(String gifName, int start,
146
 
            int end) {
147
 
        HighlightPredicate meritPredicate = getRangePredicate(start, end);
148
 
        Painter<? super Component> bronze = getImagePainter(gifName);
149
 
        PainterHighlighter painterHighlighter = new PainterHighlighter(meritPredicate, 
150
 
                new RelativePainter<Component>(bronze));
151
 
        return painterHighlighter;
152
 
    }
153
 
 
154
 
    private HighlightPredicate getRangePredicate(final int start, final int end) {
155
 
        HighlightPredicate meritPredicate = new HighlightPredicate() {
156
 
 
157
 
            public boolean isHighlighted(Component renderer,
158
 
                    ComponentAdapter adapter) {
159
 
                int merit = ((Contributor) adapter.getValue()).merits;
160
 
                return (merit >= start) && (merit < end);
161
 
            }
162
 
            
163
 
        };
164
 
        return meritPredicate;
165
 
    }
166
 
 
167
 
 
168
 
    /**
169
 
     * Configures the components after the meta-data are set. In this simple example,
170
 
     * it's equivalent to having set the models.
171
 
     * 
172
 
     * @param table
173
 
     */
174
 
    private void configureComponents(JXTable table, JXList list, JXTree tree) {
175
 
        table.setColumnControlVisible(true);
176
 
        table.getColumnExt(1).setToolTipText("Randomly generated - run again if you are disatisfied");
177
 
        table.packColumn(1, 10);
178
 
        table.getColumnExt(1).setMaxWidth(table.getColumnExt(1).getPreferredWidth());
179
 
    }
180
 
    
181
 
 
182
 
    /**
183
 
     * @return the component to show.
184
 
     */
185
 
    private Component createContent() {
186
 
        // create
187
 
        JXTable table = new JXTable();
188
 
        JXList list = new JXList();
189
 
        JXTree tree = new JXTree();
190
 
        // add
191
 
        table.setModel(tableModel);
192
 
        list.setModel(listModel);
193
 
        tree.setModel(new DefaultTreeModel(rootNode));
194
 
        // configure
195
 
        configureRendering(table, list, tree);
196
 
        configureHighlighting(table, list, tree);
197
 
        configureComponents(table, list, tree);
198
 
        JTabbedPane tabbedPane = new JTabbedPane();
199
 
        tabbedPane.addTab("JXTable", new JScrollPane(table));
200
 
        JSplitPane splitPane = new JSplitPane();
201
 
        splitPane.setLeftComponent(new JScrollPane(list));
202
 
        splitPane.setRightComponent(new JScrollPane(tree));
203
 
//        splitPane.setDividerLocation(250);
204
 
        tabbedPane.addTab("JXList/JXTree", splitPane);
205
 
        return tabbedPane;
206
 
    }
207
 
 
208
 
    
209
 
    /**
210
 
     * @param string
211
 
     * @return
212
 
     */
213
 
    private Painter<? super Component> getImagePainter(String string) {
214
 
        ImagePainter imagePainter = null;
215
 
        BufferedImage image = null;
216
 
        try {
217
 
            image = ImageIO.read(getClass()
218
 
                    .getResource("resources/" + string));
219
 
            BufferedImage mod = 
220
 
              GraphicsUtilities.createCompatibleTranslucentImage(
221
 
                      image.getWidth(), 
222
 
                      image.getHeight());
223
 
            Graphics2D g = mod.createGraphics();
224
 
            
225
 
            try {
226
 
                g.setComposite(AlphaComposite.getInstance(
227
 
                        AlphaComposite.SRC_OVER, 0.8f));
228
 
                g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(),
229
 
                        null);
230
 
            } finally {
231
 
                g.dispose();
232
 
            }
233
 
            
234
 
            imagePainter = new ImagePainter(mod);
235
 
            imagePainter.setHorizontalAlignment(HorizontalAlignment.RIGHT);
236
 
        } catch (IOException e) {
237
 
            // TODO Auto-generated catch block
238
 
            e.printStackTrace();
239
 
        }
240
 
        return imagePainter;
241
 
    }
242
 
 
243
 
 
244
 
    /**
245
 
     * Create and fill a list of contributors from a resource and 
246
 
     * wrap view models around.
247
 
     * @throws IOException 
248
 
     * 
249
 
     */
250
 
    private void initData() throws IOException {
251
 
        contributors = new ArrayList<Contributor>();
252
 
        // fill the list from the resources
253
 
        readDataSource(contributors);
254
 
        // wrap a listModel around
255
 
        listModel = new AbstractListModel() {
256
 
 
257
 
            public Object getElementAt(int index) {
258
 
                if (index == 0) {
259
 
                    return "-- Contributors --";
260
 
                }
261
 
                return contributors.get(index - 1);
262
 
            }
263
 
 
264
 
            public int getSize() {
265
 
                return contributors.size() + 1;
266
 
            }
267
 
            
268
 
        };
269
 
        // wrap a TableModel around
270
 
        tableModel = new AbstractTableModel() {
271
 
 
272
 
            public int getColumnCount() {
273
 
                return 2;
274
 
            }
275
 
 
276
 
            public int getRowCount() {
277
 
                return contributors.size();
278
 
            }
279
 
 
280
 
            public Object getValueAt(int rowIndex, int columnIndex) {
281
 
                switch (columnIndex) {
282
 
                case 0:
283
 
                    return contributors.get(rowIndex);
284
 
                case 1:
285
 
                    return contributors.get(rowIndex).merits;
286
 
                }
287
 
                return null;
288
 
            }
289
 
 
290
 
            @Override
291
 
            public Class<?> getColumnClass(int columnIndex) {
292
 
                switch (columnIndex) {
293
 
                case 0:
294
 
                    return Contributor.class;
295
 
                case 1:
296
 
                    return Number.class;
297
 
                }
298
 
                return super.getColumnClass(columnIndex);
299
 
            }
300
 
 
301
 
            @Override
302
 
            public String getColumnName(int column) {
303
 
                switch (column) {
304
 
                case 0:
305
 
                    return "Contributor";
306
 
                case 1:
307
 
                    return "Merits";
308
 
                }
309
 
                return super.getColumnName(column);
310
 
            }
311
 
 
312
 
            @Override
313
 
            public boolean isCellEditable(int rowIndex, int columnIndex) {
314
 
                return true;
315
 
            }
316
 
            
317
 
            
318
 
        };
319
 
        // fill DefaultTreeNodes with the elements 
320
 
        rootNode = new DefaultMutableTreeNode("Contributors");
321
 
        for (int i = 0; i < contributors.size(); i++) {
322
 
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(contributors.get(i));
323
 
            rootNode.add(node);
324
 
        }
325
 
        
326
 
    }
327
 
    
328
 
    private void readDataSource(List<Contributor> list) throws IOException {
329
 
        InputStream is = getClass().getResourceAsStream(dataSource);
330
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
331
 
        String line;
332
 
        try {
333
 
            while ((line = reader.readLine()) != null) {
334
 
                list.add(new Contributor(line));
335
 
            }
336
 
        } finally {
337
 
            // do our best to close
338
 
            reader.close();
339
 
        }
340
 
    }
341
 
    
342
 
    public static class Contributor implements Comparable<Contributor> {
343
 
        private String firstName;
344
 
        private String lastName;
345
 
        @SuppressWarnings("unused")
346
 
        private String userID;
347
 
        private int merits;
348
 
        
349
 
        public Contributor(String rawData) {
350
 
            setData(rawData);
351
 
            merits = new Double(Math.random() * 100).intValue();
352
 
        }
353
 
 
354
 
        /**
355
 
         * @param rawData
356
 
         */
357
 
        private void setData(String rawData) {
358
 
            if (rawData == null) {
359
 
                lastName = " <unknown> ";
360
 
                return;
361
 
            }
362
 
            StringTokenizer tokenizer = new StringTokenizer(rawData);
363
 
            try {
364
 
               firstName = tokenizer.nextToken();
365
 
               lastName = tokenizer.nextToken();
366
 
               userID = tokenizer.nextToken();
367
 
            } catch (Exception ex) {
368
 
                // don't care ...
369
 
            }
370
 
            
371
 
        }
372
 
 
373
 
        public int compareTo(Contributor o) {
374
 
            return lastName.compareTo(o.lastName);
375
 
        }
376
 
    }
377
 
 
378
 
    //--------- hack around missing size proportional painters
379
 
    
380
 
    public static class RelativePainter<T> extends AbstractLayoutPainter<T> {
381
 
 
382
 
        private Painter<? super T> painter;
383
 
        private double xFactor;
384
 
        private double yFactor;
385
 
 
386
 
        public RelativePainter() {
387
 
            this(null);
388
 
        }
389
 
        
390
 
        public RelativePainter(Painter<? super T> delegate) {
391
 
            setPainter(delegate);
392
 
        }
393
 
        
394
 
        
395
 
        public void setPainter(Painter<? super T> painter) {
396
 
            Object old = getPainter();
397
 
            this.painter = painter;
398
 
            firePropertyChange("painter", old, getPainter());
399
 
        }
400
 
        
401
 
        public Painter<? super T> getPainter() {
402
 
            return painter;
403
 
        }
404
 
        public void setXFactor(double xPercent) {
405
 
            double old = getXFactor();
406
 
            this.xFactor = xPercent;
407
 
            firePropertyChange("xFactor", old, getXFactor());
408
 
        }
409
 
        
410
 
        /**
411
 
         * @return
412
 
         */
413
 
        public double getXFactor() {
414
 
            return xFactor;
415
 
        }
416
 
 
417
 
        public void setYFactor(double yPercent) {
418
 
            double old = getYFactor();
419
 
            this.yFactor = yPercent;
420
 
            firePropertyChange("yFactor", old, getYFactor());
421
 
            
422
 
        }
423
 
        /**
424
 
         * @return
425
 
         */
426
 
        public double getYFactor() {
427
 
            return yFactor;
428
 
        }
429
 
 
430
 
        @Override
431
 
        protected void doPaint(Graphics2D g, T object, int width, int height) {
432
 
            if (painter == null) return;
433
 
            // use epsilon
434
 
            if (xFactor != 0.0) {
435
 
                int oldWidth = width;
436
 
                width = (int) (xFactor * width);
437
 
                if (getHorizontalAlignment() == HorizontalAlignment.RIGHT) {
438
 
                    g.translate(oldWidth - width, 0);
439
 
                }
440
 
            }
441
 
            if (yFactor != 0.0) {
442
 
                int oldHeight = height;
443
 
                height = (int) (yFactor * height);
444
 
                if (getVerticalAlignment() == VerticalAlignment.BOTTOM) {
445
 
                    g.translate(0, oldHeight - height);
446
 
                }
447
 
            }
448
 
            
449
 
            painter.paint(g, object, width, height);
450
 
        }
451
 
        
452
 
    }
453
 
 
454
 
    //---------------------------Main
455
 
 
456
 
    public static void main(String[] args) {
457
 
//        initLF();
458
 
        final JXFrame frame = new JXFrame("SwingX :: Animated Renderer Demo", true);
459
 
        frame.add(new AnimatedRendererDemo().createContent());
460
 
        SwingUtilities.invokeLater(new Runnable() {
461
 
            public void run() {
462
 
                frame.pack();
463
 
                frame.setSize(600, 400);
464
 
                frame.setLocation(WindowUtils.getPointForCentering(frame));
465
 
                frame.setVisible(true);
466
 
            }
467
 
        });        
468
 
    }
469
 
 
470
 
    @SuppressWarnings("unused")
471
 
    private static void initLF() {
472
 
        try {
473
 
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
474
 
        } catch (ClassNotFoundException e) {
475
 
            // TODO Auto-generated catch block
476
 
            e.printStackTrace();
477
 
        } catch (InstantiationException e) {
478
 
            // TODO Auto-generated catch block
479
 
            e.printStackTrace();
480
 
        } catch (IllegalAccessException e) {
481
 
            // TODO Auto-generated catch block
482
 
            e.printStackTrace();
483
 
        } catch (UnsupportedLookAndFeelException e) {
484
 
            // TODO Auto-generated catch block
485
 
            e.printStackTrace();
486
 
        }
487
 
        
488
 
    }
489
 
 
490
 
}