-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathUIManagerDefaults.java
More file actions
746 lines (629 loc) · 17.5 KB
/
UIManagerDefaults.java
File metadata and controls
746 lines (629 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
/*
* This programs uses the information found in the UIManager
* to create a table of key/value pairs for each Swing component.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.table.*;
public class UIManagerDefaults implements ActionListener, ItemListener
{
private final static String[] COLUMN_NAMES = {"Key", "Value", "Sample"};
private static String selectedItem;
private JComponent contentPane;
private JMenuBar menuBar;
private JComboBox comboBox;
private JRadioButton byComponent;
private JTable table;
private TreeMap<String, TreeMap<String, Object>> items;
private HashMap<String, DefaultTableModel> models;
/*
* Constructor
*/
public UIManagerDefaults()
{
items = new TreeMap<String, TreeMap<String, Object>>();
models = new HashMap<String, DefaultTableModel>();
contentPane = new JPanel( new BorderLayout() );
contentPane.add(buildNorthComponent(), BorderLayout.NORTH);
contentPane.add(buildCenterComponent(), BorderLayout.CENTER);
resetComponents();
}
/*
* The content pane should be added to a high level container
*/
public JComponent getContentPane()
{
return contentPane;
}
/*
* A menu can also be added which provides the ability to switch
* between different LAF's.
*/
public JMenuBar getMenuBar()
{
if (menuBar == null)
menuBar = createMenuBar();
return menuBar;
}
/*
* This panel is added to the North of the content pane
*/
private JComponent buildNorthComponent()
{
comboBox = new JComboBox();
JLabel label = new JLabel("Select Item:");
label.setDisplayedMnemonic('S');
label.setLabelFor( comboBox );
byComponent = new JRadioButton("By Component", true);
byComponent.setMnemonic('C');
byComponent.addActionListener( this );
JRadioButton byValueType = new JRadioButton("By Value Type");
byValueType.setMnemonic('V');
byValueType.addActionListener( this );
ButtonGroup group = new ButtonGroup();
group.add(byComponent);
group.add(byValueType);
JPanel panel = new JPanel();
panel.setBorder( new EmptyBorder(15, 0, 15, 0) );
panel.add( label );
panel.add( comboBox );
panel.add( byComponent );
panel.add( byValueType );
return panel;
}
/*
* This panel is added to the Center of the content pane
*/
private JComponent buildCenterComponent()
{
DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);
table = new JTable(model);
table.setAutoCreateColumnsFromModel( false );
table.getColumnModel().getColumn(0).setPreferredWidth(250);
table.getColumnModel().getColumn(1).setPreferredWidth(500);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setCellRenderer( new SampleRenderer() );
Dimension d = table.getPreferredSize();
d.height = 350;
table.setPreferredScrollableViewportSize( d );
return new JScrollPane( table );
}
/*
* When the LAF is changed we need to reset the content pane
*/
public void resetComponents()
{
items.clear();
models.clear();
((DefaultTableModel)table.getModel()).setRowCount(0);
buildItemsMap();
Vector<String> comboBoxItems = new Vector<String>(50);
Iterator keys = items.keySet().iterator();
while (keys.hasNext())
{
Object key = keys.next();
comboBoxItems.add( (String)key );
}
comboBox.removeItemListener( this );
comboBox.setModel( new DefaultComboBoxModel( comboBoxItems ) );
comboBox.setSelectedIndex(-1);
comboBox.addItemListener( this );
comboBox.requestFocusInWindow();
if (selectedItem != null)
comboBox.setSelectedItem(selectedItem);
}
/*
* The item map will contain items for each component or
* items for each attribute type.
*/
private TreeMap buildItemsMap()
{
UIDefaults defaults = UIManager.getLookAndFeelDefaults();
// Build of Map of items and a Map of attributes for each item
for ( Enumeration enumm = defaults.keys(); enumm.hasMoreElements(); )
{
Object key = enumm.nextElement();
Object value = defaults.get( key );
String itemName = getItemName(key.toString(), value);
if (itemName == null) continue;
// Get the attribute map for this componenent, or
// create a map when one is not found
TreeMap<String, Object> attributeMap = items.get( itemName );
if (attributeMap == null)
{
attributeMap = new TreeMap<String, Object>();
items.put(itemName, attributeMap);
}
// Add the attribute to the map for this componenent
attributeMap.put(key.toString(), value );
}
return items;
}
/*
* Parse the key to determine the item name to use
*/
private String getItemName(String key, Object value)
{
// Seems like this is an old check required for JDK1.4.2
if (key.startsWith("class") || key.startsWith("javax"))
return null;
if (byComponent.isSelected())
return getComponentName(key, value);
else
return getValueName(key, value);
}
private String getComponentName(String key, Object value)
{
// The key is of the form:
// "componentName.componentProperty", or
// "componentNameUI", or
// "someOtherString"
String componentName;
int pos = componentNameEndOffset( key );
if (pos != -1)
{
componentName = key.substring( 0, pos );
}
else if (key.endsWith( "UI" ) )
{
componentName = key.substring( 0, key.length() - 2 );
}
else if (value instanceof ColorUIResource)
{
componentName = "System Colors";
}
else
{
componentName = "Miscellaneous";
}
// Fix inconsistency
if (componentName.equals("Checkbox"))
{
componentName = "CheckBox";
}
return componentName;
}
private int componentNameEndOffset(String key)
{
// Handle Nimbus properties first
// "ComboBox.scrollPane", "Table.editor" and "Tree.cellEditor"
// have different format even within the Nimbus properties.
// (the component name is specified in quotes)
if (key.startsWith("\""))
return key.indexOf("\"", 1) + 1;
int pos = key.indexOf( ":" );
if (pos != -1)
return pos;
pos = key.indexOf( "[" );
if (pos != -1)
return pos;
// Handle normal properties
return key.indexOf( "." );
}
private String getValueName(String key, Object value)
{
if (value instanceof Icon)
return "Icon";
else if (value instanceof Font)
return "Font";
else if (value instanceof Border)
return "Border";
else if (value instanceof Color)
return "Color";
else if (value instanceof Insets)
return "Insets";
else if (value instanceof Boolean)
return "Boolean";
else if (value instanceof Dimension)
return "Dimension";
else if (value instanceof Number)
return "Number";
else if (value instanceof Painter)
return "Painter";
else if (key.endsWith("UI"))
return "UI";
else if (key.endsWith("InputMap"))
return "InputMap";
else if (key.endsWith("RightToLeft"))
return "InputMap";
else if (key.endsWith("radient"))
return "Gradient";
else
{
return "The Rest";
}
}
/**
* Create menu bar
*/
private JMenuBar createMenuBar()
{
JMenuBar menuBar = new JMenuBar();
menuBar.add( createFileMenu() );
menuBar.add( createLAFMenu() );
return menuBar;
}
/**
* Create menu items for the Application menu
*/
private JMenu createFileMenu()
{
JMenu menu = new JMenu("Application");
menu.setMnemonic('A');
menu.addSeparator();
menu.add( new ExitAction() );
return menu;
}
/**
* Create menu items for the Look & Feel menu
*/
private JMenu createLAFMenu()
{
ButtonGroup bg = new ButtonGroup();
JMenu menu = new JMenu("Look & Feel");
menu.setMnemonic('L');
String lafId = UIManager.getLookAndFeel().getID();
UIManager.LookAndFeelInfo[] lafInfo = UIManager.getInstalledLookAndFeels();
for (int i = 0; i < lafInfo.length; i++)
{
String laf = lafInfo[i].getClassName();
String name= lafInfo[i].getName();
Action action = new ChangeLookAndFeelAction(this, laf, name);
JRadioButtonMenuItem mi = new JRadioButtonMenuItem( action );
menu.add( mi );
bg.add( mi );
if (name.equals(lafId))
{
mi.setSelected(true);
}
}
return menu;
}
/*
* Implement the ActionListener interface
*/
public void actionPerformed(ActionEvent e)
{
selectedItem = null;
resetComponents();
comboBox.requestFocusInWindow();
}
/*
* Implement the ItemListener interface
*/
public void itemStateChanged(ItemEvent e)
{
String itemName = (String)e.getItem();
changeTableModel( itemName );
updateRowHeights();
selectedItem = itemName;
}
/*
* Change the TabelModel in the table for the selected item
*/
private void changeTableModel(String itemName)
{
// The model has been created previously so just use it
DefaultTableModel model = models.get( itemName );
if (model != null)
{
table.setModel( model );
return;
}
// Create a new model for the requested item
// and add the attributes of the item to the model
model = new DefaultTableModel(COLUMN_NAMES, 0);
Map attributes = (Map)items.get( itemName );
Iterator ai = attributes.keySet().iterator();
while (ai.hasNext())
{
String attribute = (String)ai.next();
Object value = attributes.get(attribute);
Vector<Object> row = new Vector<Object>(3);
row.add(attribute);
if (value != null)
{
row.add( value.toString() );
if (value instanceof Icon)
value = new SafeIcon( (Icon)value );
row.add( value );
}
else
{
row.add( "null" );
row.add( "" );
}
model.addRow( row );
}
table.setModel( model );
models.put(itemName, model);
}
/*
* Some rows containing icons, may need to be sized taller to fully
* display the icon.
*/
private void updateRowHeights()
{
for (int row = 0; row < table.getRowCount(); row++)
{
int rowHeight = table.getRowHeight();
for (int column = 0; column < table.getColumnCount(); column++)
{
Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
}
table.setRowHeight(row, rowHeight);
}
}
/**
* Thanks to Jeanette for the use of this code found at:
*
* https://jdnc-incubator.dev.java.net/source/browse/jdnc-incubator/src/kleopatra/java/org/jdesktop/swingx/renderer/UIPropertiesViewer.java?rev=1.2&view=markup
*
* Some ui-icons misbehave in that they unconditionally class-cast to the
* component type they are mostly painted on. Consequently they blow up if
* we are trying to paint them anywhere else (f.i. in a renderer).
*
* This Icon is an adaption of a cool trick by Darryl Burke found at
* http://tips4java.wordpress.com/2008/12/18/icon-table-cell-renderer
*
* The base idea is to instantiate a component of the type expected by the icon,
* let it paint into the graphics of a bufferedImage and create an ImageIcon from it.
* In subsequent calls the ImageIcon is used.
*
*/
public static class SafeIcon implements Icon
{
private Icon wrappee;
private Icon standIn;
public SafeIcon(Icon wrappee)
{
this.wrappee = wrappee;
}
@Override
public int getIconHeight()
{
return wrappee.getIconHeight();
}
@Override
public int getIconWidth()
{
return wrappee.getIconWidth();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
if (standIn == this)
{
paintFallback(c, g, x, y);
}
else if (standIn != null)
{
standIn.paintIcon(c, g, x, y);
}
else
{
try
{
wrappee.paintIcon(c, g, x, y);
}
catch (ClassCastException e)
{
createStandIn(e, x, y);
standIn.paintIcon(c, g, x, y);
}
}
}
/**
* @param e
*/
private void createStandIn(ClassCastException e, int x, int y)
{
try
{
Class<?> clazz = getClass(e);
JComponent standInComponent = getSubstitute(clazz);
standIn = createImageIcon(standInComponent, x, y);
}
catch (Exception e1)
{
// something went wrong - fallback to this painting
standIn = this;
}
}
private Icon createImageIcon(JComponent standInComponent, int x, int y)
{
BufferedImage image = new BufferedImage(getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.createGraphics();
try
{
wrappee.paintIcon(standInComponent, g, 0, 0);
return new ImageIcon(image);
}
finally
{
g.dispose();
}
}
/**
* @param clazz
* @throws IllegalAccessException
*/
private JComponent getSubstitute(Class<?> clazz) throws IllegalAccessException
{
JComponent standInComponent;
try
{
standInComponent = (JComponent) clazz.newInstance();
}
catch (InstantiationException e)
{
standInComponent = new AbstractButton() {};
((AbstractButton) standInComponent).setModel(new DefaultButtonModel());
}
return standInComponent;
}
private Class<?> getClass(ClassCastException e) throws ClassNotFoundException
{
String className = e.getMessage();
className = className.substring(className.lastIndexOf(" ") + 1);
return Class.forName(className);
}
private void paintFallback(Component c, Graphics g, int x, int y)
{
g.drawRect(x, y, getIconWidth(), getIconHeight());
g.drawLine(x, y, x + getIconWidth(), y + getIconHeight());
g.drawLine(x + getIconWidth(), y, x, y + getIconHeight());
}
}
/*
* Render the value based on its class.
*/
class SampleRenderer extends JLabel implements TableCellRenderer
{
public SampleRenderer()
{
super();
setHorizontalAlignment( SwingConstants.CENTER );
setOpaque(true);
}
public Component getTableCellRendererComponent(
JTable table, Object sample, boolean isSelected, boolean hasFocus, int row, int column)
{
setBackground( null );
setBorder( null );
setIcon( null );
setText( "" );
if ( sample instanceof Color )
{
setBackground( (Color)sample );
}
else if ( sample instanceof Border )
{
setBorder( (Border)sample );
}
else if ( sample instanceof Font )
{
setText( "Sample" );
setFont( (Font)sample );
}
else if ( sample instanceof Icon )
{
setIcon( (Icon)sample );
}
return this;
}
/*
* Some icons are painted using inner classes and are not meant to be
* shared by other items. This code will catch the
* ClassCastException that is thrown.
*/
public void paint(Graphics g)
{
try
{
super.paint(g);
}
catch(Exception e)
{
// System.out.println(e);
// System.out.println(e.getStackTrace()[0]);
}
}
}
/*
* Change the LAF and recreate the UIManagerDefaults so that the properties
* of the new LAF are correctly displayed.
*/
class ChangeLookAndFeelAction extends AbstractAction
{
private UIManagerDefaults defaults;
private String laf;
protected ChangeLookAndFeelAction(UIManagerDefaults defaults, String laf, String name)
{
this.defaults = defaults;
this.laf = laf;
putValue(Action.NAME, name);
putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME));
}
public void actionPerformed(ActionEvent e)
{
try
{
UIManager.setLookAndFeel( laf );
defaults.resetComponents();
JMenuItem mi = (JMenuItem) e.getSource();
JPopupMenu popup = (JPopupMenu) mi.getParent();
JRootPane rootPane = SwingUtilities.getRootPane( popup.getInvoker() );
SwingUtilities.updateComponentTreeUI( rootPane );
// Use custom decorations when supported by the LAF
JFrame frame = (JFrame)SwingUtilities.windowForComponent(rootPane);
frame.dispose();
if (UIManager.getLookAndFeel().getSupportsWindowDecorations())
{
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
}
else
{
frame.setUndecorated(false);
}
frame.setVisible(true);
}
catch (Exception ex)
{
System.out.println("Failed loading L&F: " + laf);
System.out.println(ex);
}
}
}
/*
* Close the frame
*/
class ExitAction extends AbstractAction
{
public ExitAction()
{
putValue(Action.NAME, "Exit");
putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME));
putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_X));
}
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
/*
* Build a GUI using the content pane and menu bar of UIManagerDefaults
*/
private static void createAndShowGUI()
{
UIManagerDefaults application = new UIManagerDefaults();
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("UIManager Defaults");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar( application.getMenuBar() );
frame.getContentPane().add(application.getContentPane());
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
/*
* UIManagerDefaults Main. Called only if we're an application.
*/
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}