Browse Source

initial

master
Konstantin Bulenkov 12 years ago
commit
e1f447492c
  1. 1
      .idea/.name
  2. 13
      .idea/codeStyleSettings.xml
  3. 23
      .idea/compiler.xml
  4. 5
      .idea/copyright/profiles_settings.xml
  5. 5
      .idea/encodings.xml
  6. 10
      .idea/misc.xml
  7. 9
      .idea/modules.xml
  8. 5
      .idea/scopes/scope_settings.xml
  9. 125
      .idea/uiDesigner.xml
  10. 8
      .idea/vcs.xml
  11. 13
      Darcula.iml
  12. BIN
      lib/SwingSet2.jar
  13. 149
      src/com/bulenkov/darcula/DarculaDefaultTableHeaderRenderer.java
  14. 383
      src/com/bulenkov/darcula/DarculaLaf.java
  15. 36
      src/com/bulenkov/darcula/DarculaLookAndFeelInfo.java
  16. 25
      src/com/bulenkov/darcula/DarculaTableHeaderBorder.java
  17. 73
      src/com/bulenkov/darcula/DarculaTableHeaderUI.java
  18. 300
      src/com/bulenkov/darcula/DarculaUIUtil.java
  19. 90
      src/com/bulenkov/darcula/SystemInfo.java
  20. 360
      src/com/bulenkov/darcula/darcula.css
  21. 104
      src/com/bulenkov/darcula/darcula.properties
  22. 7
      src/com/bulenkov/darcula/darcula_linux.properties
  23. 3
      src/com/bulenkov/darcula/darcula_mac.properties
  24. 7
      src/com/bulenkov/darcula/darcula_windows.properties
  25. 69
      src/com/bulenkov/darcula/ui/DarculaButtonPainter.java
  26. 49
      src/com/bulenkov/darcula/ui/DarculaButtonUI.java
  27. 45
      src/com/bulenkov/darcula/ui/DarculaCheckBoxBorder.java
  28. 143
      src/com/bulenkov/darcula/ui/DarculaCheckBoxUI.java
  29. 208
      src/com/bulenkov/darcula/ui/DarculaComboBoxUI.java
  30. 42
      src/com/bulenkov/darcula/ui/DarculaEditorPaneUI.java
  31. 50
      src/com/bulenkov/darcula/ui/DarculaMenuBarBorder.java
  32. 12
      src/com/bulenkov/darcula/ui/DarculaMenuItemBorder.java
  33. 31
      src/com/bulenkov/darcula/ui/DarculaPanelUI.java
  34. 81
      src/com/bulenkov/darcula/ui/DarculaPasswordFieldUI.java
  35. 38
      src/com/bulenkov/darcula/ui/DarculaPopupMenuBorder.java
  36. 27
      src/com/bulenkov/darcula/ui/DarculaProgressBarBorder.java
  37. 187
      src/com/bulenkov/darcula/ui/DarculaProgressBarUI.java
  38. 134
      src/com/bulenkov/darcula/ui/DarculaRadioButtonUI.java
  39. 336
      src/com/bulenkov/darcula/ui/DarculaScrollBarUI.java
  40. 83
      src/com/bulenkov/darcula/ui/DarculaSpinnerBorder.java
  41. 200
      src/com/bulenkov/darcula/ui/DarculaSpinnerUI.java
  42. 30
      src/com/bulenkov/darcula/ui/DarculaTabbedPaneUI.java
  43. 58
      src/com/bulenkov/darcula/ui/DarculaTextBorder.java
  44. 81
      src/com/bulenkov/darcula/ui/DarculaTextFieldUI.java
  45. 169
      src/com/bulenkov/darcula/util/Animator.java
  46. 57
      src/com/bulenkov/darcula/util/ColorUtil.java
  47. 78
      src/com/bulenkov/darcula/util/EmptyIcon.java
  48. 31
      src/com/bulenkov/darcula/util/GraphicsConfig.java
  49. 46
      src/com/bulenkov/darcula/util/GraphicsUtil.java
  50. 589
      src/com/bulenkov/darcula/util/Gray.java
  51. 42
      src/com/bulenkov/darcula/util/StringUtil.java
  52. 39
      src/com/bulenkov/darcula/util/UIUtil.java
  53. 65
      swingset2/AquaTheme.java
  54. 342
      swingset2/BezierAnimationPanel.java
  55. 555
      swingset2/ButtonDemo.java
  56. 79
      swingset2/CharcoalTheme.java
  57. 419
      swingset2/CodeViewer.java
  58. 198
      swingset2/ColorChooserDemo.java
  59. 409
      swingset2/ComboBoxDemo.java
  60. 108
      swingset2/ContrastTheme.java
  61. 248
      swingset2/DemoModule.java
  62. 167
      swingset2/DirectionPanel.java
  63. 64
      swingset2/EmeraldTheme.java
  64. 273
      swingset2/ExampleFileFilter.java
  65. 200
      swingset2/ExampleFileView.java
  66. 421
      swingset2/FileChooserDemo.java
  67. 133
      swingset2/HtmlDemo.java
  68. 331
      swingset2/InternalFrameDemo.java
  69. 341
      swingset2/LayoutControlPanel.java
  70. 378
      swingset2/ListDemo.java
  71. 235
      swingset2/OptionPaneDemo.java
  72. 119
      swingset2/Permuter.java
  73. 199
      swingset2/ProgressBarDemo.java
  74. 64
      swingset2/RubyTheme.java
  75. 131
      swingset2/ScrollPaneDemo.java
  76. 293
      swingset2/SliderDemo.java
  77. 275
      swingset2/SplitPaneDemo.java
  78. 1347
      swingset2/SwingSet2.java
  79. 86
      swingset2/SwingSet2Applet.java
  80. 242
      swingset2/TabbedPaneDemo.java
  81. 610
      swingset2/TableDemo.java
  82. 168
      swingset2/ToolTipDemo.java
  83. 137
      swingset2/TreeDemo.java
  84. 121
      swingset2/resources/ant.html
  85. 128
      swingset2/resources/bug.html
  86. BIN
      swingset2/resources/images/About.jpg
  87. 7
      swingset2/resources/images/ImageClub/COPYRIGHT
  88. BIN
      swingset2/resources/images/ImageClub/food/apple.jpg
  89. BIN
      swingset2/resources/images/ImageClub/food/asparagus.jpg
  90. BIN
      swingset2/resources/images/ImageClub/food/banana.jpg
  91. BIN
      swingset2/resources/images/ImageClub/food/broccoli.jpg
  92. BIN
      swingset2/resources/images/ImageClub/food/cantaloupe.jpg
  93. BIN
      swingset2/resources/images/ImageClub/food/carrot.jpg
  94. BIN
      swingset2/resources/images/ImageClub/food/corn.jpg
  95. BIN
      swingset2/resources/images/ImageClub/food/grapefruit.jpg
  96. BIN
      swingset2/resources/images/ImageClub/food/grapes.jpg
  97. BIN
      swingset2/resources/images/ImageClub/food/kiwi.jpg
  98. BIN
      swingset2/resources/images/ImageClub/food/onion.jpg
  99. BIN
      swingset2/resources/images/ImageClub/food/peach.jpg
  100. BIN
      swingset2/resources/images/ImageClub/food/pear.jpg
  101. Some files were not shown because too many files have changed in this diff Show More

1
.idea/.name

@ -0,0 +1 @@
Darcula

13
.idea/codeStyleSettings.xml

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectCodeStyleSettingsManager">
<option name="PER_PROJECT_SETTINGS">
<value>
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
</value>
</option>
</component>
</project>

23
.idea/compiler.xml

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<option name="DEFAULT_COMPILER" value="Javac" />
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>

5
.idea/copyright/profiles_settings.xml

@ -0,0 +1,5 @@
<component name="CopyrightManager">
<settings default="">
<module2copyright />
</settings>
</component>

5
.idea/encodings.xml

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
</project>

10
.idea/misc.xml

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<entry_points version="2.0" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="IDEA jdk" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

9
.idea/modules.xml

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Darcula.iml" filepath="$PROJECT_DIR$/Darcula.iml" />
</modules>
</component>
</project>

5
.idea/scopes/scope_settings.xml

@ -0,0 +1,5 @@
<component name="DependencyValidationManager">
<state>
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</state>
</component>

125
.idea/uiDesigner.xml

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

8
.idea/vcs.xml

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

13
Darcula.iml

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/swingset2" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

BIN
lib/SwingSet2.jar

Binary file not shown.

149
src/com/bulenkov/darcula/DarculaDefaultTableHeaderRenderer.java

@ -0,0 +1,149 @@
package com.intellij.ide.ui.laf.darcula;
import javax.swing.*;
import javax.swing.plaf.UIResource;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaDefaultTableHeaderRenderer extends DefaultTableCellRenderer implements UIResource {
public DarculaDefaultTableHeaderRenderer() {
setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
//if (table == null) {
// setBorder(DefaultTableCellRenderer.noFocusBorder);
// setValue(value);
// setOpaque(false);
// return this;
//}
//
//if (table.getTableHeader() == null) {
// return super.getTableCellRendererComponent(table, value,
// isSelected, hasFocus, row, column);
//}
//
//JTableHeader tableHeader = table.getTableHeader();
//TableHeaderUI tableHeaderUI = tableHeader.getUI();
//if (UIUtil.isUnderDarcula() && (tableHeaderUI instanceof DarculaTableHeaderUI)) {
// DarculaTableHeaderUI ui = (DarculaTableHeaderUI) tableHeaderUI;
// StateTransitionTracker.ModelStateInfo modelStateInfo = ui
// .getModelStateInfo(column);
// ComponentState currState = ui.getColumnState(column);
//
// if (modelStateInfo != null) {
// Map<ComponentState, StateContributionInfo> activeStates = modelStateInfo
// .getStateContributionMap();
// SubstanceColorScheme colorScheme = getColorSchemeForState(
// tableHeader, currState);
// if (currState.isDisabled() || (activeStates == null)
// || (activeStates.size() == 1)) {
// super.setForeground(new ColorUIResource(colorScheme
// .getForegroundColor()));
// } else {
// float aggrRed = 0;
// float aggrGreen = 0;
// float aggrBlue = 0;
//
// for (Map.Entry<ComponentState, StateTransitionTracker.StateContributionInfo> activeEntry : modelStateInfo
// .getStateContributionMap().entrySet()) {
// ComponentState activeState = activeEntry.getKey();
// SubstanceColorScheme scheme = getColorSchemeForState(
// tableHeader, activeState);
// Color schemeFg = scheme.getForegroundColor();
// float contribution = activeEntry.getValue()
// .getContribution();
// aggrRed += schemeFg.getRed() * contribution;
// aggrGreen += schemeFg.getGreen() * contribution;
// aggrBlue += schemeFg.getBlue() * contribution;
// }
// super.setForeground(new ColorUIResource(new Color(
// (int) aggrRed, (int) aggrGreen, (int) aggrBlue)));
// }
// } else {
// SubstanceColorScheme scheme = getColorSchemeForState(
// tableHeader, currState);
// super.setForeground(new ColorUIResource(scheme
// .getForegroundColor()));
// }
//} else {
// super.setForeground(table.getForeground());
//}
//
//this.setBackground(tableHeader.getBackground());
//
//// fix for issue 319 - using font from the table header
//if (tableHeader.getFont() != null) {
// setFont(tableHeader.getFont());
//} else {
// setFont(table.getFont());
//}
//
//TableUI tableUI = table.getUI();
//if (SubstanceLookAndFeel.isCurrentLookAndFeel()
// && (tableUI instanceof SubstanceTableUI)) {
// this.setBorder(new EmptyBorder(((SubstanceTableUI) tableUI)
// .getCellRendererInsets()));
//}
//
//this.setValue(value);
//this.setOpaque(false);
//
//this.setEnabled(tableHeader.isEnabled() && table.isEnabled());
//
//// fix for defect 242 - not showing sort icon
//if (SubstanceLookAndFeel.isCurrentLookAndFeel()) {
// this.setIcon(null);
// RowSorter<? extends TableModel> rowSorter = table.getRowSorter();
// if (rowSorter != null) {
// setHorizontalTextPosition(JLabel.LEADING);
// java.util.List<? extends RowSorter.SortKey> sortKeys = rowSorter
// .getSortKeys();
// Icon sortIcon = null;
// SubstanceColorScheme scheme = null;
// if (tableHeaderUI instanceof SubstanceTableHeaderUI) {
// SubstanceTableHeaderUI ui = (SubstanceTableHeaderUI) tableHeaderUI;
// ComponentState state = ui.getColumnState(column);
// ColorSchemeAssociationKind colorSchemeAssociationKind = (state == ComponentState.ENABLED) ? ColorSchemeAssociationKind.MARK
// : ColorSchemeAssociationKind.HIGHLIGHT_MARK;
// scheme = SubstanceColorSchemeUtilities.getColorScheme(
// tableHeader, colorSchemeAssociationKind, state);
// } else {
// scheme = SubstanceColorSchemeUtilities.getColorScheme(
// tableHeader, ComponentState.ENABLED);
// }
//
// if (sortKeys.size() > 0
// && sortKeys.get(0).getColumn() == table
// .convertColumnIndexToModel(column)) {
// switch (sortKeys.get(0).getSortOrder()) {
// case ASCENDING:
// sortIcon = SubstanceImageCreator.getArrowIcon(
// SubstanceSizeUtils
// .getComponentFontSize(tableHeader),
// SwingConstants.NORTH, scheme);
// break;
// case DESCENDING:
// sortIcon = SubstanceImageCreator.getArrowIcon(
// SubstanceSizeUtils
// .getComponentFontSize(tableHeader),
// SwingConstants.SOUTH, scheme);
// break;
// case UNSORTED:
// sortIcon = null;
// }
// this.setIcon(sortIcon);
// }
// }
//}
return this;
}
}

383
src/com/bulenkov/darcula/DarculaLaf.java

@ -0,0 +1,383 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula;
import com.bulenkov.darcula.util.ColorUtil;
import com.bulenkov.darcula.util.StringUtil;
import sun.awt.AppContext;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.IconUIResource;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.basic.BasicLookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
/**
* @author Konstantin Bulenkov
*/
public final class DarculaLaf extends BasicLookAndFeel {
public static final String NAME = "Darcula";
BasicLookAndFeel base;
public DarculaLaf() {
try {
if (SystemInfo.isWindows || SystemInfo.isLinux) {
base = new MetalLookAndFeel();
} else {
final String name = UIManager.getSystemLookAndFeelClassName();
base = (BasicLookAndFeel)Class.forName(name).newInstance();
}
}
catch (Exception ignore) {
log(ignore);
}
}
private void callInit(String method, UIDefaults defaults) {
try {
final Method superMethod = BasicLookAndFeel.class.getDeclaredMethod(method, UIDefaults.class);
superMethod.setAccessible(true);
superMethod.invoke(base, defaults);
}
catch (Exception ignore) {
log(ignore);
}
}
@SuppressWarnings("UnusedParameters")
private static void log(Exception e) {
//everything is gonna be alright
//e.printStackTrace();
}
@Override
public UIDefaults getDefaults() {
try {
final Method superMethod = BasicLookAndFeel.class.getDeclaredMethod("getDefaults");
superMethod.setAccessible(true);
final UIDefaults metalDefaults =
(UIDefaults)superMethod.invoke(new MetalLookAndFeel());
final UIDefaults defaults = (UIDefaults)superMethod.invoke(base);
initInputMapDefaults(defaults);
initIdeaDefaults(defaults);
patchStyledEditorKit();
patchComboBox(metalDefaults, defaults);
defaults.remove("Spinner.arrowButtonBorder");
defaults.put("Spinner.arrowButtonSize", new Dimension(16, 5));
return defaults;
}
catch (Exception ignore) {
log(ignore);
}
return super.getDefaults();
}
private static void patchComboBox(UIDefaults metalDefaults, UIDefaults defaults) {
defaults.remove("ComboBox.ancestorInputMap");
defaults.remove("ComboBox.actionMap");
defaults.put("ComboBox.ancestorInputMap", metalDefaults.get("ComboBox.ancestorInputMap"));
defaults.put("ComboBox.actionMap", metalDefaults.get("ComboBox.actionMap"));
}
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static void patchStyledEditorKit() {
try {
StyleSheet defaultStyles = new StyleSheet();
InputStream is = DarculaLaf.class.getResourceAsStream("darcula.css");
Reader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
defaultStyles.loadRules(r, null);
r.close();
final Field keyField = HTMLEditorKit.class.getDeclaredField("DEFAULT_STYLES_KEY");
keyField.setAccessible(true);
final Object key = keyField.get(null);
AppContext.getAppContext().put(key, defaultStyles);
} catch (Exception e) {
log(e);
}
}
private void call(String method) {
try {
final Method superMethod = BasicLookAndFeel.class.getDeclaredMethod(method);
superMethod.setAccessible(true);
superMethod.invoke(base);
}
catch (Exception ignore) {
log(ignore);
}
}
public void initComponentDefaults(UIDefaults defaults) {
callInit("initComponentDefaults", defaults);
}
@SuppressWarnings({"HardCodedStringLiteral"})
static void initIdeaDefaults(UIDefaults defaults) {
loadDefaults(defaults);
defaults.put("Table.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] {
"ctrl C", "copy",
"ctrl V", "paste",
"ctrl X", "cut",
"COPY", "copy",
"PASTE", "paste",
"CUT", "cut",
"control INSERT", "copy",
"shift INSERT", "paste",
"shift DELETE", "cut",
"RIGHT", "selectNextColumn",
"KP_RIGHT", "selectNextColumn",
"LEFT", "selectPreviousColumn",
"KP_LEFT", "selectPreviousColumn",
"DOWN", "selectNextRow",
"KP_DOWN", "selectNextRow",
"UP", "selectPreviousRow",
"KP_UP", "selectPreviousRow",
"shift RIGHT", "selectNextColumnExtendSelection",
"shift KP_RIGHT", "selectNextColumnExtendSelection",
"shift LEFT", "selectPreviousColumnExtendSelection",
"shift KP_LEFT", "selectPreviousColumnExtendSelection",
"shift DOWN", "selectNextRowExtendSelection",
"shift KP_DOWN", "selectNextRowExtendSelection",
"shift UP", "selectPreviousRowExtendSelection",
"shift KP_UP", "selectPreviousRowExtendSelection",
"PAGE_UP", "scrollUpChangeSelection",
"PAGE_DOWN", "scrollDownChangeSelection",
"HOME", "selectFirstColumn",
"END", "selectLastColumn",
"shift PAGE_UP", "scrollUpExtendSelection",
"shift PAGE_DOWN", "scrollDownExtendSelection",
"shift HOME", "selectFirstColumnExtendSelection",
"shift END", "selectLastColumnExtendSelection",
"ctrl PAGE_UP", "scrollLeftChangeSelection",
"ctrl PAGE_DOWN", "scrollRightChangeSelection",
"ctrl HOME", "selectFirstRow",
"ctrl END", "selectLastRow",
"ctrl shift PAGE_UP", "scrollRightExtendSelection",
"ctrl shift PAGE_DOWN", "scrollLeftExtendSelection",
"ctrl shift HOME", "selectFirstRowExtendSelection",
"ctrl shift END", "selectLastRowExtendSelection",
"TAB", "selectNextColumnCell",
"shift TAB", "selectPreviousColumnCell",
//"ENTER", "selectNextRowCell",
"shift ENTER", "selectPreviousRowCell",
"ctrl A", "selectAll",
//"ESCAPE", "cancel",
"F2", "startEditing"
}));
}
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static void loadDefaults(UIDefaults defaults) {
final Properties properties = new Properties();
final String osSuffix = SystemInfo.isMac ? "mac" : SystemInfo.isWindows ? "windows" : "linux";
try {
InputStream stream = DarculaLaf.class.getResourceAsStream("darcula.properties");
properties.load(stream);
stream.close();
stream = DarculaLaf.class.getResourceAsStream("darcula_" + osSuffix + ".properties");
properties.load(stream);
stream.close();
HashMap<String, Object> darculaGlobalSettings = new HashMap<String, Object>();
final String prefix = "darcula.";
for (String key : properties.stringPropertyNames()) {
if (key.startsWith(prefix)) {
darculaGlobalSettings.put(key.substring(prefix.length()), parseValue(key, properties.getProperty(key)));
}
}
for (Object key : defaults.keySet()) {
if (key instanceof String && ((String)key).contains(".")) {
final String s = (String)key;
final String darculaKey = s.substring(s.lastIndexOf('.') + 1);
if (darculaGlobalSettings.containsKey(darculaKey)) {
defaults.put(key, darculaGlobalSettings.get(darculaKey));
}
}
}
for (String key : properties.stringPropertyNames()) {
final String value = properties.getProperty(key);
defaults.put(key, parseValue(key, value));
}
}
catch (IOException e) {log(e);}
}
private static Object parseValue(String key, String value) {
if (key.endsWith("Insets")) {
final List<String> numbers = StringUtil.split(value, ",");
return new InsetsUIResource(Integer.parseInt(numbers.get(0)),
Integer.parseInt(numbers.get(1)),
Integer.parseInt(numbers.get(2)),
Integer.parseInt(numbers.get(3)));
} else if (key.endsWith(".border")) {
try {
return Class.forName(value).newInstance();
} catch (Exception e) {log(e);}
} else {
final Color color = ColorUtil.fromHex(value, null);
final Integer invVal = getInteger(value);
final Boolean boolVal = "true".equals(value) ? Boolean.TRUE : "false".equals(value) ? Boolean.FALSE : null;
Icon icon = key.toLowerCase().endsWith("icon") ? null : null; //TODO: copy image loading
if (color != null) {
return new ColorUIResource(color);
} else if (invVal != null) {
return invVal;
} else if (icon != null) {
return new IconUIResource(icon);
} else if (boolVal != null) {
return boolVal;
}
}
return value;
}
private static Integer getInteger(String value) {
try {
return Integer.parseInt(value);
}
catch (NumberFormatException e) {
return null;
}
}
@Override
public String getName() {
return NAME;
}
@Override
public String getID() {
return getName();
}
@Override
public String getDescription() {
return "IntelliJ Dark Look and Feel";
}
@Override
public boolean isNativeLookAndFeel() {
return true;
}
@Override
public boolean isSupportedLookAndFeel() {
return true;
}
@Override
protected void initSystemColorDefaults(UIDefaults defaults) {
callInit("initSystemColorDefaults", defaults);
}
@Override
protected void initClassDefaults(UIDefaults defaults) {
callInit("initClassDefaults", defaults);
}
@Override
public void initialize() {
call("initialize");
}
@Override
public void uninitialize() {
call("uninitialize");
}
@Override
protected void loadSystemColors(UIDefaults defaults, String[] systemColors, boolean useNative) {
try {
final Method superMethod = BasicLookAndFeel.class.getDeclaredMethod("loadSystemColors",
UIDefaults.class,
String[].class,
boolean.class);
superMethod.setAccessible(true);
superMethod.invoke(base, defaults, systemColors, useNative);
}
catch (Exception ignore) {
log(ignore);
}
}
@Override
public boolean getSupportsWindowDecorations() {
return true;
}
@SuppressWarnings({"HardCodedStringLiteral"})
public static void initInputMapDefaults(UIDefaults defaults){
// Make ENTER work in JTrees
InputMap treeInputMap = (InputMap)defaults.get("Tree.focusInputMap");
if(treeInputMap!=null){ // it's really possible. For example, GTK+ doesn't have such map
treeInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"toggle");
}
// Cut/Copy/Paste in JTextAreas
InputMap textAreaInputMap=(InputMap)defaults.get("TextArea.focusInputMap");
if(textAreaInputMap!=null){ // It really can be null, for example when LAF isn't properly initialized (Alloy license problem)
installCutCopyPasteShortcuts(textAreaInputMap, false);
}
// Cut/Copy/Paste in JTextFields
InputMap textFieldInputMap=(InputMap)defaults.get("TextField.focusInputMap");
if(textFieldInputMap!=null){ // It really can be null, for example when LAF isn't properly initialized (Alloy license problem)
installCutCopyPasteShortcuts(textFieldInputMap, false);
}
// Cut/Copy/Paste in JPasswordField
InputMap passwordFieldInputMap=(InputMap)defaults.get("PasswordField.focusInputMap");
if(passwordFieldInputMap!=null){ // It really can be null, for example when LAF isn't properly initialized (Alloy license problem)
installCutCopyPasteShortcuts(passwordFieldInputMap, false);
}
// Cut/Copy/Paste in JTables
InputMap tableInputMap=(InputMap)defaults.get("Table.ancestorInputMap");
if(tableInputMap!=null){ // It really can be null, for example when LAF isn't properly initialized (Alloy license problem)
installCutCopyPasteShortcuts(tableInputMap, true);
}
}
private static void installCutCopyPasteShortcuts(InputMap inputMap, boolean useSimpleActionKeys) {
String copyActionKey = useSimpleActionKeys ? "copy" : DefaultEditorKit.copyAction;
String pasteActionKey = useSimpleActionKeys ? "paste" : DefaultEditorKit.pasteAction;
String cutActionKey = useSimpleActionKeys ? "cut" : DefaultEditorKit.cutAction;
// Ctrl+Ins, Shift+Ins, Shift+Del
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, InputEvent.CTRL_MASK | InputEvent.CTRL_DOWN_MASK), copyActionKey);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, InputEvent.SHIFT_MASK | InputEvent.SHIFT_DOWN_MASK), pasteActionKey);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.SHIFT_MASK | InputEvent.SHIFT_DOWN_MASK), cutActionKey);
// Ctrl+C, Ctrl+V, Ctrl+X
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK | InputEvent.CTRL_DOWN_MASK), copyActionKey);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK | InputEvent.CTRL_DOWN_MASK), pasteActionKey);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK | InputEvent.CTRL_DOWN_MASK), DefaultEditorKit.cutAction);
}
}

36
src/com/bulenkov/darcula/DarculaLookAndFeelInfo.java

@ -0,0 +1,36 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula;
import javax.swing.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaLookAndFeelInfo extends UIManager.LookAndFeelInfo {
public static final String CLASS_NAME = "idea.dark.laf.classname";
public DarculaLookAndFeelInfo(){
super("Darcula", CLASS_NAME);
}
public boolean equals(Object obj){
return (obj instanceof DarculaLookAndFeelInfo);
}
public int hashCode(){
return getName().hashCode();
}
}

25
src/com/bulenkov/darcula/DarculaTableHeaderBorder.java

@ -0,0 +1,25 @@
package com.bulenkov.darcula;
import javax.swing.border.Border;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTableHeaderBorder implements Border, UIResource {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(0, 0, 0, 0);
}
@Override
public boolean isBorderOpaque() {
return false;
}
}

73
src/com/bulenkov/darcula/DarculaTableHeaderUI.java

@ -0,0 +1,73 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula;
import com.bulenkov.darcula.util.ColorUtil;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.Gray;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.util.Enumeration;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTableHeaderUI extends BasicTableHeaderUI {
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new DarculaTableHeaderUI();
}
@Override
public void paint(Graphics g2, JComponent c) {
final Graphics2D g = (Graphics2D)g2;
final GraphicsConfig config = new GraphicsConfig(g);
final Color bg = c.getBackground();
g.setPaint(new GradientPaint(0, 0, ColorUtil.shift(bg, 1.4), 0, c.getHeight(), ColorUtil.shift(bg, 0.9)));
final int h = c.getHeight();
final int w = c.getWidth();
g.fillRect(0,0, w, h);
g.setPaint(ColorUtil.shift(bg, 0.75));
g.drawLine(0, h-1, w, h-1);
g.drawLine(w-1, 0, w-1, h-1);
final Enumeration<TableColumn> columns = ((JTableHeader)c).getColumnModel().getColumns();
final Color lineColor = ColorUtil.shift(bg, 0.7);
final Color shadow = Gray._255.withAlpha(30);
int offset = 0;
while (columns.hasMoreElements()) {
final TableColumn column = columns.nextElement();
if (columns.hasMoreElements() && column.getWidth() > 0) {
offset += column.getWidth();
g.setColor(lineColor);
g.drawLine(offset-1, 1, offset-1, h-3);
g.setColor(shadow);
g.drawLine(offset, 1, offset, h-3);
}
}
config.restore();
super.paint(g, c);
}
}

300
src/com/bulenkov/darcula/DarculaUIUtil.java

@ -0,0 +1,300 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula;
import com.bulenkov.darcula.util.ColorUtil;
import com.bulenkov.darcula.util.Gray;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.geom.GeneralPath;
/**
* @author Konstantin Bulenkov
*/
public class DarculaUIUtil {
public static final Color GLOW_COLOR = new Color(96, 175, 255);
public static void paintFocusRing(Graphics g, int x, int y, int width, int height) {
paintFocusRing((Graphics2D)g, GLOW_COLOR, new Rectangle(x, y, width, height));
}
public static void paintFocusOval(Graphics g, int x, int y, int width, int height) {
paintFocusRing((Graphics2D)g, GLOW_COLOR, new Rectangle(x, y, width, height), true);
}
public static final boolean USE_QUARTZ = "true".equals(System.getProperty("apple.awt.graphics.UseQuartz"));
public static final String MAC_FILL_BORDER = "MAC_FILL_BORDER";
public static final int MAC_COMBO_BORDER_V_OFFSET = SystemInfo.isMacOSLion ? 1 : 0;
private static Cursor INVERTED_TEXT_CURSOR;
public static void paintFocusRing(Graphics2D g2d, Color ringColor, Rectangle bounds) {
paintFocusRing(g2d, ringColor, bounds, false);
}
public static void paintFocusRing(Graphics2D g, Color ringColor, Rectangle bounds, boolean oval) {
int correction = 50;
final Color[] colors = new Color[]{
ColorUtil.toAlpha(ringColor, 180 - correction),
ColorUtil.toAlpha(ringColor, 120 - correction),
ColorUtil.toAlpha(ringColor, 70 - correction),
ColorUtil.toAlpha(ringColor, 100 - correction),
ColorUtil.toAlpha(ringColor, 50 - correction)
};
final Object oldAntialiasingValue = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
final Object oldStrokeControlValue = g.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, !oval &&
USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE);
final Rectangle r = new Rectangle(bounds.x - 3, bounds.y - 3, bounds.width + 6, bounds.height + 6);
g.setColor(colors[0]);
drawRectOrOval(g, oval, 5, r.x + 2, r.y + 2, r.width - 5, r.height - 5);
g.setColor(colors[1]);
drawRectOrOval(g, oval, 7, r.x + 1, r.y + 1, r.width - 3, r.height - 3);
g.setColor(colors[2]);
drawRectOrOval(g, oval, 9, r.x, r.y, r.width - 1, r.height - 1);
g.setColor(colors[3]);
drawRectOrOval(g, oval, 0, r.x + 3, r.y + 3, r.width - 7, r.height - 7);
g.setColor(colors[4]);
drawRectOrOval(g, oval, 0, r.x + 4, r.y + 4, r.width - 9, r.height - 9);
// restore rendering hints
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasingValue);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, oldStrokeControlValue);
}
private static void drawRectOrOval(Graphics2D g, boolean oval, int arc, int x, int y, int width, int height) {
if (oval) {
g.drawOval(x, y, width, height);
} else {
if (arc == 0) {
g.drawRect(x, y, width, height);
} else {
g.drawRoundRect(x, y, width, height, arc, arc);
}
}
}
public static void drawToolbarDecoratorBackground(Graphics g2, int width, int height) {
final Graphics2D g = (Graphics2D)g2;
final int h1 = height / 2;
g.setPaint(new GradientPaint(0,0, Gray._247, 0, h1, Gray._240));
g.fillRect(0, 0, width, h1);
g.setPaint(new GradientPaint(0,h1, Gray._229, 0, height, Gray._234));
g.fillRect(0, h1, width, height);
}
public static class EditorTextFieldBorder implements Border {
private JComponent myEnabledComponent;
public EditorTextFieldBorder(final JComponent enabledComponent) {
myEnabledComponent = enabledComponent;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
final int x1 = x + 3;
final int y1 = y + 3;
final int width1 = width - 8;
final int height1 = height - 6;
if (c.isOpaque() || (c instanceof JComponent && ((JComponent)c).getClientProperty(MAC_FILL_BORDER) == Boolean.TRUE)) {
g.setColor(UIManager.getColor("Panel.background"));
g.fillRect(x, y, width, height);
}
g.setColor(c.getBackground());
g.fillRect(x1, y1, width1, height1);
if (!myEnabledComponent.isEnabled()) {
((Graphics2D)g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
}
g.setColor(new Color(100, 100, 100, 200));
g.drawLine(x1, y1, x1 + width1 - 1, y1);
g.setColor(new Color(212, 212, 212, 200));
g.drawLine(x1, y1 + 1, x1 + width1 - 1, y1 + 1);
g.setColor(Gray._225);
g.drawLine(x1 + 1, y1 + height1 - 1, x1 + width1 - 2, y1 + height1 - 1);
g.setColor(new Color(30, 30, 30, 70));
g.drawLine(x1, y1, x1, y1 + height1 - 1);
g.drawLine(x1 + width1 - 1, y1, x1 + width1 - 1, y1 + height1 - 1);
g.setColor(new Color(30, 30, 30, 10));
g.drawLine(x1 + 1, y1, x1 + 1, y1 + height1 - 1);
g.drawLine(x1 + width1 - 2, y1, x1 + width1 - 2, y1 + height1 - 1);
if (myEnabledComponent.isEnabled() && myEnabledComponent.isVisible() && hasFocus(myEnabledComponent)) {
paintTextFieldFocusRing((Graphics2D) g, new Rectangle(x1, y1, width1, height1));
}
}
private static boolean hasFocus(final Component toCheck) {
if (toCheck.hasFocus()) return true;
if (toCheck instanceof JComponent) {
final JComponent c = (JComponent)toCheck;
for (int i = 0; i < c.getComponentCount(); i++) {
final boolean b = hasFocus(c.getComponent(i));
if (b) return true;
}
}
return false;
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(6, 7, 6, 7);
}
@Override
public boolean isBorderOpaque() {
return true;
}
}
public static Color getFocusRingColor() {
final Object o = UIManager.get("Focus.color");
if (o instanceof Color) {
return (Color)o;
}
return new Color(64, 113, 167);
}
public static void paintTextFieldFocusRing(final Graphics2D g2d, final Rectangle bounds) {
paintFocusRing(g2d, getFocusRingColor(), bounds);
}
public static void paintComboboxFocusRing(final Graphics2D g2d, final Rectangle bounds) {
final Color color = getFocusRingColor();
final Color[] colors = new Color[]{
ColorUtil.toAlpha(color, 180),
ColorUtil.toAlpha(color, 130),
ColorUtil.toAlpha(color, 80),
ColorUtil.toAlpha(color, 80)
};
final Object oldAntialiasingValue = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
final Object oldStrokeControlValue = g2d.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE);
int _y = MAC_COMBO_BORDER_V_OFFSET;
final GeneralPath path1 = new GeneralPath();
path1.moveTo(2, _y + 4);
path1.quadTo(2, +_y + 2, 4, _y + 2);
path1.lineTo(bounds.width - 7, _y + 2);
path1.quadTo(bounds.width - 5, _y + 3, bounds.width - 4, _y + 5);
path1.lineTo(bounds.width - 4, bounds.height - 7 + _y);
path1.quadTo(bounds.width - 5, bounds.height - 5 + _y, bounds.width - 7, bounds.height - 4 + _y);
path1.lineTo(4, bounds.height - 4 + _y);
path1.quadTo(2, bounds.height - 4 + _y, 2, bounds.height - 6 + _y);
path1.closePath();
g2d.setColor(colors[0]);
g2d.draw(path1);
final GeneralPath path2 = new GeneralPath();
path2.moveTo(1, 5 + _y);
path2.quadTo(1, 1 + _y, 5, 1 + _y);
path2.lineTo(bounds.width - 8, 1 + _y);
path2.quadTo(bounds.width - 4, 2 + _y, bounds.width - 3, 6 + _y);
path2.lineTo(bounds.width - 3, bounds.height - 7 + _y);
path2.quadTo(bounds.width - 4, bounds.height - 4 + _y, bounds.width - 8, bounds.height - 3 + _y);
path2.lineTo(4, bounds.height - 3 + _y);
path2.quadTo(1, bounds.height - 3 + _y, 1, bounds.height - 6 + _y);
path2.closePath();
g2d.setColor(colors[1]);
g2d.draw(path2);
final GeneralPath path3 = new GeneralPath();
path3.moveTo(0, 4 + _y);
path3.quadTo(0, _y, 7, _y);
path3.lineTo(bounds.width - 9, _y);
path3.quadTo(bounds.width - 2, 1 + _y, bounds.width - 2, 7 + _y);
path3.lineTo(bounds.width - 2, bounds.height - 8 + _y);
path3.quadTo(bounds.width - 3, bounds.height - 1 + _y, bounds.width - 12, bounds.height - 2 + _y);
path3.lineTo(7, bounds.height - 2 + _y);
path3.quadTo(0, bounds.height - 1 + _y, 0, bounds.height - 7 + _y);
path3.closePath();
g2d.setColor(colors[2]);
g2d.draw(path3);
// restore rendering hints
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasingValue);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, oldStrokeControlValue);
}
// public static void drawComboboxFocusRing(final JComboBox combobox, final Graphics g) {
// if (SystemInfo.isMac && combobox.isEnabled() && combobox.isEditable() && UIUtil.isUnderAquaLookAndFeel()) {
// final Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
// if (focusOwner != null) {
// final Container ancestor = SwingUtilities.getAncestorOfClass(JComboBox.class, focusOwner);
// if (ancestor == combobox) {
// paintComboboxFocusRing((Graphics2D)g, combobox.getBounds());
// }
// }
// }
// }
// public static void doNotFillBackground(final JTree tree, final DefaultTreeCellRenderer renderer) {
// TreeUI ui = tree.getUI();
// if (ui instanceof WideSelectionTreeUI) {
// if (((WideSelectionTreeUI)ui).isWideSelection()) {
// renderer.setOpaque(false);
// try {
// final Field fillBackground = DefaultTreeCellRenderer.class.getDeclaredField("fillBackground");
// fillBackground.setAccessible(true);
// fillBackground.set(renderer, false);
// }
// catch (Exception e) {
// // nothing
// }
// }
// }
// }
// public static Cursor getInvertedTextCursor() {
// if (INVERTED_TEXT_CURSOR == null) {
// final Toolkit toolkit = Toolkit.getDefaultToolkit();
// Image cursorImage = toolkit.createImage(MacUIUtil.class.getClassLoader().getResource("/mac/text.gif"));
// INVERTED_TEXT_CURSOR = toolkit.createCustomCursor(cursorImage, new Point(15, 13), "InvertedTextCursor");
// }
// return INVERTED_TEXT_CURSOR;
// }
}

90
src/com/bulenkov/darcula/SystemInfo.java

@ -0,0 +1,90 @@
package com.bulenkov.darcula;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings({"HardCodedStringLiteral", "UtilityClassWithoutPrivateConstructor", "UnusedDeclaration"})
public class SystemInfo {
public static final String OS_NAME = System.getProperty("os.name");
public static final String OS_VERSION = System.getProperty("os.version").toLowerCase();
protected static final String _OS_NAME = OS_NAME.toLowerCase();
public static final boolean isWindows = _OS_NAME.startsWith("windows");
public static final boolean isOS2 = _OS_NAME.startsWith("os/2") || _OS_NAME.startsWith("os2");
public static final boolean isMac = _OS_NAME.startsWith("mac");
public static final boolean isLinux = _OS_NAME.startsWith("linux");
public static final boolean isUnix = !isWindows && !isOS2;
public static final boolean isFileSystemCaseSensitive = isUnix && !isMac;
public static final boolean isMacOSLion = isLion();
public static boolean isOsVersionAtLeast(String version) {
return compareVersionNumbers(OS_VERSION, version) >= 0;
}
private static boolean isTiger() {
return isMac &&
!OS_VERSION.startsWith("10.0") &&
!OS_VERSION.startsWith("10.1") &&
!OS_VERSION.startsWith("10.2") &&
!OS_VERSION.startsWith("10.3");
}
private static boolean isLeopard() {
return isMac && isTiger() && !OS_VERSION.startsWith("10.4");
}
private static boolean isSnowLeopard() {
return isMac && isLeopard() && !OS_VERSION.startsWith("10.5");
}
private static boolean isLion() {
return isMac && isSnowLeopard() && !OS_VERSION.startsWith("10.6");
}
private static boolean isMountainLion() {
return isMac && isLion() && !OS_VERSION.startsWith("10.7");
}
public static int compareVersionNumbers(String v1, String v2) {
if (v1 == null && v2 == null) {
return 0;
}
if (v1 == null) {
return -1;
}
if (v2 == null) {
return 1;
}
String[] part1 = v1.split("[\\.\\_\\-]");
String[] part2 = v2.split("[\\.\\_\\-]");
int idx = 0;
for (; idx < part1.length && idx < part2.length; idx++) {
String p1 = part1[idx];
String p2 = part2[idx];
int cmp;
if (p1.matches("\\d+") && p2.matches("\\d+")) {
cmp = new Integer(p1).compareTo(new Integer(p2));
}
else {
cmp = part1[idx].compareTo(part2[idx]);
}
if (cmp != 0) return cmp;
}
if (part1.length == part2.length) {
return 0;
}
else if (part1.length > idx) {
return 1;
}
else {
return -1;
}
}
}

360
src/com/bulenkov/darcula/darcula.css

@ -0,0 +1,360 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
body {
font-size: 14pt;
font-family: Serif;
font-weight: normal;
margin-left: 0;
margin-right: 0;
color: #bbbbbb
}
p {
margin-top: 15
}
h1 {
font-size: x-large;
font-weight: bold;
margin-top: 10;
margin-bottom: 10
}
h2 {
font-size: large;
font-weight: bold;
margin-top: 10;
margin-bottom: 10
}
h3 {
font-size: medium;
font-weight: bold;
margin-top: 10;
margin-bottom: 10
}
h4 {
font-size: small;
font-weight: bold;
margin-top: 10;
margin-bottom: 10
}
h5 {
font-size: x-small;
font-weight: bold;
margin-top: 10;
margin-bottom: 10
}
h6 {
font-size: xx-small;
font-weight: bold;
margin-top: 10;
margin-bottom: 10
}
li p {
margin-top: 0;
margin-bottom: 0
}
td p {
margin-top: 0
}
menu li p {
margin-top: 0;
margin-bottom: 0
}
menu li {
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0
}
menu {
margin-left-ltr: 40;
margin-right-rtl: 40;
margin-top: 10;
margin-bottom: 10
}
dir li p {
margin-top: 0;
margin-bottom: 0
}
dir li {
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0
}
dir {
margin-left-ltr: 40;
margin-right-rtl: 40;
margin-top: 10;
margin-bottom: 10
}
dd {
margin-left-ltr: 40;
margin-right-rtl: 40;
margin-top: 0;
margin-bottom: 0
}
dd p {
margin-left: 0;
margin-rigth: 0;
margin-top: 0;
margin-bottom: 0
}
dt {
margin-top: 0;
margin-bottom: 0
}
dl {
margin-left: 0;
margin-top: 10;
margin-bottom: 10
}
ol li {
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0
}
ol {
margin-top: 10;
margin-bottom: 10;
margin-left-ltr: 50;
margin-right-rtl: 50;
list-style-type: decimal
}
ol li p {
margin-top: 0;
margin-bottom: 0
}
ul li {
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0
}
ul {
margin-top: 10;
margin-bottom: 10;
margin-left-ltr: 50;
margin-right-rtl: 50;
list-style-type: disc;
-bullet-gap: 10
}
ul li ul li {
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0
}
ul li ul {
list-style-type: circle;
margin-left-ltr: 25;
margin-right-rtl: 25;
}
ul li ul li ul li {
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0
}
ul li ul li ul {
list-style-type: square;
margin-left-ltr: 25;
margin-right-rtl: 25
}
ul li menu {
list-style-type: circle;
margin-left-ltr: 25;
margin-right-rtl: 25;
}
ul li p {
margin-top: 0;
margin-bottom: 0
}
a {
color: #589df6;
text-decoration: underline
}
address {
color: #589df6;
font-style: italic
}
big {
font-size: x-large
}
small {
font-size: x-small
}
samp {
font-size: small;
font-family: Monospaced
}
cite {
font-style: italic
}
code {
font-size: small;
font-family: Monospaced
}
dfn {
font-style: italic
}
em {
font-style: italic
}
i {
font-style: italic
}
b {
font-weight: bold
}
kbd {
font-size: small;
font-family: Monospaced
}
s {
text-decoration: line-through
}
strike {
text-decoration: line-through
}
strong {
font-weight: bold
}
sub {
vertical-align: sub
}
sup {
vertical-align: sup
}
tt {
font-family: Monospaced
}
u {
text-decoration: underline
}
var {
font-weight: bold;
font-style: italic
}
table {
border-color: Gray;
border-style: outset
}
tr {
text-align: left
}
td {
border-color: Gray;
border-style: inset;
padding-left: 3;
padding-right: 3;
padding-top: 3;
padding-bottom: 3
}
th {
text-align: center;
font-weight: bold;
border-color: Gray;
border-style: inset;
padding-left: 3;
padding-right: 3;
padding-top: 3;
padding-bottom: 3
}
blockquote {
margin-top: 5;
margin-bottom: 5;
margin-left: 35;
margin-right: 35
}
center {
text-align: center
}
pre {
margin-top: 5;
margin-bottom: 5;
font-family: Monospaced
}
pre p {
margin-top: 0
}
caption {
caption-side: top;
text-align: center
}
nobr {
white-space: nowrap
}

104
src/com/bulenkov/darcula/darcula.properties

@ -0,0 +1,104 @@
# suppress inspection "UnusedProperty" for whole file
darcula.background=3c3f41
darcula.textBackground=3c3f41
darcula.foreground=bbbbbb
darcula.textForeground=bbbbbb
darcula.caretForeground=bbbbbb
darcula.inactiveBackground=3C3F41
window=3c3f41
info=3c3f41
controlLtHighlight=3c3f41
text=bbbbbb
textText=bbbbbb
infoText=bbbbbb
activeCaption=3c3f41
OptionPane.messageForeground=bbbbbb
TitledBorder.titleColor=bbbbbb
Menu.maxGutterIconWidth=18
MenuItem.maxGutterIconWidth=18
MenuItem.acceleratorDelimiter=-
MenuItem.border=com.bulenkov.darcula.ui.DarculaMenuItemBorder
Menu.border=com.bulenkov.darcula.ui.DarculaMenuItemBorder
EditorPane.inactiveBackground=45494A
EditorPane.inactiveForeground=bbbbbb
EditorPaneUI=com.bulenkov.darcula.ui.DarculaEditorPaneUI
control=3c3f41
link.foreground=589df6
ScrollBarUI=com.bulenkov.darcula.ui.DarculaScrollBarUI
TableHeaderUI=com.bulenkov.darcula.DarculaTableHeaderUI
Table.gridColor=2c2c2c
Table.ascendingSortIcon=AllIcons.General.SplitUp
Table.descendingSortIcon=AllIcons.General.SplitDown
#just to suppress border painters
TableHeader.cellBorder=com.bulenkov.darcula.DarculaTableHeaderBorder
MenuBar.disabledBackground=3c3f41
MenuBar.shadow=3c3f41
TabbedPaneUI=com.bulenkov.darcula.ui.DarculaTabbedPaneUI
TabbedPane.tabInsets=0,4,0,4
TabbedPane.highlight=292b2d
TabbedPane.light=444444
TabbedPane.selected=626262
TabbedPane.selectHighlight=3c3f41
TabbedPane.contentBorderInsets=3,1,1,1
TabbedPane.darkShadow=292b2d
TabbedPane.shadow=3c3f41
Separator.foreground=2d2d2d
Focus.color=ff0000
TextField.background=45494A
TextFieldUI=com.bulenkov.darcula.ui.DarculaTextFieldUI
TextField.border=com.bulenkov.darcula.ui.DarculaTextBorder
PasswordField.background=45494A
PasswordFieldUI=com.bulenkov.darcula.ui.DarculaPasswordFieldUI
PasswordField.border=com.bulenkov.darcula.ui.DarculaTextBorder
ProgressBarUI=com.bulenkov.darcula.ui.DarculaProgressBarUI
ProgressBar.border=com.bulenkov.darcula.ui.DarculaProgressBarBorder
ProgressBar.foreground=808080
FormattedTextField.background=45494A
TextArea.background=45494A
CheckBoxUI=com.bulenkov.darcula.ui.DarculaCheckBoxUI
CheckBox.border=com.bulenkov.darcula.ui.DarculaCheckBoxBorder
ComboBoxUI=com.bulenkov.darcula.ui.DarculaComboBoxUI
ComboBox.disabledBackground=3c3f41
ComboBox.squareButton=false
RadioButtonUI=com.bulenkov.darcula.ui.DarculaRadioButtonUI
StatusBar.topColor=2c2c2c
StatusBar.top2Color=2c2c2c
StatusBar.bottomColor=2c2c2c
Button.border=com.bulenkov.darcula.ui.DarculaButtonPainter
ButtonUI=com.bulenkov.darcula.ui.DarculaButtonUI
MenuItem.acceleratorForeground=eeeeee
PopupMenu.translucentBackground=3c3f41
ToolTip.background=5C5C42
SpinnerUI=com.bulenkov.darcula.ui.DarculaSpinnerUI
Spinner.border=com.bulenkov.darcula.ui.DarculaSpinnerBorder
Spinner.background=3c3f41
Spinner.arrowButtonInsets=1,1,1,1
Spinner.editorBorderPainted=false
Hyperlink.linkColor=589df6
Tree.collapsedIcon=AllIcons.Mac.Tree_white_right_arrow
Tree.expandedIcon=AllIcons.Mac.Tree_white_down_arrow

7
src/com/bulenkov/darcula/darcula_linux.properties

@ -0,0 +1,7 @@
# suppress inspection "UnusedProperty" for whole file
darcula.selectionBackground=2F65CA
darcula.selectionForeground=bbbbbb
PopupMenu.border=com.bulenkov.darcula.ui.DarculaPopupMenuBorder
MenuBar.border=com.bulenkov.darcula.ui.DarculaMenuBarBorder

3
src/com/bulenkov/darcula/darcula_mac.properties

@ -0,0 +1,3 @@
# suppress inspection "UnusedProperty" for whole file
darcula.selectionBackground=2F65CA
#Menu.arrowIcon=AllIcons.Mac.Tree_white_right_arrow

7
src/com/bulenkov/darcula/darcula_windows.properties

@ -0,0 +1,7 @@
# suppress inspection "UnusedProperty" for whole file
darcula.selectionBackground=4B6EAF
darcula.selectionForeground=bbbbbb
PopupMenu.border=com.bulenkov.darcula.ui.DarculaPopupMenuBorder
MenuBar.border=com.bulenkov.darcula.ui.DarculaMenuBarBorder

69
src/com/bulenkov/darcula/ui/DarculaButtonPainter.java

@ -0,0 +1,69 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.Gray;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaButtonPainter implements Border, UIResource {
private static final int myOffset = 4;
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
final Graphics2D g2d = (Graphics2D)g;
final Insets ins = getBorderInsets(c);
final int yOff = (ins.top + ins.bottom) / 4;
int offset = getOffset();
if (c.hasFocus()) {
DarculaUIUtil.paintFocusRing(g2d, offset, yOff, width - 2 * offset, height - 2 * yOff);
} else {
final GraphicsConfig config = new GraphicsConfig(g);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
g2d.setPaint(
new GradientPaint(width / 2, y + yOff + 1, Gray._80.withAlpha(90), width / 2, height - 2 * yOff, Gray._90.withAlpha(90)));
//g.drawRoundRect(x + offset + 1, y + yOff + 1, width - 2 * offset, height - 2*yOff, 5, 5);
((Graphics2D)g).setPaint(Gray._100.withAlpha(180));
g.drawRoundRect(x + offset, y + yOff, width - 2 * offset, height - 2*yOff, 5, 5);
config.restore();
}
}
@Override
public Insets getBorderInsets(Component c) {
return new InsetsUIResource(6, 12, 6, 12);
}
protected int getOffset() {
return myOffset;
}
@Override
public boolean isBorderOpaque() {
return false;
}
}

49
src/com/bulenkov/darcula/ui/DarculaButtonUI.java

@ -0,0 +1,49 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaButtonUI extends BasicButtonUI {
@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
public static ComponentUI createUI(JComponent c) {
return new DarculaButtonUI();
}
@Override
public void paint(Graphics g, JComponent c) {
final Border border = c.getBorder();
if (c.isEnabled() && border != null) {
final Insets ins = border.getBorderInsets(c);
final int yOff = (ins.top + ins.bottom) / 4;
if (((JButton)c).isDefaultButton()) {
((Graphics2D)g).setPaint(new GradientPaint(0, 0, new Color(0x384F6B), 0, c.getHeight(), new Color(0x233143)));
}
else {
((Graphics2D)g).setPaint(new GradientPaint(0, 0, new Color(85, 90, 92), 0, c.getHeight(), new Color(65, 70, 72)));
}
g.fillRoundRect(4, yOff, c.getWidth() - 2 * 4, c.getHeight() - 2 * yOff, 5, 5);
}
super.paint(g, c);
}
}

45
src/com/bulenkov/darcula/ui/DarculaCheckBoxBorder.java

@ -0,0 +1,45 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.SystemInfo;
import com.bulenkov.darcula.util.UIUtil;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaCheckBoxBorder implements Border, UIResource {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
}
@Override
public Insets getBorderInsets(Component c) {
final int a = SystemInfo.isMac || UIUtil.getParentOfType(CellRendererPane.class, c) != null ? 0 : 2;
return new InsetsUIResource(a, a, a, a);
}
@Override
public boolean isBorderOpaque() {
return false;
}
}

143
src/com/bulenkov/darcula/ui/DarculaCheckBoxUI.java

@ -0,0 +1,143 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.darcula.util.EmptyIcon;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.Gray;
import com.bulenkov.darcula.util.UIUtil;
import sun.swing.SwingUtilities2;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.IconUIResource;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.plaf.metal.MetalCheckBoxUI;
import javax.swing.text.View;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaCheckBoxUI extends MetalCheckBoxUI {
@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
public static ComponentUI createUI(JComponent c) {
if (UIUtil.getParentOfType(CellRendererPane.class, c) != null) {
c.setBorder(null);
}
return new DarculaCheckBoxUI();
}
@Override
public synchronized void paint(Graphics g2d, JComponent c) {
Graphics2D g = (Graphics2D)g2d;
JCheckBox b = (JCheckBox) c;
final ButtonModel model = b.getModel();
final Dimension size = c.getSize();
final Font font = c.getFont();
g.setFont(font);
FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, font);
Rectangle viewRect = new Rectangle(size);
Rectangle iconRect = new Rectangle();
Rectangle textRect = new Rectangle();
Insets i = c.getInsets();
viewRect.x += i.left;
viewRect.y += i.top;
viewRect.width -= (i.right + viewRect.x);
viewRect.height -= (i.bottom + viewRect.y);
String text = SwingUtilities.layoutCompoundLabel(c, fm, b.getText(), getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect, b.getIconTextGap());
//background
if(c.isOpaque()) {
g.setColor(b.getBackground());
g.fillRect(0,0, size.width, size.height);
}
final int x = iconRect.x + 3;
final int y = iconRect.y + 3;
final int w = iconRect.width - 6;
final int h = iconRect.height - 6;
g.translate(x, y);
final Paint paint = new GradientPaint(w / 2, 0, b.getBackground().brighter(),
w / 2, h, b.getBackground());
g.setPaint(paint);
g.fillRect(1, 1, w - 2, h - 2);
//setup AA for lines
final GraphicsConfig config = new GraphicsConfig(g);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
final boolean armed = b.getModel().isArmed();
if (c.hasFocus()) {
g.setPaint(new GradientPaint(w/2, 1, armed ? Gray._100: Gray._120, w/2, h, armed ? Gray._55 : Gray._75));
g.fillRoundRect(0, 0, w - 2, h - 2, 4, 4);
DarculaUIUtil.paintFocusRing(g, 1, 1, w - 2, h - 2);
} else {
g.setPaint(new GradientPaint(w / 2, 1, Gray._110, w / 2, h, Gray._95));
g.fillRoundRect(0, 0, w , h , 4, 4);
g.setPaint(new GradientPaint(w / 2, 1, Gray._120.withAlpha(90), w / 2, h, Gray._105.withAlpha(90)));
g.drawRoundRect(0, 1, w, h - 1, 4, 4);
g.setPaint(Gray._40.withAlpha(180));
g.drawRoundRect(0, 0, w, h - 1, 4, 4);
}
if (b.getModel().isSelected()) {
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g.setStroke(new BasicStroke(1 *2.0f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
g.setPaint(b.isEnabled() ? Gray._30 : Gray._60);
g.drawLine(4, 7, 7, 11);
g.drawLine(7, 11, w, 2);
g.setPaint(b.isEnabled() ? Gray._170 : Gray._120);
g.drawLine(4, 5, 7, 9);
g.drawLine(7, 9, w, 0);
}
g.translate(-x, -y);
config.restore();
//text
if(text != null) {
View view = (View) c.getClientProperty(BasicHTML.propertyKey);
if (view != null) {
view.paint(g, textRect);
} else {
g.setColor(model.isEnabled() ? b.getForeground() : getDisabledTextColor());
SwingUtilities2.drawStringUnderlineCharAt(c, g, text,
b.getDisplayedMnemonicIndex(),
textRect.x,
textRect.y + fm.getAscent());
}
}
}
@Override
public Icon getDefaultIcon() {
return new IconUIResource(EmptyIcon.create(20));
}
}

208
src/com/bulenkov/darcula/ui/DarculaComboBoxUI.java

@ -0,0 +1,208 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.Gray;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.plaf.basic.BasicComboBoxUI;
import java.awt.*;
import java.awt.geom.Path2D;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings("GtkPreferredJComboBoxRenderer")
public class DarculaComboBoxUI extends BasicComboBoxUI implements Border {
private final JComboBox myComboBox;
public DarculaComboBoxUI(JComboBox comboBox) {
super();
myComboBox = comboBox;
myComboBox.setBorder(this);
}
@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
public static ComponentUI createUI(final JComponent c) {
return new DarculaComboBoxUI(((JComboBox)c));
}
@Override
protected ListCellRenderer createRenderer() {
return new BasicComboBoxRenderer.UIResource() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
final Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (c instanceof JComponent) {
final JComponent jc = (JComponent)c;
if (index == -1) {
jc.setOpaque(false);
jc.setForeground(list.getForeground());
} else {
jc.setOpaque(true);
}
}
return c;
}
};
}
protected JButton createArrowButton() {
final Color bg = myComboBox.getBackground();
final Color fg = myComboBox.getForeground();
JButton button = new BasicArrowButton(SwingConstants.SOUTH, bg, fg, fg, fg) {
@Override
public void paint(Graphics g2) {
final Graphics2D g = (Graphics2D)g2;
final GraphicsConfig config = new GraphicsConfig(g);
final int w = getWidth();
final int h = getHeight();
g.setColor(UIManager.getColor("control"));
g.fillRect(0, 0, w, h);
g.setColor(myComboBox.isEnabled() ? getForeground() : getForeground().darker());
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
final int xU = w / 4;
final int yU = h / 4;
final Path2D.Double path = new Path2D.Double();
g.translate(1, 1);
path.moveTo(xU + 1, yU + 2);
path.lineTo(3 * xU + 1, yU + 2);
path.lineTo(2 * xU + 1, 3 * yU);
path.lineTo(xU + 1, yU + 2);
path.closePath();
g.fill(path);
g.translate(-1, -1);
g.setColor(getBorderColor());
g.drawLine(0, -1, 0, h);
config.restore();
}
};
button.setBorder(BorderFactory.createEmptyBorder());
button.setOpaque(false);
return button;
}
@Override
protected Insets getInsets() {
return new InsetsUIResource(4, 7, 4, 5);
}
@Override
public void paint(Graphics g, JComponent c) {
final Container parent = c.getParent();
if (parent != null) {
g.setColor(parent.getBackground());
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
paintBorder(c, g, 0, 0, c.getWidth(), c.getHeight());
hasFocus = comboBox.hasFocus();
Rectangle r = rectangleForCurrentValue();
paintCurrentValueBackground(g, r, hasFocus);
paintCurrentValue(g, r, hasFocus);
}
@Override
protected void installKeyboardActions() {
super.installKeyboardActions();
}
@Override
public void paintBorder(Component c, Graphics g2, int x, int y, int width, int height) {
if (comboBox == null || arrowButton == null) {
return; //NPE on LaF change
}
hasFocus = false;
checkFocus();
final Graphics2D g = (Graphics2D)g2;
final Rectangle arrowButtonBounds = arrowButton.getBounds();
final int xxx = arrowButtonBounds.x - 5;
final GraphicsConfig config = new GraphicsConfig(g);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
if (editor != null && comboBox.isEditable()) {
((JComponent)editor).setBorder(null);
g.setColor(editor.getBackground());
g.fillRoundRect(x + 1, y + 1, width - 2, height - 4, 5, 5);
g.setColor(arrowButton.getBackground());
g.fillRoundRect(xxx, y + 1, width - xxx, height - 4, 5, 5);
g.setColor(editor.getBackground());
g.fillRect(xxx, y + 1, 5, height - 4);
} else {
g.setColor(UIManager.getColor("Panel.background"));
g.fillRoundRect(x + 1, y + 1, width - 2, height - 4, 5, 5);
}
final Color borderColor = getBorderColor();//ColorUtil.shift(UIUtil.getBorderColor(), 4);
g.setColor(borderColor);
int off = hasFocus ? 1 : 0;
g.drawLine(xxx + 5, y + 1 + off, xxx + 5, height - 3);
Rectangle r = rectangleForCurrentValue();
paintCurrentValueBackground(g,r,hasFocus);
paintCurrentValue(g,r,hasFocus);
if (hasFocus) {
DarculaUIUtil.paintFocusRing(g, 2, 2, width - 4, height - 4);
}
else {
g.setColor(borderColor);
g.drawRoundRect(1, 1, width - 2, height - 4, 5, 5);
}
config.restore();
}
private void checkFocus() {
hasFocus = hasFocus(comboBox);
if (hasFocus) return;
final ComboBoxEditor ed = comboBox.getEditor();
editor = ed == null ? null : ed.getEditorComponent();
if (editor != null) {
hasFocus = hasFocus(editor);
}
}
private static boolean hasFocus(Component c) {
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
return owner != null && SwingUtilities.isDescendingFrom(owner, c);
}
private static Gray getBorderColor() {
return Gray._100;
}
@Override
public Insets getBorderInsets(Component c) {
return new InsetsUIResource(4, 7, 4, 5);
}
@Override
public boolean isBorderOpaque() {
return false;
}
}

42
src/com/bulenkov/darcula/ui/DarculaEditorPaneUI.java

@ -0,0 +1,42 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicEditorPaneUI;
/**
* @author Konstantin Bulenkov
*/
public class DarculaEditorPaneUI extends BasicEditorPaneUI {
private final JEditorPane myEditorPane;
public DarculaEditorPaneUI(JComponent comp) {
myEditorPane = ((JEditorPane)comp);
}
@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
public static ComponentUI createUI(JComponent comp) {
return new DarculaEditorPaneUI(comp);
}
@Override
protected void installDefaults() {
super.installDefaults();
}
}

50
src/com/bulenkov/darcula/ui/DarculaMenuBarBorder.java

@ -0,0 +1,50 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.util.Gray;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaMenuBarBorder implements Border, UIResource {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
g.translate(x, y);
w--;h--;
g.setColor(Gray._85);
g.drawLine(0, h, w, h);
h--;
g.setColor(Gray._40);
g.drawLine(0, h, w, h);
g.translate(-x, -y);
}
@Override
public Insets getBorderInsets(Component c) {
return new InsetsUIResource(0, 0, 2, 0);
}
@Override
public boolean isBorderOpaque() {
return true;
}
}

12
src/com/bulenkov/darcula/ui/DarculaMenuItemBorder.java

@ -0,0 +1,12 @@
package com.bulenkov.darcula.ui;
import javax.swing.plaf.BorderUIResource;
/**
* @author Konstantin Bulenkov
*/
public class DarculaMenuItemBorder extends BorderUIResource.EmptyBorderUIResource {
public DarculaMenuItemBorder() {
super(2, 2, 2, 2);
}
}

31
src/com/bulenkov/darcula/ui/DarculaPanelUI.java

@ -0,0 +1,31 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicPanelUI;
/**
* @author Konstantin Bulenkov
*/
public class DarculaPanelUI extends BasicPanelUI {
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new DarculaPanelUI();
}
}

81
src/com/bulenkov/darcula/ui/DarculaPasswordFieldUI.java

@ -0,0 +1,81 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.util.GraphicsConfig;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicPasswordFieldUI;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
/**
* @author Konstantin Bulenkov
*/
public class DarculaPasswordFieldUI extends BasicPasswordFieldUI {
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(final JComponent c) {
c.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
c.repaint();
}
@Override
public void focusLost(FocusEvent e) {
c.repaint();
}
});
return new DarculaPasswordFieldUI();
}
@Override
protected void paintBackground(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics;
final JTextComponent c = getComponent();
final Container parent = c.getParent();
if (parent != null) {
g.setColor(parent.getBackground());
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
final Border border = c.getBorder();
if (border instanceof DarculaTextBorder) {
g.setColor(c.getBackground());
final int width = c.getWidth();
final int height = c.getHeight();
final Insets i = border.getBorderInsets(c);
if (c.hasFocus()) {
final GraphicsConfig config = new GraphicsConfig(g);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g.fillRoundRect(i.left - 5, i.top - 2, width - i.left - i.right + 10, height - i.top - i.bottom + 6, 5, 5);
config.restore();
}
else {
g.fillRect(i.left - 5, i.top - 2, width - i.left - i.right + 12, height - i.top - i.bottom + 6);
}
} else {
super.paintBackground(g);
}
}
}

38
src/com/bulenkov/darcula/ui/DarculaPopupMenuBorder.java

@ -0,0 +1,38 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import javax.swing.*;
import javax.swing.border.AbstractBorder;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaPopupMenuBorder extends AbstractBorder implements UIResource {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.setColor(UIManager.getDefaults().getColor("Separator.foreground"));
g.drawRect(0,0,width-1,height-1);
}
@Override
public Insets getBorderInsets(Component c) {
return new InsetsUIResource(1,1,1,1);
}
}

27
src/com/bulenkov/darcula/ui/DarculaProgressBarBorder.java

@ -0,0 +1,27 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import javax.swing.plaf.BorderUIResource;
/**
* @author Konstantin Bulenkov
*/
public class DarculaProgressBarBorder extends BorderUIResource.EmptyBorderUIResource {
public DarculaProgressBarBorder() {
super(0,0,0,0);
}
}

187
src/com/bulenkov/darcula/ui/DarculaProgressBarUI.java

@ -0,0 +1,187 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.util.GraphicsUtil;
import com.bulenkov.darcula.util.Gray;
import sun.swing.SwingUtilities2;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.BorderUIResource;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicProgressBarUI;
import java.awt.*;
import java.awt.geom.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaProgressBarUI extends BasicProgressBarUI {
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
c.setBorder(new BorderUIResource(new EmptyBorder(0,0,0,0)));
return new DarculaProgressBarUI();
}
protected volatile int offset = 0;
@Override
protected void paintIndeterminate(Graphics g, JComponent c) {
if (!(g instanceof Graphics2D)) {
return;
}
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth() - (b.right + b.left);
int barRectHeight = progressBar.getHeight() - (b.top + b.bottom);
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
//boxRect = getBox(boxRect);
g.setColor(Gray._128);
int w = c.getWidth();
int h = c.getHeight();
g.fillRect(0, 0, w, h);
g.setColor(Gray._88);
GraphicsUtil.setupAAPainting(g);
Path2D.Double path = new Path2D.Double();
int ww = getPeriodLength() / 2;
path.moveTo(0, 0);
path.lineTo(ww, 0);
path.lineTo(ww - h / 2, h);
path.lineTo(-h / 2, h);
path.lineTo(0, 0);
path.closePath();
int x = -offset;
while (x < Math.max(c.getWidth(), c.getHeight())) {
g.translate(x, 0);
((Graphics2D)g).fill(path);
g.translate(-x, 0);
x+= getPeriodLength();
}
offset = (offset + 1) % getPeriodLength();
Area area = new Area(new Rectangle2D.Double(0, 0, w, h));
area.subtract(new Area(new RoundRectangle2D.Double(1,1,w-2, h-2, 8,8)));
((Graphics2D)g).setPaint(Gray._128);
((Graphics2D)g).fill(area);
area.subtract(new Area(new RoundRectangle2D.Double(0,0,w, h, 9,9)));
((Graphics2D)g).setPaint(c.getParent().getBackground());
((Graphics2D)g).fill(area);
g.drawRoundRect(1,1, w-3, h-3, 8,8);
// Deal with possible text painting
if (progressBar.isStringPainted()) {
if (progressBar.getOrientation() == SwingConstants.HORIZONTAL) {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, boxRect.x, boxRect.width);
}
else {
paintString(g, b.left, b.top, barRectWidth, barRectHeight, boxRect.y, boxRect.height);
}
}
}
@Override
protected void paintDeterminate(Graphics g, JComponent c) {
if (!(g instanceof Graphics2D)) {
return;
}
if (progressBar.getOrientation() != SwingConstants.HORIZONTAL || !c.getComponentOrientation().isLeftToRight()) {
super.paintDeterminate(g, c);
return;
}
GraphicsUtil.setupAAPainting(g);
Insets b = progressBar.getInsets(); // area for border
final int w = progressBar.getWidth();
final int h = progressBar.getHeight();
int barRectWidth = w - (b.right + b.left);
int barRectHeight = h - (b.top + b.bottom);
if (barRectWidth <= 0 || barRectHeight <= 0) {
return;
}
int amountFull = getAmountFull(b, barRectWidth, barRectHeight);
g.setColor(c.getParent().getBackground());
Graphics2D g2 = (Graphics2D)g;
g.fillRect(0, 0, w, h);
g2.setColor(progressBar.getForeground());
g2.fill(new RoundRectangle2D.Double(0, 0, w - 1, h - 1, 9, 9));
g2.setColor(c.getParent().getBackground());
g2.fill(new RoundRectangle2D.Double(1,1,w-3,h-3,8,8));
g2.setColor(progressBar.getForeground());
g2.fill(new RoundRectangle2D.Double(2,2,amountFull-5,h-5,7,7));
// Deal with possible text painting
if (progressBar.isStringPainted()) {
paintString(g, b.left, b.top,
barRectWidth, barRectHeight,
amountFull, b);
}
}
private void paintString(Graphics g, int x, int y, int w, int h, int fillStart, int amountFull) {
if (!(g instanceof Graphics2D)) {
return;
}
Graphics2D g2 = (Graphics2D)g;
String progressString = progressBar.getString();
g2.setFont(progressBar.getFont());
Point renderLocation = getStringPlacement(g2, progressString,
x, y, w, h);
Rectangle oldClip = g2.getClipBounds();
if (progressBar.getOrientation() == JProgressBar.HORIZONTAL) {
g2.setColor(getSelectionBackground());
SwingUtilities2.drawString(progressBar, g2, progressString,
renderLocation.x, renderLocation.y);
g2.setColor(getSelectionForeground());
g2.clipRect(fillStart, y, amountFull, h);
SwingUtilities2.drawString(progressBar, g2, progressString,
renderLocation.x, renderLocation.y);
} else { // VERTICAL
g2.setColor(getSelectionBackground());
AffineTransform rotate =
AffineTransform.getRotateInstance(Math.PI/2);
g2.setFont(progressBar.getFont().deriveFont(rotate));
renderLocation = getStringPlacement(g2, progressString,
x, y, w, h);
SwingUtilities2.drawString(progressBar, g2, progressString,
renderLocation.x, renderLocation.y);
g2.setColor(getSelectionForeground());
g2.clipRect(x, fillStart, w, amountFull);
SwingUtilities2.drawString(progressBar, g2, progressString,
renderLocation.x, renderLocation.y);
}
g2.setClip(oldClip);
}
@Override
protected int getBoxLength(int availableLength, int otherDimension) {
return availableLength;
}
protected int getPeriodLength() {
return 16;
}
}

134
src/com/bulenkov/darcula/ui/DarculaRadioButtonUI.java

@ -0,0 +1,134 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.darcula.SystemInfo;
import com.bulenkov.darcula.util.*;
import sun.swing.SwingUtilities2;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.IconUIResource;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.plaf.metal.MetalRadioButtonUI;
import javax.swing.text.View;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaRadioButtonUI extends MetalRadioButtonUI {
@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
public static ComponentUI createUI(JComponent c) {
return new DarculaRadioButtonUI();
}
@Override
public synchronized void paint(Graphics g2d, JComponent c) {
Graphics2D g = (Graphics2D)g2d;
AbstractButton b = (AbstractButton) c;
ButtonModel model = b.getModel();
Dimension size = c.getSize();
Font f = c.getFont();
g.setFont(f);
FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f);
Rectangle viewRect = new Rectangle(size);
Rectangle iconRect = new Rectangle();
Rectangle textRect = new Rectangle();
Insets i = c.getInsets();
viewRect.x += i.left;
viewRect.y += i.top;
viewRect.width -= (i.right + viewRect.x);
viewRect.height -= (i.bottom + viewRect.y);
String text = SwingUtilities.layoutCompoundLabel(
c, fm, b.getText(), getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
viewRect, iconRect, textRect, b.getIconTextGap());
// fill background
if(c.isOpaque()) {
g.setColor(b.getBackground());
g.fillRect(0,0, size.width, size.height);
}
// Paint the radio button
final int x = iconRect.x + 2;
final int y = iconRect.y + 2;
final int w = iconRect.width - 4;
final int h = iconRect.height - 4;
g.translate(x, y);
//setup AA for lines
final GraphicsConfig config = GraphicsUtil.setupAAPainting(g);
g.setPaint(
new GradientPaint(0, 0, ColorUtil.shift(c.getBackground(), 1.5), 0, c.getHeight(), ColorUtil.shift(c.getBackground(), 1.2)));
g.fillOval(0, 1, w - 1, h - 1);
if (b.hasFocus()) {
int sysOffX = SystemInfo.isMac ? 0 : 1;
int sysOffY = SystemInfo.isMac ? 0 : -1;
DarculaUIUtil.paintFocusOval(g, x - 6 + sysOffX, y - 3 + sysOffY, w - 2, h - 2);
} else {
g.setPaint(new GradientPaint(w / 2, 1, Gray._160.withAlpha(90), w / 2, h, Gray._100.withAlpha(90)));
g.drawOval(0, 2, w - 1, h - 1);
g.setPaint(Gray._40.withAlpha(200));
g.drawOval(0, 1, w - 1, h - 1);
}
if (b.isSelected()) {
g.setColor(b.isEnabled() ? Gray._30 : Gray._60);
g.fillOval(w/2 - 3, h/2 - 1, 5, 5);
g.setColor(b.isEnabled() ? Gray._170 : Gray._120);
g.fillOval(w/2 - 3, h/2 - 2, 5, 5);
}
config.restore();
g.translate(-x, -y);
// Draw the Text
if(text != null) {
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (v != null) {
v.paint(g, textRect);
} else {
int mnemIndex = b.getDisplayedMnemonicIndex();
if(model.isEnabled()) {
// *** paint the text normally
g.setColor(b.getForeground());
} else {
// *** paint the text disabled
g.setColor(getDisabledTextColor());
}
SwingUtilities2.drawStringUnderlineCharAt(c, g, text,
mnemIndex, textRect.x, textRect.y + fm.getAscent());
}
}
}
@Override
public Icon getDefaultIcon() {
return new IconUIResource(EmptyIcon.create(20));
}
}

336
src/com/bulenkov/darcula/ui/DarculaScrollBarUI.java

@ -0,0 +1,336 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.util.Animator;
import com.bulenkov.darcula.util.Gray;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.*;
import java.awt.event.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaScrollBarUI extends BasicScrollBarUI {
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new DarculaScrollBarUI();
}
public static Color getGradientLightColor() {
return Gray._90;
}
public static Color getGradientDarkColor() {
return Gray._70;
}
private static Color getGradientThumbBorderColor() {
return Gray._75;
}
public static Color getTrackBackground() {
return UIManager.getColor("control");
}
public static Color getTrackBorderColor() {
return UIManager.getColor("control");
}
private static final BasicStroke BORDER_STROKE = new BasicStroke();
public static final int ANIMATION_COLOR_SHIFT = 20;
private final AdjustmentListener myAdjustmentListener;
private final MouseMotionAdapter myMouseMotionListener;
private final MouseAdapter myMouseListener;
private Animator myAnimator;
private int myAnimationColorShift = 0;
private boolean myMouseIsOverThumb = false;
public static final int DELAY_FRAMES = 4;
public static final int FRAMES_COUNT = 10 + DELAY_FRAMES;
protected DarculaScrollBarUI() {
myAdjustmentListener = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
resetAnimator();
}
};
myMouseMotionListener = new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
boolean inside = isOverThumb(e.getPoint());
if (inside != myMouseIsOverThumb) {
myMouseIsOverThumb = inside;
resetAnimator();
}
}
};
myMouseListener = new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
if (myMouseIsOverThumb) {
myMouseIsOverThumb = false;
resetAnimator();
}
}
};
}
@Override
public void layoutContainer(Container scrollbarContainer) {
try {
super.layoutContainer(scrollbarContainer);
} catch (NullPointerException ignore) {
//installUI is not performed yet or uninstallUI has set almost every field to null. Just ignore it //IDEA-89674
}
}
public int getDecrementButtonHeight() {
return decrButton.getHeight();
}
public int getIncrementButtonHeight() {
return incrButton.getHeight();
}
private void resetAnimator() {
myAnimator.reset();
if (scrollbar != null && scrollbar.getValueIsAdjusting() || myMouseIsOverThumb) {
myAnimator.suspend();
myAnimationColorShift = ANIMATION_COLOR_SHIFT;
}
else {
myAnimator.resume();
}
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
scrollbar.setFocusable(false);
}
@Override
protected void installDefaults() {
final int incGap = UIManager.getInt("ScrollBar.incrementButtonGap");
final int decGap = UIManager.getInt("ScrollBar.decrementButtonGap");
try {
UIManager.put("ScrollBar.incrementButtonGap", 0);
UIManager.put("ScrollBar.decrementButtonGap", 0);
super.installDefaults();
}
finally {
UIManager.put("ScrollBar.incrementButtonGap", incGap);
UIManager.put("ScrollBar.decrementButtonGap", decGap);
}
}
@Override
protected void installListeners() {
if (myAnimator == null || myAnimator.isDisposed()) {
myAnimator = createAnimator();
}
super.installListeners();
scrollbar.addAdjustmentListener(myAdjustmentListener);
scrollbar.addMouseListener(myMouseListener);
scrollbar.addMouseMotionListener(myMouseMotionListener);
}
private Animator createAnimator() {
return new Animator("Adjustment fadeout", FRAMES_COUNT, FRAMES_COUNT * 50, false) {
@Override
public void paintNow(int frame, int totalFrames, int cycle) {
myAnimationColorShift = ANIMATION_COLOR_SHIFT;
if (frame > DELAY_FRAMES) {
myAnimationColorShift *= 1 - ((double)(frame - DELAY_FRAMES)) / ((double)(totalFrames - DELAY_FRAMES));
}
if (scrollbar != null) {
scrollbar.repaint(((DarculaScrollBarUI)scrollbar.getUI()).getThumbBounds());
}
}
};
}
private boolean isOverThumb(Point p) {
final Rectangle bounds = getThumbBounds();
return bounds != null && bounds.contains(p);
}
@Override
public Rectangle getThumbBounds() {
return super.getThumbBounds();
}
@Override
protected void uninstallListeners() {
if (scrollTimer != null) {
// it is already called otherwise
super.uninstallListeners();
}
scrollbar.removeAdjustmentListener(myAdjustmentListener);
}
@Override
protected void paintTrack(Graphics g, JComponent c, Rectangle bounds) {
g.setColor(getTrackBackground());
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(getTrackBorderColor());
if (isVertical()) {
g.drawLine(bounds.x, bounds.y, bounds.x, bounds.y + bounds.height);
}
else {
g.drawLine(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y);
}
}
@Override
protected Dimension getMinimumThumbSize() {
final int thickness = getThickness();
return isVertical() ? new Dimension(thickness, thickness * 2) : new Dimension(thickness * 2, thickness);
}
protected int getThickness() {
return 13;
}
@Override
public Dimension getMaximumSize(JComponent c) {
int thickness = getThickness();
return new Dimension(thickness, thickness);
}
@Override
public Dimension getMinimumSize(JComponent c) {
return getMaximumSize(c);
}
@Override
public Dimension getPreferredSize(JComponent c) {
return getMaximumSize(c);
}
@Override
protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
if (thumbBounds.isEmpty() || !scrollbar.isEnabled()) {
return;
}
g.translate(thumbBounds.x, thumbBounds.y);
paintMaxiThumb((Graphics2D)g, thumbBounds);
g.translate(-thumbBounds.x, -thumbBounds.y);
}
private void paintMaxiThumb(Graphics2D g, Rectangle thumbBounds) {
final boolean vertical = isVertical();
int hGap = vertical ? 2 : 1;
int vGap = vertical ? 1 : 2;
int w = adjustThumbWidth(thumbBounds.width - hGap * 2);
int h = thumbBounds.height - vGap * 2;
// leave one pixel between thumb and right or bottom edge
if (vertical) {
h -= 1;
}
else {
w -= 1;
}
final Paint paint;
final Color start = adjustColor(getGradientLightColor());
final Color end = adjustColor(getGradientDarkColor());
if (vertical) {
paint = new GradientPaint(1, 0, start, w + 1, 0, end);
}
else {
paint = new GradientPaint(0, 1, start, 0, h + 1, end);
}
g.setPaint(paint);
g.fillRect(hGap + 1, vGap + 1, w - 1, h - 1);
final Stroke stroke = g.getStroke();
g.setStroke(BORDER_STROKE);
g.setColor(getGradientThumbBorderColor());
g.drawRoundRect(hGap, vGap, w, h, 3, 3);
g.setStroke(stroke);
}
@Override
public boolean getSupportsAbsolutePositioning() {
return true;
}
protected int adjustThumbWidth(int width) {
return width;
}
protected Color adjustColor(Color c) {
if (myAnimationColorShift == 0) return c;
return Gray.get(c.getRed() + myAnimationColorShift);
}
private boolean isVertical() {
return scrollbar.getOrientation() == Adjustable.VERTICAL;
}
@Override
protected JButton createIncreaseButton(int orientation) {
return new EmptyButton();
}
@Override
protected JButton createDecreaseButton(int orientation) {
return new EmptyButton();
}
private static class EmptyButton extends JButton {
private EmptyButton() {
setFocusable(false);
setRequestFocusEnabled(false);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(0, 0);
}
@Override
public Dimension getPreferredSize() {
return getMaximumSize();
}
@Override
public Dimension getMinimumSize() {
return getMaximumSize();
}
}
}

83
src/com/bulenkov/darcula/ui/DarculaSpinnerBorder.java

@ -0,0 +1,83 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.GraphicsUtil;
import com.bulenkov.darcula.util.Gray;
import com.bulenkov.darcula.util.UIUtil;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaSpinnerBorder implements Border, UIResource {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
final JSpinner spinner = (JSpinner)c;
final JFormattedTextField editor = UIUtil.findComponentOfType(spinner, JFormattedTextField.class);
final int x1 = x + 3;
final int y1 = y + 3;
final int width1 = width - 8;
final int height1 = height - 6;
final boolean focused = c.isEnabled() && c.isVisible() && editor != null && editor.hasFocus();
final GraphicsConfig config = GraphicsUtil.setupAAPainting(g);
if (c.isOpaque()) {
g.setColor(UIManager.getColor("Panel.background"));
g.fillRect(x, y, width, height);
}
g.setColor(UIManager.getColor("TextField.background"));
g.fillRoundRect(x1, y1, width1, height1, 5, 5);
g.setColor(UIManager.getColor("Panel.background"));
if (editor != null) {
final int off = editor.getBounds().x + editor.getWidth() + ((JSpinner)c).getInsets().left;
g.fillRect(off, y1, 17, height1);
g.setColor(Gray._100);
g.drawLine(off, y1, off, height1+2);
}
if (!c.isEnabled()) {
((Graphics2D)g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
}
if (focused) {
DarculaUIUtil.paintFocusRing(g, x1, y1, width1, height1);
} else {
g.setColor(Gray._100);
g.drawRoundRect(x1, y1, width1, height1, 5, 5);
}
config.restore();
}
@Override
public Insets getBorderInsets(Component c) {
return new InsetsUIResource(6, 7, 6, 7);
}
@Override
public boolean isBorderOpaque() {
return true;
}
}

200
src/com/bulenkov/darcula/ui/DarculaSpinnerUI.java

@ -0,0 +1,200 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.GraphicsUtil;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicSpinnerUI;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
/**
* @author Konstantin Bulenkov
*/
public class DarculaSpinnerUI extends BasicSpinnerUI {
private FocusAdapter myFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
spinner.repaint();
}
@Override
public void focusLost(FocusEvent e) {
spinner.repaint();
}
};
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new DarculaSpinnerUI();
}
@Override
protected void replaceEditor(JComponent oldEditor, JComponent newEditor) {
super.replaceEditor(oldEditor, newEditor);
if (oldEditor != null) {
oldEditor.getComponents()[0].removeFocusListener(myFocusListener);
}
if (newEditor != null) {
newEditor.getComponents()[0].addFocusListener(myFocusListener);
}
}
@Override
protected JComponent createEditor() {
final JComponent editor = super.createEditor();
editor.getComponents()[0].addFocusListener(myFocusListener);
return editor;
}
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
final Border border = spinner.getBorder();
if (border != null) {
border.paintBorder(c, g, 0, 0, spinner.getWidth(), spinner.getHeight());
}
}
@Override
protected Component createPreviousButton() {
JButton button = createArrow(SwingConstants.SOUTH);
button.setName("Spinner.previousButton");
button.setBorder(new EmptyBorder(1, 1, 1, 1));
installPreviousButtonListeners(button);
return button;
}
@Override
protected Component createNextButton() {
JButton button = createArrow(SwingConstants.NORTH);
button.setName("Spinner.nextButton");
button.setBorder(new EmptyBorder(1, 1, 1, 1));
installNextButtonListeners(button);
return button;
}
@Override
protected LayoutManager createLayout() {
return new LayoutManagerDelegate(super.createLayout()) {
@Override
public void layoutContainer(Container parent) {
super.layoutContainer(parent);
final JComponent editor = spinner.getEditor();
if (editor != null) {
final Rectangle bounds = editor.getBounds();
editor.setBounds(bounds.x, bounds.y, bounds.width - 6, bounds.height);
}
}
};
}
private JButton createArrow(int direction) {
final Color shadow = UIManager.getColor("Panel.background");
final Color darkShadow = UIManager.getColor("Label.foreground");
JButton b = new BasicArrowButton(direction, shadow, shadow, darkShadow, shadow) {
@Override
public void paint(Graphics g) {
int y = direction == NORTH ? getHeight() - 6 : 2;
paintTriangle(g, 0, y, 0, direction, DarculaSpinnerUI.this.spinner.isEnabled());
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintTriangle(Graphics g, int x, int y, int size, int direction, boolean isEnabled) {
final GraphicsConfig config = GraphicsUtil.setupAAPainting(g);
int mid;
final int w = 8;
final int h = 6;
mid = w / 2;
g.setColor(isEnabled ? darkShadow : darkShadow.darker());
g.translate(x, y);
switch (direction) {
case SOUTH:
g.fillPolygon(new int[]{0, w, mid}, new int[]{1, 1, h}, 3);
break;
case NORTH:
g.fillPolygon(new int[]{0, w, mid}, new int[]{h - 1, h - 1, 0}, 3);
break;
case WEST:
case EAST:
}
g.translate(-x, -y);
config.restore();
}
};
Border buttonBorder = UIManager.getBorder("Spinner.arrowButtonBorder");
if (buttonBorder instanceof UIResource) {
// Wrap the border to avoid having the UIResource be replaced by
// the ButtonUI. This is the opposite of using BorderUIResource.
b.setBorder(new CompoundBorder(buttonBorder, null));
}
else {
b.setBorder(buttonBorder);
}
b.setInheritsPopupMenu(true);
return b;
}
static class LayoutManagerDelegate implements LayoutManager {
protected final LayoutManager myDelegate;
LayoutManagerDelegate(LayoutManager delegate) {
myDelegate = delegate;
}
@Override
public void addLayoutComponent(String name, Component comp) {
myDelegate.addLayoutComponent(name, comp);
}
@Override
public void removeLayoutComponent(Component comp) {
myDelegate.removeLayoutComponent(comp);
}
@Override
public Dimension preferredLayoutSize(Container parent) {
return myDelegate.preferredLayoutSize(parent);
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return myDelegate.minimumLayoutSize(parent);
}
@Override
public void layoutContainer(Container parent) {
myDelegate.layoutContainer(parent);
}
}
}

30
src/com/bulenkov/darcula/ui/DarculaTabbedPaneUI.java

@ -0,0 +1,30 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTabbedPaneUI extends BasicTabbedPaneUI {
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new DarculaTabbedPaneUI();
}
}

58
src/com/bulenkov/darcula/ui/DarculaTextBorder.java

@ -0,0 +1,58 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.darcula.util.GraphicsConfig;
import com.bulenkov.darcula.util.Gray;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import javax.swing.text.JTextComponent;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTextBorder implements Border, UIResource {
@Override
public Insets getBorderInsets(Component c) {
return new InsetsUIResource(4, 7, 4, 7);
}
@Override
public boolean isBorderOpaque() {
return false;
}
@Override
public void paintBorder(Component c, Graphics g2, int x, int y, int width, int height) {
Graphics2D g = ((Graphics2D)g2);
final GraphicsConfig config = new GraphicsConfig(g);
g.translate(x, y);
if (c.hasFocus()) {
DarculaUIUtil.paintFocusRing(g, 2, 2, width - 4, height - 4);
} else {
boolean editable = !(c instanceof JTextComponent) || (((JTextComponent)c).isEditable());
g.setColor(c.isEnabled() && editable ? Gray._100 : new Color(0x535353));
g.drawRect(1, 1, width - 2, height - 2);
}
g.translate(-x, -y);
config.restore();
}
}

81
src/com/bulenkov/darcula/ui/DarculaTextFieldUI.java

@ -0,0 +1,81 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.util.GraphicsConfig;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
/**
* @author Konstantin Bulenkov
*/
public class DarculaTextFieldUI extends BasicTextFieldUI {
@SuppressWarnings("MethodOverridesStaticMethodOfSuperclass")
public static ComponentUI createUI(final JComponent c) {
c.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
c.repaint();
}
@Override
public void focusLost(FocusEvent e) {
c.repaint();
}
});
return new DarculaTextFieldUI();
}
@Override
protected void paintBackground(Graphics graphics) {
Graphics2D g = (Graphics2D)graphics;
final JTextComponent c = getComponent();
final Container parent = c.getParent();
if (parent != null) {
g.setColor(parent.getBackground());
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
final Border border = c.getBorder();
if (border instanceof DarculaTextBorder) {
if (c.isEnabled() && c.isEditable()) {
g.setColor(c.getBackground());
}
final int width = c.getWidth();
final int height = c.getHeight();
final Insets i = border.getBorderInsets(c);
if (c.hasFocus()) {
final GraphicsConfig config = new GraphicsConfig(g);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g.fillRoundRect(i.left - 5, i.top - 2, width - i.right - i.left + 10, height - i.top - i.bottom + 6, 5, 5);
config.restore();
} else {
g.fillRect(i.left - 5, i.top - 2, width - i.right - i.left + 12, height - i.top - i.bottom + 6);
}
} else {
super.paintBackground(g);
}
}
}

169
src/com/bulenkov/darcula/util/Animator.java

@ -0,0 +1,169 @@
package com.bulenkov.darcula.util;
import javax.swing.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Konstantin Bulenkov
*/
public abstract class Animator {
private final static ScheduledExecutorService scheduler = createScheduler();
private static ScheduledExecutorService createScheduler() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
public Thread newThread(final Runnable r) {
final Thread thread = new Thread(r, "Darcula Animations");
thread.setDaemon(true);
thread.setPriority(Thread.NORM_PRIORITY);
return thread;
}
});
executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
return executor;
}
private final int myTotalFrames;
private final int myCycleDuration;
private final boolean myForward;
private final boolean myRepeatable;
private ScheduledFuture<?> myTicker;
private int myCurrentFrame;
private long myStartTime;
private long myStopTime;
private volatile boolean myDisposed = false;
public Animator(final String name,
final int totalFrames,
final int cycleDuration,
boolean repeatable) {
this(name, totalFrames, cycleDuration, repeatable, true);
}
public Animator(final String name,
final int totalFrames,
final int cycleDuration,
boolean repeatable,
boolean forward) {
myTotalFrames = totalFrames;
myCycleDuration = cycleDuration;
myRepeatable = repeatable;
myForward = forward;
myCurrentFrame = forward ? 0 : totalFrames;
reset();
}
private void onTick() {
if (isDisposed()) return;
if (myStartTime == -1) {
myStartTime = System.currentTimeMillis();
myStopTime = myStartTime + myCycleDuration * (myTotalFrames - myCurrentFrame) / myTotalFrames;
}
final double passedTime = System.currentTimeMillis() - myStartTime;
final double totalTime = myStopTime - myStartTime;
final int newFrame = (int)(passedTime * myTotalFrames / totalTime);
if (myCurrentFrame > 0 && newFrame == myCurrentFrame) return;
myCurrentFrame = newFrame;
if (myCurrentFrame >= myTotalFrames) {
if (myRepeatable) {
reset();
}
else {
animationDone();
return;
}
}
paint();
}
private void paint() {
paintNow(myForward ? myCurrentFrame : myTotalFrames - myCurrentFrame - 1, myTotalFrames, myCycleDuration);
}
private void animationDone() {
stopTicker();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
paintCycleEnd();
}
});
}
private void stopTicker() {
if (myTicker != null) {
myTicker.cancel(false);
myTicker = null;
}
}
protected void paintCycleEnd() {
}
public void suspend() {
myStartTime = -1;
stopTicker();
}
public void resume() {
if (myCycleDuration == 0) {
myCurrentFrame = myTotalFrames - 1;
paint();
animationDone();
}
else if (myTicker == null) {
myTicker = scheduler.scheduleWithFixedDelay(new Runnable() {
AtomicBoolean scheduled = new AtomicBoolean(false);
@Override
public void run() {
if (scheduled.compareAndSet(false, true) && !isDisposed()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
scheduled.set(false);
onTick();
}
});
}
}
}, 0, myCycleDuration * 1000 / myTotalFrames, TimeUnit.MICROSECONDS);
}
}
public abstract void paintNow(int frame, int totalFrames, int cycle);
public void dispose() {
myDisposed = true;
stopTicker();
}
public boolean isRunning() {
return myTicker != null;
}
public void reset() {
myCurrentFrame = 0;
myStartTime = -1;
}
public final boolean isForward() {
return myForward;
}
public boolean isDisposed() {
return myDisposed;
}
}

57
src/com/bulenkov/darcula/util/ColorUtil.java

@ -0,0 +1,57 @@
package com.bulenkov.darcula.util;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class ColorUtil {
private static int shift(int colorComponent, double d) {
final int n = (int) (colorComponent * d);
return n > 255 ? 255 : n < 0 ? 0 : n;
}
public static Color shift(Color c, double d) {
return new Color(shift(c.getRed(), d), shift(c.getGreen(), d), shift(c.getBlue(), d), c.getAlpha());
}
public static Color toAlpha(Color color, int a) {
Color c = color != null ? color : Color.black;
return new Color(c.getRed(), c.getGreen(), c.getBlue(), a);
}
/**
* Return Color object from string. The following formats are allowed:
* <code>#abc123</code>,
* <code>ABC123</code>,
* <code>ab5</code>,
* <code>#FFF</code>.
*
* @param str hex string
* @return Color object
*/
public static Color fromHex(String str) {
if (str.startsWith("#")) {
str = str.substring(1);
}
if (str.length() == 3) {
return new Color(
17 * Integer.valueOf(String.valueOf(str.charAt(0)), 16).intValue(),
17 * Integer.valueOf(String.valueOf(str.charAt(1)), 16).intValue(),
17 * Integer.valueOf(String.valueOf(str.charAt(2)), 16).intValue());
} else if (str.length() == 6) {
return Color.decode("0x" + str);
} else {
throw new IllegalArgumentException("Should be String of 3 or 6 chars length.");
}
}
public static Color fromHex(String str, Color defaultValue) {
try {
return fromHex(str);
} catch (Exception e) {
return defaultValue;
}
}
}

78
src/com/bulenkov/darcula/util/EmptyIcon.java

@ -0,0 +1,78 @@
package com.bulenkov.darcula.util;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author Konstantin Bulenkov
*/
public class EmptyIcon implements Icon {
private static final Map<Integer, Icon> cache = new HashMap<Integer, Icon>();
private final int width;
private final int height;
public static Icon create(int size) {
Icon icon = cache.get(size);
if (icon == null && size < 129) {
cache.put(size, icon = new EmptyIcon(size, size));
}
return icon == null ? new EmptyIcon(size, size) : icon;
}
public static Icon create(int width, int height) {
return width == height ? create(width) : new EmptyIcon(width, height);
}
public static Icon create(Icon base) {
return create(base.getIconWidth(), base.getIconHeight());
}
/**
* @deprecated use {@linkplain #create(int)} for caching.
*/
public EmptyIcon(int size) {
this(size, size);
}
public EmptyIcon(int width, int height) {
this.width = width;
this.height = height;
}
/**
* @deprecated use {@linkplain #create(javax.swing.Icon)} for caching.
*/
public EmptyIcon(Icon base) {
this(base.getIconWidth(), base.getIconHeight());
}
public int getIconWidth() {
return width;
}
public int getIconHeight() {
return height;
}
public void paintIcon(Component component, Graphics g, int i, int j) {
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EmptyIcon)) return false;
final EmptyIcon icon = (EmptyIcon)o;
if (height != icon.height) return false;
if (width != icon.width) return false;
return true;
}
public int hashCode() {
int sum = width + height;
return sum * (sum + 1)/2 + width;
}
}

31
src/com/bulenkov/darcula/util/GraphicsConfig.java

@ -0,0 +1,31 @@
package com.bulenkov.darcula.util;
import java.awt.*;
import java.util.Map;
/**
* @author Konstantin Bulenkov
*/
public class GraphicsConfig {
private final Graphics2D myG;
private final Map myHints;
public GraphicsConfig(Graphics g) {
myG = (Graphics2D)g;
myHints = (Map)myG.getRenderingHints().clone();
}
public GraphicsConfig setAntialiasing(boolean on) {
myG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, on ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
return this;
}
public Graphics2D getG() {
return myG;
}
public void restore() {
myG.setRenderingHints(myHints);
}
}

46
src/com/bulenkov/darcula/util/GraphicsUtil.java

@ -0,0 +1,46 @@
package com.bulenkov.darcula.util;
import java.awt.*;
import java.util.Map;
/**
* @author Konstantin Bulenkov
*/
public class GraphicsUtil {
public static void setupAntialiasing(Graphics g2) {
setupAntialiasing(g2, true, false);
}
public static void setupAntialiasing(Graphics g2, boolean enableAA, boolean ignoreSystemSettings) {
if (g2 instanceof Graphics2D) {
Graphics2D g = (Graphics2D)g2;
Toolkit tk = Toolkit.getDefaultToolkit();
//noinspection HardCodedStringLiteral
Map map = (Map)tk.getDesktopProperty("awt.font.desktophints");
if (map != null && !ignoreSystemSettings) {
g.addRenderingHints(map);
} else {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
enableAA ? RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
}
}
public static GraphicsConfig setupAAPainting(Graphics g) {
final GraphicsConfig config = new GraphicsConfig(g);
final Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
return config;
}
public static GraphicsConfig paintWithAlpha(Graphics g, float alpha) {
assert 0.0f <= alpha && alpha <= 1.0f : "alpha should be in range 0.0f .. 1.0f";
final GraphicsConfig config = new GraphicsConfig(g);
final Graphics2D g2 = (Graphics2D)g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
return config;
}
}

589
src/com/bulenkov/darcula/util/Gray.java

@ -0,0 +1,589 @@
package com.bulenkov.darcula.util;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings({"InspectionUsingGrayColors", "UnusedDeclaration"})
public class Gray extends Color {
private Gray(int num) {
super(num, num, num);
}
private Gray(int num, int alpha) {
super(num, num, num, alpha);
}
public Color withAlpha(int alpha) {
assert 0 <= alpha && alpha <= 255 : "Alpha " + alpha + "is incorrect. Alpha should be in range 0..255";
return new Gray(getRed(), alpha);
}
public static Gray get(int gray) {
assert 0 <= gray && gray <= 255 : "Gray == " + gray +"Gray should be in range 0..255";
return cache[gray];
}
public static Color get(int gray, int alpha) {
return get(gray).withAlpha(alpha);
}
public static final Gray _0 = new Gray(0);
public static final Gray _1 = new Gray(1);
public static final Gray _2 = new Gray(2);
public static final Gray _3 = new Gray(3);
public static final Gray _4 = new Gray(4);
public static final Gray _5 = new Gray(5);
public static final Gray _6 = new Gray(6);
public static final Gray _7 = new Gray(7);
public static final Gray _8 = new Gray(8);
public static final Gray _9 = new Gray(9);
public static final Gray _10 = new Gray(10);
public static final Gray _11 = new Gray(11);
public static final Gray _12 = new Gray(12);
public static final Gray _13 = new Gray(13);
public static final Gray _14 = new Gray(14);
public static final Gray _15 = new Gray(15);
public static final Gray _16 = new Gray(16);
public static final Gray _17 = new Gray(17);
public static final Gray _18 = new Gray(18);
public static final Gray _19 = new Gray(19);
public static final Gray _20 = new Gray(20);
public static final Gray _21 = new Gray(21);
public static final Gray _22 = new Gray(22);
public static final Gray _23 = new Gray(23);
public static final Gray _24 = new Gray(24);
public static final Gray _25 = new Gray(25);
public static final Gray _26 = new Gray(26);
public static final Gray _27 = new Gray(27);
public static final Gray _28 = new Gray(28);
public static final Gray _29 = new Gray(29);
public static final Gray _30 = new Gray(30);
public static final Gray _31 = new Gray(31);
public static final Gray _32 = new Gray(32);
public static final Gray _33 = new Gray(33);
public static final Gray _34 = new Gray(34);
public static final Gray _36 = new Gray(36);
public static final Gray _35 = new Gray(35);
public static final Gray _37 = new Gray(37);
public static final Gray _38 = new Gray(38);
public static final Gray _39 = new Gray(39);
public static final Gray _40 = new Gray(40);
public static final Gray _41 = new Gray(41);
public static final Gray _42 = new Gray(42);
public static final Gray _43 = new Gray(43);
public static final Gray _44 = new Gray(44);
public static final Gray _45 = new Gray(45);
public static final Gray _46 = new Gray(46);
public static final Gray _47 = new Gray(47);
public static final Gray _48 = new Gray(48);
public static final Gray _49 = new Gray(49);
public static final Gray _50 = new Gray(50);
public static final Gray _51 = new Gray(51);
public static final Gray _52 = new Gray(52);
public static final Gray _53 = new Gray(53);
public static final Gray _54 = new Gray(54);
public static final Gray _55 = new Gray(55);
public static final Gray _56 = new Gray(56);
public static final Gray _57 = new Gray(57);
public static final Gray _58 = new Gray(58);
public static final Gray _59 = new Gray(59);
public static final Gray _60 = new Gray(60);
public static final Gray _61 = new Gray(61);
public static final Gray _62 = new Gray(62);
public static final Gray _63 = new Gray(63);
public static final Gray _64 = new Gray(64);
public static final Gray _65 = new Gray(65);
public static final Gray _66 = new Gray(66);
public static final Gray _67 = new Gray(67);
public static final Gray _68 = new Gray(68);
public static final Gray _69 = new Gray(69);
public static final Gray _70 = new Gray(70);
public static final Gray _71 = new Gray(71);
public static final Gray _72 = new Gray(72);
public static final Gray _73 = new Gray(73);
public static final Gray _74 = new Gray(74);
public static final Gray _75 = new Gray(75);
public static final Gray _76 = new Gray(76);
public static final Gray _77 = new Gray(77);
public static final Gray _78 = new Gray(78);
public static final Gray _79 = new Gray(79);
public static final Gray _80 = new Gray(80);
public static final Gray _81 = new Gray(81);
public static final Gray _82 = new Gray(82);
public static final Gray _83 = new Gray(83);
public static final Gray _84 = new Gray(84);
public static final Gray _85 = new Gray(85);
public static final Gray _86 = new Gray(86);
public static final Gray _87 = new Gray(87);
public static final Gray _88 = new Gray(88);
public static final Gray _89 = new Gray(89);
public static final Gray _90 = new Gray(90);
public static final Gray _91 = new Gray(91);
public static final Gray _92 = new Gray(92);
public static final Gray _93 = new Gray(93);
public static final Gray _94 = new Gray(94);
public static final Gray _95 = new Gray(95);
public static final Gray _96 = new Gray(96);
public static final Gray _97 = new Gray(97);
public static final Gray _98 = new Gray(98);
public static final Gray _99 = new Gray(99);
public static final Gray _100 = new Gray(100);
public static final Gray _101 = new Gray(101);
public static final Gray _102 = new Gray(102);
public static final Gray _103 = new Gray(103);
public static final Gray _104 = new Gray(104);
public static final Gray _105 = new Gray(105);
public static final Gray _106 = new Gray(106);
public static final Gray _107 = new Gray(107);
public static final Gray _108 = new Gray(108);
public static final Gray _109 = new Gray(109);
public static final Gray _110 = new Gray(110);
public static final Gray _111 = new Gray(111);
public static final Gray _112 = new Gray(112);
public static final Gray _113 = new Gray(113);
public static final Gray _114 = new Gray(114);
public static final Gray _115 = new Gray(115);
public static final Gray _116 = new Gray(116);
public static final Gray _117 = new Gray(117);
public static final Gray _118 = new Gray(118);
public static final Gray _119 = new Gray(119);
public static final Gray _120 = new Gray(120);
public static final Gray _121 = new Gray(121);
public static final Gray _122 = new Gray(122);
public static final Gray _123 = new Gray(123);
public static final Gray _124 = new Gray(124);
public static final Gray _125 = new Gray(125);
public static final Gray _126 = new Gray(126);
public static final Gray _127 = new Gray(127);
public static final Gray _128 = new Gray(128);
public static final Gray _129 = new Gray(129);
public static final Gray _130 = new Gray(130);
public static final Gray _131 = new Gray(131);
public static final Gray _132 = new Gray(132);
public static final Gray _133 = new Gray(133);
public static final Gray _134 = new Gray(134);
public static final Gray _135 = new Gray(135);
public static final Gray _136 = new Gray(136);
public static final Gray _137 = new Gray(137);
public static final Gray _138 = new Gray(138);
public static final Gray _139 = new Gray(139);
public static final Gray _140 = new Gray(140);
public static final Gray _141 = new Gray(141);
public static final Gray _142 = new Gray(142);
public static final Gray _143 = new Gray(143);
public static final Gray _144 = new Gray(144);
public static final Gray _145 = new Gray(145);
public static final Gray _146 = new Gray(146);
public static final Gray _147 = new Gray(147);
public static final Gray _148 = new Gray(148);
public static final Gray _149 = new Gray(149);
public static final Gray _150 = new Gray(150);
public static final Gray _151 = new Gray(151);
public static final Gray _152 = new Gray(152);
public static final Gray _153 = new Gray(153);
public static final Gray _154 = new Gray(154);
public static final Gray _155 = new Gray(155);
public static final Gray _156 = new Gray(156);
public static final Gray _157 = new Gray(157);
public static final Gray _158 = new Gray(158);
public static final Gray _159 = new Gray(159);
public static final Gray _160 = new Gray(160);
public static final Gray _161 = new Gray(161);
public static final Gray _162 = new Gray(162);
public static final Gray _163 = new Gray(163);
public static final Gray _164 = new Gray(164);
public static final Gray _165 = new Gray(165);
public static final Gray _166 = new Gray(166);
public static final Gray _167 = new Gray(167);
public static final Gray _168 = new Gray(168);
public static final Gray _169 = new Gray(169);
public static final Gray _170 = new Gray(170);
public static final Gray _171 = new Gray(171);
public static final Gray _172 = new Gray(172);
public static final Gray _173 = new Gray(173);
public static final Gray _174 = new Gray(174);
public static final Gray _175 = new Gray(175);
public static final Gray _176 = new Gray(176);
public static final Gray _177 = new Gray(177);
public static final Gray _178 = new Gray(178);
public static final Gray _179 = new Gray(179);
public static final Gray _180 = new Gray(180);
public static final Gray _181 = new Gray(181);
public static final Gray _182 = new Gray(182);
public static final Gray _183 = new Gray(183);
public static final Gray _184 = new Gray(184);
public static final Gray _185 = new Gray(185);
public static final Gray _186 = new Gray(186);
public static final Gray _187 = new Gray(187);
public static final Gray _188 = new Gray(188);
public static final Gray _189 = new Gray(189);
public static final Gray _190 = new Gray(190);
public static final Gray _191 = new Gray(191);
public static final Gray _192 = new Gray(192);
public static final Gray _193 = new Gray(193);
public static final Gray _194 = new Gray(194);
public static final Gray _195 = new Gray(195);
public static final Gray _196 = new Gray(196);
public static final Gray _197 = new Gray(197);
public static final Gray _198 = new Gray(198);
public static final Gray _199 = new Gray(199);
public static final Gray _200 = new Gray(200);
public static final Gray _201 = new Gray(201);
public static final Gray _202 = new Gray(202);
public static final Gray _203 = new Gray(203);
public static final Gray _204 = new Gray(204);
public static final Gray _205 = new Gray(205);
public static final Gray _206 = new Gray(206);
public static final Gray _207 = new Gray(207);
public static final Gray _208 = new Gray(208);
public static final Gray _209 = new Gray(209);
public static final Gray _210 = new Gray(210);
public static final Gray _211 = new Gray(211);
public static final Gray _212 = new Gray(212);
public static final Gray _213 = new Gray(213);
public static final Gray _214 = new Gray(214);
public static final Gray _215 = new Gray(215);
public static final Gray _216 = new Gray(216);
public static final Gray _217 = new Gray(217);
public static final Gray _218 = new Gray(218);
public static final Gray _219 = new Gray(219);
public static final Gray _220 = new Gray(220);
public static final Gray _221 = new Gray(221);
public static final Gray _222 = new Gray(222);
public static final Gray _223 = new Gray(223);
public static final Gray _224 = new Gray(224);
public static final Gray _225 = new Gray(225);
public static final Gray _226 = new Gray(226);
public static final Gray _227 = new Gray(227);
public static final Gray _228 = new Gray(228);
public static final Gray _229 = new Gray(229);
public static final Gray _230 = new Gray(230);
public static final Gray _231 = new Gray(231);
public static final Gray _232 = new Gray(232);
public static final Gray _233 = new Gray(233);
public static final Gray _234 = new Gray(234);
public static final Gray _235 = new Gray(235);
public static final Gray _236 = new Gray(236);
public static final Gray _237 = new Gray(237);
public static final Gray _238 = new Gray(238);
public static final Gray _239 = new Gray(239);
public static final Gray _240 = new Gray(240);
public static final Gray _241 = new Gray(241);
public static final Gray _242 = new Gray(242);
public static final Gray _243 = new Gray(243);
public static final Gray _244 = new Gray(244);
public static final Gray _245 = new Gray(245);
public static final Gray _246 = new Gray(246);
public static final Gray _247 = new Gray(247);
public static final Gray _248 = new Gray(248);
public static final Gray _249 = new Gray(249);
public static final Gray _250 = new Gray(250);
public static final Gray _251 = new Gray(251);
public static final Gray _252 = new Gray(252);
public static final Gray _253 = new Gray(253);
public static final Gray _254 = new Gray(254);
public static final Gray _255 = new Gray(255);
public static final Gray x00 = _0;
public static final Gray x01 = _1;
public static final Gray x02 = _2;
public static final Gray x03 = _3;
public static final Gray x04 = _4;
public static final Gray x05 = _5;
public static final Gray x06 = _6;
public static final Gray x07 = _7;
public static final Gray x08 = _8;
public static final Gray x09 = _9;
public static final Gray x0A = _10;
public static final Gray x0B = _11;
public static final Gray x0C = _12;
public static final Gray x0D = _13;
public static final Gray x0E = _14;
public static final Gray x0F = _15;
public static final Gray x10 = _16;
public static final Gray x11 = _17;
public static final Gray x12 = _18;
public static final Gray x13 = _19;
public static final Gray x14 = _20;
public static final Gray x15 = _21;
public static final Gray x16 = _22;
public static final Gray x17 = _23;
public static final Gray x18 = _24;
public static final Gray x19 = _25;
public static final Gray x1A = _26;
public static final Gray x1B = _27;
public static final Gray x1C = _28;
public static final Gray x1D = _29;
public static final Gray x1E = _30;
public static final Gray x1F = _31;
public static final Gray x20 = _32;
public static final Gray x21 = _33;
public static final Gray x22 = _34;
public static final Gray x23 = _35;
public static final Gray x24 = _36;
public static final Gray x25 = _37;
public static final Gray x26 = _38;
public static final Gray x27 = _39;
public static final Gray x28 = _40;
public static final Gray x29 = _41;
public static final Gray x2A = _42;
public static final Gray x2B = _43;
public static final Gray x2C = _44;
public static final Gray x2D = _45;
public static final Gray x2E = _46;
public static final Gray x2F = _47;
public static final Gray x30 = _48;
public static final Gray x31 = _49;
public static final Gray x32 = _50;
public static final Gray x33 = _51;
public static final Gray x34 = _52;
public static final Gray x35 = _53;
public static final Gray x36 = _54;
public static final Gray x37 = _55;
public static final Gray x38 = _56;
public static final Gray x39 = _57;
public static final Gray x3A = _58;
public static final Gray x3B = _59;
public static final Gray x3C = _60;
public static final Gray x3D = _61;
public static final Gray x3E = _62;
public static final Gray x3F = _63;
public static final Gray x40 = _64;
public static final Gray x41 = _65;
public static final Gray x42 = _66;
public static final Gray x43 = _67;
public static final Gray x44 = _68;
public static final Gray x45 = _69;
public static final Gray x46 = _70;
public static final Gray x47 = _71;
public static final Gray x48 = _72;
public static final Gray x49 = _73;
public static final Gray x4A = _74;
public static final Gray x4B = _75;
public static final Gray x4C = _76;
public static final Gray x4D = _77;
public static final Gray x4E = _78;
public static final Gray x4F = _79;
public static final Gray x50 = _80;
public static final Gray x51 = _81;
public static final Gray x52 = _82;
public static final Gray x53 = _83;
public static final Gray x54 = _84;
public static final Gray x55 = _85;
public static final Gray x56 = _86;
public static final Gray x57 = _87;
public static final Gray x58 = _88;
public static final Gray x59 = _89;
public static final Gray x5A = _90;
public static final Gray x5B = _91;
public static final Gray x5C = _92;
public static final Gray x5D = _93;
public static final Gray x5E = _94;
public static final Gray x5F = _95;
public static final Gray x60 = _96;
public static final Gray x61 = _97;
public static final Gray x62 = _98;
public static final Gray x63 = _99;
public static final Gray x64 = _100;
public static final Gray x65 = _101;
public static final Gray x66 = _102;
public static final Gray x67 = _103;
public static final Gray x68 = _104;
public static final Gray x69 = _105;
public static final Gray x6A = _106;
public static final Gray x6B = _107;
public static final Gray x6C = _108;
public static final Gray x6D = _109;
public static final Gray x6E = _110;
public static final Gray x6F = _111;
public static final Gray x70 = _112;
public static final Gray x71 = _113;
public static final Gray x72 = _114;
public static final Gray x73 = _115;
public static final Gray x74 = _116;
public static final Gray x75 = _117;
public static final Gray x76 = _118;
public static final Gray x77 = _119;
public static final Gray x78 = _120;
public static final Gray x79 = _121;
public static final Gray x7A = _122;
public static final Gray x7B = _123;
public static final Gray x7C = _124;
public static final Gray x7D = _125;
public static final Gray x7E = _126;
public static final Gray x7F = _127;
public static final Gray x80 = _128;
public static final Gray x81 = _129;
public static final Gray x82 = _130;
public static final Gray x83 = _131;
public static final Gray x84 = _132;
public static final Gray x85 = _133;
public static final Gray x86 = _134;
public static final Gray x87 = _135;
public static final Gray x88 = _136;
public static final Gray x89 = _137;
public static final Gray x8A = _138;
public static final Gray x8B = _139;
public static final Gray x8C = _140;
public static final Gray x8D = _141;
public static final Gray x8E = _142;
public static final Gray x8F = _143;
public static final Gray x90 = _144;
public static final Gray x91 = _145;
public static final Gray x92 = _146;
public static final Gray x93 = _147;
public static final Gray x94 = _148;
public static final Gray x95 = _149;
public static final Gray x96 = _150;
public static final Gray x97 = _151;
public static final Gray x98 = _152;
public static final Gray x99 = _153;
public static final Gray x9A = _154;
public static final Gray x9B = _155;
public static final Gray x9C = _156;
public static final Gray x9D = _157;
public static final Gray x9E = _158;
public static final Gray x9F = _159;
public static final Gray xA0 = _160;
public static final Gray xA1 = _161;
public static final Gray xA2 = _162;
public static final Gray xA3 = _163;
public static final Gray xA4 = _164;
public static final Gray xA5 = _165;
public static final Gray xA6 = _166;
public static final Gray xA7 = _167;
public static final Gray xA8 = _168;
public static final Gray xA9 = _169;
public static final Gray xAA = _170;
public static final Gray xAB = _171;
public static final Gray xAC = _172;
public static final Gray xAD = _173;
public static final Gray xAE = _174;
public static final Gray xAF = _175;
public static final Gray xB0 = _176;
public static final Gray xB1 = _177;
public static final Gray xB2 = _178;
public static final Gray xB3 = _179;
public static final Gray xB4 = _180;
public static final Gray xB5 = _181;
public static final Gray xB6 = _182;
public static final Gray xB7 = _183;
public static final Gray xB8 = _184;
public static final Gray xB9 = _185;
public static final Gray xBA = _186;
public static final Gray xBB = _187;
public static final Gray xBC = _188;
public static final Gray xBD = _189;
public static final Gray xBE = _190;
public static final Gray xBF = _191;
public static final Gray xC0 = _192;
public static final Gray xC1 = _193;
public static final Gray xC2 = _194;
public static final Gray xC3 = _195;
public static final Gray xC4 = _196;
public static final Gray xC5 = _197;
public static final Gray xC6 = _198;
public static final Gray xC7 = _199;
public static final Gray xC8 = _200;
public static final Gray xC9 = _201;
public static final Gray xCA = _202;
public static final Gray xCB = _203;
public static final Gray xCC = _204;
public static final Gray xCD = _205;
public static final Gray xCE = _206;
public static final Gray xCF = _207;
public static final Gray xD0 = _208;
public static final Gray xD1 = _209;
public static final Gray xD2 = _210;
public static final Gray xD3 = _211;
public static final Gray xD4 = _212;
public static final Gray xD5 = _213;
public static final Gray xD6 = _214;
public static final Gray xD7 = _215;
public static final Gray xD8 = _216;
public static final Gray xD9 = _217;
public static final Gray xDA = _218;
public static final Gray xDB = _219;
public static final Gray xDC = _220;
public static final Gray xDD = _221;
public static final Gray xDE = _222;
public static final Gray xDF = _223;
public static final Gray xE0 = _224;
public static final Gray xE1 = _225;
public static final Gray xE2 = _226;
public static final Gray xE3 = _227;
public static final Gray xE4 = _228;
public static final Gray xE5 = _229;
public static final Gray xE6 = _230;
public static final Gray xE7 = _231;
public static final Gray xE8 = _232;
public static final Gray xE9 = _233;
public static final Gray xEA = _234;
public static final Gray xEB = _235;
public static final Gray xEC = _236;
public static final Gray xED = _237;
public static final Gray xEE = _238;
public static final Gray xEF = _239;
public static final Gray xF0 = _240;
public static final Gray xF1 = _241;
public static final Gray xF2 = _242;
public static final Gray xF3 = _243;
public static final Gray xF4 = _244;
public static final Gray xF5 = _245;
public static final Gray xF6 = _246;
public static final Gray xF7 = _247;
public static final Gray xF8 = _248;
public static final Gray xF9 = _249;
public static final Gray xFA = _250;
public static final Gray xFB = _251;
public static final Gray xFC = _252;
public static final Gray xFD = _253;
public static final Gray xFE = _254;
public static final Gray xFF = _255;
private static final Gray[] cache = {
_0, _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};
//public static void main(String[] args) {
// for (int i = 0; i < 256; i++) {
// System.out.println("public static final Gray _" + i + " = new Gray("+ i + ");");
// }
// for (int i = 0; i < 256; i++) {
// System.out.println("public static final Gray x" + (i < 16 ? "0" : "") + Integer.toHexString(i).toUpperCase() + " = _" + i + ";");
// }
//
// System.out.println();
// System.out.println("private static final Gray[] cache = {");
// System.out.print(" ");
// for (int i = 0; i < 256; i++) {
// System.out.print(String.format("%4s", "_" + String.valueOf(i)));
// if (i == 255) {
// System.out.println("};");
// } else {
// if (i % 16 == 15) {
// System.out.println(",");
// System.out.print(" ");
// } else {
// System.out.print(", ");
// }
// }
// }
//}
}

42
src/com/bulenkov/darcula/util/StringUtil.java

@ -0,0 +1,42 @@
package com.bulenkov.darcula.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class StringUtil {
public static List<String> split(String s, String separator) {
return split(s, separator, true);
}
public static List<String> split(String s, String separator,
boolean excludeSeparator) {
return split(s, separator, excludeSeparator, true);
}
public static List<String> split(String s, String separator,
boolean excludeSeparator, boolean excludeEmptyStrings) {
if (separator.isEmpty()) {
return Collections.singletonList(s);
}
List<String> result = new ArrayList<String>();
int pos = 0;
while (true) {
int index = s.indexOf(separator, pos);
if (index == -1) break;
final int nextPos = index + separator.length();
String token = s.substring(pos, excludeSeparator ? index : nextPos);
if (!token.isEmpty() || !excludeEmptyStrings) {
result.add(token);
}
pos = nextPos;
}
if (pos < s.length() || (!excludeEmptyStrings && pos == s.length())) {
result.add(s.substring(pos, s.length()));
}
return result;
}
}

39
src/com/bulenkov/darcula/util/UIUtil.java

@ -0,0 +1,39 @@
package com.bulenkov.darcula.util;
import javax.swing.*;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class UIUtil {
public static <T extends JComponent> T findComponentOfType(JComponent parent, Class<T> cls) {
if (parent == null || cls.isAssignableFrom(parent.getClass())) {
@SuppressWarnings({"unchecked"}) final T t = (T)parent;
return t;
}
for (Component component : parent.getComponents()) {
if (component instanceof JComponent) {
T comp = findComponentOfType((JComponent)component, cls);
if (comp != null) return comp;
}
}
return null;
}
public static <T> T getParentOfType(Class<? extends T> cls, Component c) {
Component eachParent = c;
while (eachParent != null) {
if (cls.isAssignableFrom(eachParent.getClass())) {
@SuppressWarnings({"unchecked"}) final T t = (T)eachParent;
return t;
}
eachParent = eachParent.getParent();
}
return null;
}
}

65
swingset2/AquaTheme.java

@ -0,0 +1,65 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)AquaTheme.java 1.7 03/01/23
*/
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
/**
* This class describes a theme using "blue-green" colors.
*
* 1.7 01/23/03
* @author Steve Wilson
*/
public class AquaTheme extends DefaultMetalTheme {
public String getName() { return "Aqua"; }
private final ColorUIResource primary1 = new ColorUIResource(102, 153, 153);
private final ColorUIResource primary2 = new ColorUIResource(128, 192, 192);
private final ColorUIResource primary3 = new ColorUIResource(159, 235, 235);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
}

342
swingset2/BezierAnimationPanel.java

@ -0,0 +1,342 @@
/*
* @(#)BezierAnimationPanel.java 1.16 05/11/17
*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* @(#)BezierAnimationPanel.java 1.16 05/11/17
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.event.*;
/**
* BezierAnimationPanel
*
* @version 1.16 11/17/05
* @author Jim Graham
* @author Jeff Dinkins (removed dynamic setting changes, made swing friendly)
*/
class BezierAnimationPanel extends JPanel implements Runnable {
Color backgroundColor = new Color(0, 0, 153);
Color outerColor = new Color(255, 255, 255);
Color gradientColorA = new Color(255, 0, 101);
Color gradientColorB = new Color(255, 255, 0);
boolean bgChanged = false;
GradientPaint gradient = null;
public final int NUMPTS = 6;
float animpts[] = new float[NUMPTS * 2];
float deltas[] = new float[NUMPTS * 2];
float staticpts[] = {
50.0f, 0.0f,
150.0f, 0.0f,
200.0f, 75.0f,
150.0f, 150.0f,
50.0f, 150.0f,
0.0f, 75.0f,
};
float movepts[] = new float[staticpts.length];
BufferedImage img;
Rectangle bounds = null;
Thread anim;
private final Object lock = new Object();
/**
* BezierAnimationPanel Constructor
*/
public BezierAnimationPanel() {
addHierarchyListener(
new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
if(isShowing()) {
start();
} else {
stop();
}
}
}
);
setBackground(getBackgroundColor());
}
public boolean isOpaque() {
return true;
}
public Color getGradientColorA() {
return gradientColorA;
}
public void setGradientColorA(Color c) {
if(c != null) {
gradientColorA = c;
}
}
public Color getGradientColorB() {
return gradientColorB;
}
public void setGradientColorB(Color c) {
if(c != null) {
gradientColorB = c;
}
}
public Color getOuterColor() {
return outerColor;
}
public void setOuterColor(Color c) {
if(c != null) {
outerColor = c;
}
}
public Color getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(Color c) {
if(c != null) {
backgroundColor = c;
setBackground(c);
bgChanged = true;
}
}
public void start() {
Dimension size = getSize();
for (int i = 0; i < animpts.length; i += 2) {
animpts[i + 0] = (float) (Math.random() * size.width);
animpts[i + 1] = (float) (Math.random() * size.height);
deltas[i + 0] = (float) (Math.random() * 4.0 + 2.0);
deltas[i + 1] = (float) (Math.random() * 4.0 + 2.0);
if (animpts[i + 0] > size.width / 6.0f) {
deltas[i + 0] = -deltas[i + 0];
}
if (animpts[i + 1] > size.height / 6.0f) {
deltas[i + 1] = -deltas[i + 1];
}
}
anim = new Thread(this);
anim.setPriority(Thread.MIN_PRIORITY);
anim.start();
}
public synchronized void stop() {
anim = null;
notify();
}
public void animate(float[] pts, float[] deltas, int index, int limit) {
float newpt = pts[index] + deltas[index];
if (newpt <= 0) {
newpt = -newpt;
deltas[index] = (float) (Math.random() * 3.0 + 2.0);
} else if (newpt >= (float) limit) {
newpt = 2.0f * limit - newpt;
deltas[index] = - (float) (Math.random() * 3.0 + 2.0);
}
pts[index] = newpt;
}
public void run() {
Thread me = Thread.currentThread();
while (getSize().width <= 0) {
try {
anim.sleep(500);
} catch (InterruptedException e) {
return;
}
}
Graphics2D g2d = null;
Graphics2D BufferG2D = null;
Graphics2D ScreenG2D = null;
BasicStroke solid = new BasicStroke(9.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 9.0f);
GeneralPath gp = new GeneralPath(GeneralPath.WIND_NON_ZERO);
int rule = AlphaComposite.SRC_OVER;
AlphaComposite opaque = AlphaComposite.SrcOver;
AlphaComposite blend = AlphaComposite.getInstance(rule, 0.9f);
AlphaComposite set = AlphaComposite.Src;
int frame = 0;
int frametmp = 0;
Dimension oldSize = getSize();
Shape clippath = null;
while (anim == me) {
Dimension size = getSize();
if (size.width != oldSize.width || size.height != oldSize.height) {
img = null;
clippath = null;
if (BufferG2D != null) {
BufferG2D.dispose();
BufferG2D = null;
}
if (ScreenG2D != null) {
ScreenG2D.dispose();
ScreenG2D = null;
}
}
oldSize = size;
if (img == null) {
img = (BufferedImage) createImage(size.width, size.height);
}
if (BufferG2D == null) {
BufferG2D = img.createGraphics();
BufferG2D.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_DEFAULT);
BufferG2D.setClip(clippath);
}
g2d = BufferG2D;
float[] ctrlpts;
for (int i = 0; i < animpts.length; i += 2) {
animate(animpts, deltas, i + 0, size.width);
animate(animpts, deltas, i + 1, size.height);
}
ctrlpts = animpts;
int len = ctrlpts.length;
gp.reset();
int dir = 0;
float prevx = ctrlpts[len - 2];
float prevy = ctrlpts[len - 1];
float curx = ctrlpts[0];
float cury = ctrlpts[1];
float midx = (curx + prevx) / 2.0f;
float midy = (cury + prevy) / 2.0f;
gp.moveTo(midx, midy);
for (int i = 2; i <= ctrlpts.length; i += 2) {
float x1 = (midx + curx) / 2.0f;
float y1 = (midy + cury) / 2.0f;
prevx = curx;
prevy = cury;
if (i < ctrlpts.length) {
curx = ctrlpts[i + 0];
cury = ctrlpts[i + 1];
} else {
curx = ctrlpts[0];
cury = ctrlpts[1];
}
midx = (curx + prevx) / 2.0f;
midy = (cury + prevy) / 2.0f;
float x2 = (prevx + midx) / 2.0f;
float y2 = (prevy + midy) / 2.0f;
gp.curveTo(x1, y1, x2, y2, midx, midy);
}
gp.closePath();
synchronized(lock) {
g2d.setComposite(set);
g2d.setBackground(backgroundColor);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
if(bgChanged || bounds == null) {
bounds = new Rectangle(0, 0, getWidth(), getHeight());
bgChanged = false;
}
// g2d.clearRect(bounds.x-5, bounds.y-5, bounds.x + bounds.width + 5, bounds.y + bounds.height + 5);
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(outerColor);
g2d.setComposite(opaque);
g2d.setStroke(solid);
g2d.draw(gp);
g2d.setPaint(gradient);
if(!bgChanged) {
bounds = gp.getBounds();
} else {
bounds = new Rectangle(0, 0, getWidth(), getHeight());
bgChanged = false;
}
gradient = new GradientPaint(bounds.x, bounds.y, gradientColorA,
bounds.x + bounds.width, bounds.y + bounds.height,
gradientColorB, true);
g2d.setComposite(blend);
g2d.fill(gp);
}
if (g2d == BufferG2D) {
repaint();
}
++frame;
Thread.yield();
}
if (g2d != null) {
g2d.dispose();
}
}
public void paint(Graphics g) {
synchronized (lock) {
Graphics2D g2d = (Graphics2D) g;
if (img != null) {
int imgw = img.getWidth();
int imgh = img.getHeight();
g2d.setComposite(AlphaComposite.Src);
g2d.drawImage(img, null, 0, 0);
}
}
}
}

555
swingset2/ButtonDemo.java

@ -0,0 +1,555 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ButtonDemo.java 1.10 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JButton, JRadioButton, JToggleButton, JCheckBox Demos
*
* @version 1.10 01/23/03
* @author Jeff Dinkins
*/
public class ButtonDemo extends DemoModule implements ChangeListener {
JTabbedPane tab;
JPanel buttonPanel = new JPanel();
JPanel checkboxPanel = new JPanel();
JPanel radioButtonPanel = new JPanel();
JPanel toggleButtonPanel = new JPanel();
Vector buttons = new Vector();
Vector checkboxes = new Vector();
Vector radiobuttons = new Vector();
Vector togglebuttons = new Vector();
Vector currentControls = buttons;
JButton button;
JCheckBox check;
JRadioButton radio;
JToggleButton toggle;
EmptyBorder border5 = new EmptyBorder(5,5,5,5);
EmptyBorder border10 = new EmptyBorder(10,10,10,10);
ItemListener buttonDisplayListener = null;
ItemListener buttonPadListener = null;
Insets insets0 = new Insets(0,0,0,0);
Insets insets10 = new Insets(10,10,10,10);
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ButtonDemo demo = new ButtonDemo(null);
demo.mainImpl();
}
/**
* ButtonDemo Constructor
*/
public ButtonDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "ButtonDemo", "toolbar/JButton.gif");
tab = new JTabbedPane();
tab.getModel().addChangeListener(this);
JPanel demo = getDemoPanel();
demo.setLayout(new BoxLayout(demo, BoxLayout.Y_AXIS));
demo.add(tab);
addButtons();
addRadioButtons();
addCheckBoxes();
// addToggleButtons();
currentControls = buttons;
}
public void addButtons() {
tab.addTab(getString("ButtonDemo.buttons"), buttonPanel);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.setBorder(border5);
JPanel p1 = createVerticalPanel(true);
p1.setAlignmentY(TOP_ALIGNMENT);
buttonPanel.add(p1);
// Text Buttons
JPanel p2 = createHorizontalPanel(false);
p1.add(p2);
p2.setBorder(new CompoundBorder(new TitledBorder(null, getString("ButtonDemo.textbuttons"),
TitledBorder.LEFT, TitledBorder.TOP), border5));
buttons.add(p2.add(new JButton(getString("ButtonDemo.button1"))));
p2.add(Box.createRigidArea(HGAP10));
buttons.add(p2.add(new JButton(getString("ButtonDemo.button2"))));
p2.add(Box.createRigidArea(HGAP10));
buttons.add(p2.add(new JButton(getString("ButtonDemo.button3"))));
// Image Buttons
p1.add(Box.createRigidArea(VGAP30));
JPanel p3 = createHorizontalPanel(false);
p1.add(p3);
p3.setLayout(new BoxLayout(p3, BoxLayout.X_AXIS));
p3.setBorder(new TitledBorder(null, getString("ButtonDemo.imagebuttons"),
TitledBorder.LEFT, TitledBorder.TOP));
// home image button
String description = getString("ButtonDemo.phone");
button = new JButton(createImageIcon("buttons/b1.gif", description));
button.setPressedIcon(createImageIcon("buttons/b1p.gif", description));
button.setRolloverIcon(createImageIcon("buttons/b1r.gif", description));
button.setDisabledIcon(createImageIcon("buttons/b1d.gif", description));
button.setMargin(new Insets(0,0,0,0));
p3.add(button);
buttons.add(button);
p3.add(Box.createRigidArea(HGAP10));
// write image button
description = getString("ButtonDemo.write");
button = new JButton(createImageIcon("buttons/b2.gif", description));
button.setPressedIcon(createImageIcon("buttons/b2p.gif", description));
button.setRolloverIcon(createImageIcon("buttons/b2r.gif", description));
button.setDisabledIcon(createImageIcon("buttons/b2d.gif", description));
button.setMargin(new Insets(0,0,0,0));
p3.add(button);
buttons.add(button);
p3.add(Box.createRigidArea(HGAP10));
// write image button
description = getString("ButtonDemo.peace");
button = new JButton(createImageIcon("buttons/b3.gif", description));
button.setPressedIcon(createImageIcon("buttons/b3p.gif", description));
button.setRolloverIcon(createImageIcon("buttons/b3r.gif", description));
button.setDisabledIcon(createImageIcon("buttons/b3d.gif", description));
button.setMargin(new Insets(0,0,0,0));
p3.add(button);
buttons.add(button);
p1.add(Box.createVerticalGlue());
buttonPanel.add(Box.createRigidArea(HGAP10));
currentControls = buttons;
buttonPanel.add(createControls());
}
public void addRadioButtons() {
ButtonGroup group = new ButtonGroup();
tab.addTab(getString("ButtonDemo.radiobuttons"), radioButtonPanel);
radioButtonPanel.setLayout(new BoxLayout(radioButtonPanel, BoxLayout.X_AXIS));
radioButtonPanel.setBorder(border5);
JPanel p1 = createVerticalPanel(true);
p1.setAlignmentY(TOP_ALIGNMENT);
radioButtonPanel.add(p1);
// Text Radio Buttons
JPanel p2 = createHorizontalPanel(false);
p1.add(p2);
p2.setBorder(new CompoundBorder(
new TitledBorder(
null, getString("ButtonDemo.textradiobuttons"),
TitledBorder.LEFT, TitledBorder.TOP), border5)
);
radio = (JRadioButton)p2.add(
new JRadioButton(getString("ButtonDemo.radio1")));
group.add(radio);
radiobuttons.add(radio);
p2.add(Box.createRigidArea(HGAP10));
radio = (JRadioButton)p2.add(
new JRadioButton(getString("ButtonDemo.radio2")));
group.add(radio);
radiobuttons.add(radio);
p2.add(Box.createRigidArea(HGAP10));
radio = (JRadioButton)p2.add(
new JRadioButton(getString("ButtonDemo.radio3")));
group.add(radio);
radiobuttons.add(radio);
// Image Radio Buttons
group = new ButtonGroup();
p1.add(Box.createRigidArea(VGAP30));
JPanel p3 = createHorizontalPanel(false);
p1.add(p3);
p3.setLayout(new BoxLayout(p3, BoxLayout.X_AXIS));
p3.setBorder(new TitledBorder(null, getString("ButtonDemo.imageradiobuttons"),
TitledBorder.LEFT, TitledBorder.TOP));
// image radio button 1
String description = getString("ButtonDemo.customradio");
String text = getString("ButtonDemo.radio1");
radio = new JRadioButton(text, createImageIcon("buttons/rb.gif", description));
radio.setPressedIcon(createImageIcon("buttons/rbp.gif", description));
radio.setRolloverIcon(createImageIcon("buttons/rbr.gif", description));
radio.setRolloverSelectedIcon(createImageIcon("buttons/rbrs.gif", description));
radio.setSelectedIcon(createImageIcon("buttons/rbs.gif", description));
radio.setMargin(new Insets(0,0,0,0));
group.add(radio);
p3.add(radio);
radiobuttons.add(radio);
p3.add(Box.createRigidArea(HGAP20));
// image radio button 2
text = getString("ButtonDemo.radio2");
radio = new JRadioButton(text, createImageIcon("buttons/rb.gif", description));
radio.setPressedIcon(createImageIcon("buttons/rbp.gif", description));
radio.setRolloverIcon(createImageIcon("buttons/rbr.gif", description));
radio.setRolloverSelectedIcon(createImageIcon("buttons/rbrs.gif", description));
radio.setSelectedIcon(createImageIcon("buttons/rbs.gif", description));
radio.setMargin(new Insets(0,0,0,0));
group.add(radio);
p3.add(radio);
radiobuttons.add(radio);
p3.add(Box.createRigidArea(HGAP20));
// image radio button 3
text = getString("ButtonDemo.radio3");
radio = new JRadioButton(text, createImageIcon("buttons/rb.gif", description));
radio.setPressedIcon(createImageIcon("buttons/rbp.gif", description));
radio.setRolloverIcon(createImageIcon("buttons/rbr.gif", description));
radio.setRolloverSelectedIcon(createImageIcon("buttons/rbrs.gif", description));
radio.setSelectedIcon(createImageIcon("buttons/rbs.gif", description));
radio.setMargin(new Insets(0,0,0,0));
group.add(radio);
radiobuttons.add(radio);
p3.add(radio);
// verticaly glue fills out the rest of the box
p1.add(Box.createVerticalGlue());
radioButtonPanel.add(Box.createRigidArea(HGAP10));
currentControls = radiobuttons;
radioButtonPanel.add(createControls());
}
public void addCheckBoxes() {
tab.addTab(getString("ButtonDemo.checkboxes"), checkboxPanel);
checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.X_AXIS));
checkboxPanel.setBorder(border5);
JPanel p1 = createVerticalPanel(true);
p1.setAlignmentY(TOP_ALIGNMENT);
checkboxPanel.add(p1);
// Text Radio Buttons
JPanel p2 = createHorizontalPanel(false);
p1.add(p2);
p2.setBorder(new CompoundBorder(
new TitledBorder(
null, getString("ButtonDemo.textcheckboxes"),
TitledBorder.LEFT, TitledBorder.TOP), border5)
);
checkboxes.add(p2.add(new JCheckBox(getString("ButtonDemo.check1"))));
p2.add(Box.createRigidArea(HGAP10));
checkboxes.add(p2.add(new JCheckBox(getString("ButtonDemo.check2"))));
p2.add(Box.createRigidArea(HGAP10));
checkboxes.add(p2.add(new JCheckBox(getString("ButtonDemo.check3"))));
// Image Radio Buttons
p1.add(Box.createRigidArea(VGAP30));
JPanel p3 = createHorizontalPanel(false);
p1.add(p3);
p3.setLayout(new BoxLayout(p3, BoxLayout.X_AXIS));
p3.setBorder(new TitledBorder(null, getString("ButtonDemo.imagecheckboxes"),
TitledBorder.LEFT, TitledBorder.TOP));
// image checkbox 1
String description = getString("ButtonDemo.customcheck");
String text = getString("ButtonDemo.check1");
check = new JCheckBox(text, createImageIcon("buttons/cb.gif", description));
check.setRolloverIcon(createImageIcon("buttons/cbr.gif", description));
check.setRolloverSelectedIcon(createImageIcon("buttons/cbrs.gif", description));
check.setSelectedIcon(createImageIcon("buttons/cbs.gif", description));
check.setMargin(new Insets(0,0,0,0));
p3.add(check);
checkboxes.add(check);
p3.add(Box.createRigidArea(HGAP20));
// image checkbox 2
text = getString("ButtonDemo.check2");
check = new JCheckBox(text, createImageIcon("buttons/cb.gif", description));
check.setRolloverIcon(createImageIcon("buttons/cbr.gif", description));
check.setRolloverSelectedIcon(createImageIcon("buttons/cbrs.gif", description));
check.setSelectedIcon(createImageIcon("buttons/cbs.gif", description));
check.setMargin(new Insets(0,0,0,0));
p3.add(check);
checkboxes.add(check);
p3.add(Box.createRigidArea(HGAP20));
// image checkbox 3
text = getString("ButtonDemo.check3");
check = new JCheckBox(text, createImageIcon("buttons/cb.gif", description));
check.setRolloverIcon(createImageIcon("buttons/cbr.gif", description));
check.setRolloverSelectedIcon(createImageIcon("buttons/cbrs.gif", description));
check.setSelectedIcon(createImageIcon("buttons/cbs.gif", description));
check.setMargin(new Insets(0,0,0,0));
p3.add(check);
checkboxes.add(check);
// verticaly glue fills out the rest of the box
p1.add(Box.createVerticalGlue());
checkboxPanel.add(Box.createRigidArea(HGAP10));
currentControls = checkboxes;
checkboxPanel.add(createControls());
}
public void addToggleButtons() {
tab.addTab(getString("ButtonDemo.togglebuttons"), toggleButtonPanel);
}
public JPanel createControls() {
JPanel controls = new JPanel() {
public Dimension getMaximumSize() {
return new Dimension(300, super.getMaximumSize().height);
}
};
controls.setLayout(new BoxLayout(controls, BoxLayout.Y_AXIS));
controls.setAlignmentY(TOP_ALIGNMENT);
controls.setAlignmentX(LEFT_ALIGNMENT);
JPanel buttonControls = createHorizontalPanel(true);
buttonControls.setAlignmentY(TOP_ALIGNMENT);
buttonControls.setAlignmentX(LEFT_ALIGNMENT);
JPanel leftColumn = createVerticalPanel(false);
leftColumn.setAlignmentX(LEFT_ALIGNMENT);
leftColumn.setAlignmentY(TOP_ALIGNMENT);
JPanel rightColumn = new LayoutControlPanel(this);
buttonControls.add(leftColumn);
buttonControls.add(Box.createRigidArea(HGAP20));
buttonControls.add(rightColumn);
buttonControls.add(Box.createRigidArea(HGAP20));
controls.add(buttonControls);
createListeners();
// Display Options
JLabel l = new JLabel("Display Options:");
leftColumn.add(l);
JCheckBox bordered = new JCheckBox("Paint Border");
bordered.setToolTipText("Click here to turn border painting on or off.");
bordered.setMnemonic('b');
if (currentControls == buttons) {
bordered.setSelected(true);
}
bordered.addItemListener(buttonDisplayListener);
leftColumn.add(bordered);
JCheckBox focused = new JCheckBox("Paint Focus");
focused.setToolTipText("Click here to turn focus painting on or off.");
focused.setMnemonic('f');
focused.setSelected(true);
focused.addItemListener(buttonDisplayListener);
leftColumn.add(focused);
JCheckBox enabled = new JCheckBox("Enabled");
enabled.setToolTipText("Click here to enable or disable the buttons.");
enabled.setSelected(true);
enabled.addItemListener(buttonDisplayListener);
enabled.setMnemonic('e');
leftColumn.add(enabled);
JCheckBox filled = new JCheckBox("Content Filled");
filled.setToolTipText("Click here to control the filling of the content area.");
filled.setSelected(true);
filled.addItemListener(buttonDisplayListener);
filled.setMnemonic('i');
leftColumn.add(filled);
leftColumn.add(Box.createRigidArea(VGAP20));
l = new JLabel("Pad Amount:");
leftColumn.add(l);
ButtonGroup group = new ButtonGroup();
JRadioButton defaultPad = new JRadioButton("Default");
defaultPad.setToolTipText("Uses the default padding between the border and label.");
defaultPad.setMnemonic('d');
defaultPad.addItemListener(buttonPadListener);
group.add(defaultPad);
defaultPad.setSelected(true);
leftColumn.add(defaultPad);
JRadioButton zeroPad = new JRadioButton("0");
zeroPad.setToolTipText("Uses no padding between the border and label.");
zeroPad.addItemListener(buttonPadListener);
zeroPad.setMnemonic('0');
group.add(zeroPad);
leftColumn.add(zeroPad);
JRadioButton tenPad = new JRadioButton("10");
tenPad.setMnemonic('1');
tenPad.setToolTipText("Uses a 10 pixel pad between the border and label.");
tenPad.addItemListener(buttonPadListener);
group.add(tenPad);
leftColumn.add(tenPad);
leftColumn.add(Box.createRigidArea(VGAP20));
return controls;
}
public void createListeners() {
buttonDisplayListener = new ItemListener() {
Component c;
AbstractButton b;
public void itemStateChanged(ItemEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
if(cb.getText().equals("Enabled")) {
for(int i = 0; i < currentControls.size(); i++) {
c = (Component) currentControls.elementAt(i);
c.setEnabled(cb.isSelected());
c.invalidate();
}
} else if(cb.getText().equals("Paint Border")) {
c = (Component) currentControls.elementAt(0);
if(c instanceof AbstractButton) {
for(int i = 0; i < currentControls.size(); i++) {
b = (AbstractButton) currentControls.elementAt(i);
b.setBorderPainted(cb.isSelected());
b.invalidate();
}
}
} else if(cb.getText().equals("Paint Focus")) {
c = (Component) currentControls.elementAt(0);
if(c instanceof AbstractButton) {
for(int i = 0; i < currentControls.size(); i++) {
b = (AbstractButton) currentControls.elementAt(i);
b.setFocusPainted(cb.isSelected());
b.invalidate();
}
}
} else if(cb.getText().equals("Content Filled")) {
c = (Component) currentControls.elementAt(0);
if(c instanceof AbstractButton) {
for(int i = 0; i < currentControls.size(); i++) {
b = (AbstractButton) currentControls.elementAt(i);
b.setContentAreaFilled(cb.isSelected());
b.invalidate();
}
}
}
invalidate();
validate();
repaint();
}
};
buttonPadListener = new ItemListener() {
Component c;
AbstractButton b;
public void itemStateChanged(ItemEvent e) {
// *** pad = 0
int pad = -1;
JRadioButton rb = (JRadioButton) e.getSource();
if(rb.getText().equals("0") && rb.isSelected()) {
pad = 0;
} else if(rb.getText().equals("10") && rb.isSelected()) {
pad = 10;
}
for(int i = 0; i < currentControls.size(); i++) {
b = (AbstractButton) currentControls.elementAt(i);
if(pad == -1) {
b.setMargin(null);
} else if(pad == 0) {
b.setMargin(insets0);
} else {
b.setMargin(insets10);
}
}
invalidate();
validate();
repaint();
}
};
}
public void stateChanged(ChangeEvent e) {
SingleSelectionModel model = (SingleSelectionModel) e.getSource();
if(model.getSelectedIndex() == 0) {
currentControls = buttons;
} else if(model.getSelectedIndex() == 1) {
currentControls = radiobuttons;
} else if(model.getSelectedIndex() == 2) {
currentControls = checkboxes;
} else {
currentControls = togglebuttons;
}
}
public Vector getCurrentControls() {
return currentControls;
}
}

79
swingset2/CharcoalTheme.java

@ -0,0 +1,79 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)CharcoalTheme.java 1.7 03/01/23
*/
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
/**
* This class describes a theme using gray colors.
*
* 1.7 01/23/03
* @author Steve Wilson
*/
public class CharcoalTheme extends DefaultMetalTheme {
public String getName() { return "Charcoal"; }
private final ColorUIResource primary1 = new ColorUIResource(66, 33, 66);
private final ColorUIResource primary2 = new ColorUIResource(90, 86, 99);
private final ColorUIResource primary3 = new ColorUIResource(99, 99, 99);
private final ColorUIResource secondary1 = new ColorUIResource(0, 0, 0);
private final ColorUIResource secondary2 = new ColorUIResource(51, 51, 51);
private final ColorUIResource secondary3 = new ColorUIResource(102, 102, 102);
private final ColorUIResource black = new ColorUIResource(222, 222, 222);
private final ColorUIResource white = new ColorUIResource(0, 0, 0);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
protected ColorUIResource getSecondary1() { return secondary1; }
protected ColorUIResource getSecondary2() { return secondary2; }
protected ColorUIResource getSecondary3() { return secondary3; }
protected ColorUIResource getBlack() { return black; }
protected ColorUIResource getWhite() { return white; }
}

419
swingset2/CodeViewer.java

@ -0,0 +1,419 @@
/**
* CodeViewer.java
*
* Bill Lynch & Matt Tucker
* CoolServlets.com, October 1999
*
* Please visit CoolServlets.com for high quality, open source Java servlets.
*
* Copyright (C) 1999 CoolServlets.com
*
* Any errors or suggested improvements to this class can be reported
* as instructed on Coolservlets.com. We hope you enjoy
* this program... your comments will encourage further development!
*
* This software is distributed under the terms of The BSD License.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither name of CoolServlets.com nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY COOLSERVLETS.COM AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL COOLSERVLETS.COM OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @(#)CodeViewer.java 1.6 02/06/13
*/
import java.io.*;
import java.util.*;
/**
* A class that syntax highlights Java code by turning it into html.
*
* <p> A <code>CodeViewer</code> object is created and then keeps state as
* lines are passed in. Each line passed in as java text, is returned as syntax
* highlighted html text.
*
* <p> Users of the class can set how the java code will be highlighted with
* setter methods.
*
* <p> Only valid java lines should be passed in since the object maintains
* state and may not handle illegal code gracefully.
*
* <p> The actual system is implemented as a series of filters that deal with
* specific portions of the java code. The filters are as follows:
*
* <pre>
* htmlFilter
* |__
* multiLineCommentFilter
* |___
* inlineCommentFilter
* |___
* stringFilter
* |__
* keywordFilter
* </pre>
*
* @version 1.6 06/13/02
* @author Bill Lynch, Matt Tucker, CoolServlets.com
*/
public class CodeViewer {
private static HashMap reservedWords = new HashMap(); // >= Java2 only (also, not thread-safe)
//private static Hashtable reservedWords = new Hashtable(); // < Java2 (thread-safe)
private boolean inMultiLineComment = false;
private String backgroundColor = "#ffffff";
private String commentStart = "</font><font size=2 color=\"#0000aa\"><i>";
private String commentEnd = "</font></i><font size=2 color=black>";
private String stringStart = "</font><font size=2 color=\"#00bb00\">";
private String stringEnd = "</font><font size=2 color=black>";
private String reservedWordStart = "<b>";
private String reservedWordEnd = "</b>";
static {
loadHash();
}
public CodeViewer() {
}
public void setCommentStart(String commentStart) {
this.commentStart = commentStart;
}
public void setCommentEnd(String commentEnd) {
this.commentEnd = commentEnd;
}
public void setStringStart(String stringStart) {
this.stringStart = stringStart;
}
public void setStringEnd(String stringEnd) {
this.stringEnd = stringEnd;
}
public void setReservedWordStart(String reservedWordStart) {
this.reservedWordStart = reservedWordStart;
}
public void setReservedWordEnd(String reservedWordEnd) {
this.reservedWordEnd = reservedWordEnd;
}
public String getCommentStart() {
return commentStart;
}
public String getCommentEnd() {
return commentEnd;
}
public String getStringStart() {
return stringStart;
}
public String getStringEnd() {
return stringEnd;
}
public String getReservedWordStart() {
return reservedWordStart;
}
public String getReservedWordEnd() {
return reservedWordEnd;
}
/**
* Passes off each line to the first filter.
* @param line The line of Java code to be highlighted.
*/
public String syntaxHighlight( String line ) {
return htmlFilter(line);
}
/*
* Filter html tags into more benign text.
*/
private String htmlFilter( String line ) {
if( line == null || line.equals("") ) {
return "";
}
// replace ampersands with HTML escape sequence for ampersand;
line = replace(line, "&", "&#38;");
// replace the \\ with HTML escape sequences. fixes a problem when
// backslashes preceed quotes.
line = replace(line, "\\\\", "&#92;&#92;" );
// replace \" sequences with HTML escape sequences;
line = replace(line, "" + (char)92 + (char)34, "&#92;&#34");
// replace less-than signs which might be confused
// by HTML as tag angle-brackets;
line = replace(line, "<", "&#60;");
// replace greater-than signs which might be confused
// by HTML as tag angle-brackets;
line = replace(line, ">", "&#62;");
return multiLineCommentFilter(line);
}
/*
* Filter out multiLine comments. State is kept with a private boolean
* variable.
*/
private String multiLineCommentFilter(String line) {
if (line == null || line.equals("")) {
return "";
}
StringBuffer buf = new StringBuffer();
int index;
//First, check for the end of a multi-line comment.
if (inMultiLineComment && (index = line.indexOf("*/")) > -1 && !isInsideString(line,index)) {
inMultiLineComment = false;
buf.append(line.substring(0,index));
buf.append("*/").append(commentEnd);
if (line.length() > index+2) {
buf.append(inlineCommentFilter(line.substring(index+2)));
}
return buf.toString();
}
//If there was no end detected and we're currently in a multi-line
//comment, we don't want to do anymore work, so return line.
else if (inMultiLineComment) {
return line;
}
//We're not currently in a comment, so check to see if the start
//of a multi-line comment is in this line.
else if ((index = line.indexOf("/*")) > -1 && !isInsideString(line,index)) {
inMultiLineComment = true;
//Return result of other filters + everything after the start
//of the multiline comment. We need to pass the through the
//to the multiLineComment filter again in case the comment ends
//on the same line.
buf.append(inlineCommentFilter(line.substring(0,index)));
buf.append(commentStart).append("/*");
buf.append(multiLineCommentFilter(line.substring(index+2)));
return buf.toString();
}
//Otherwise, no useful multi-line comment information was found so
//pass the line down to the next filter for processesing.
else {
return inlineCommentFilter(line);
}
}
/*
* Filter inline comments from a line and formats them properly.
*/
private String inlineCommentFilter(String line) {
if (line == null || line.equals("")) {
return "";
}
StringBuffer buf = new StringBuffer();
int index;
if ((index = line.indexOf("//")) > -1 && !isInsideString(line,index)) {
buf.append(stringFilter(line.substring(0,index)));
buf.append(commentStart);
buf.append(line.substring(index));
buf.append(commentEnd);
}
else {
buf.append(stringFilter(line));
}
return buf.toString();
}
/*
* Filters strings from a line of text and formats them properly.
*/
private String stringFilter(String line) {
if (line == null || line.equals("")) {
return "";
}
StringBuffer buf = new StringBuffer();
if (line.indexOf("\"") <= -1) {
return keywordFilter(line);
}
int start = 0;
int startStringIndex = -1;
int endStringIndex = -1;
int tempIndex;
//Keep moving through String characters until we want to stop...
while ((tempIndex = line.indexOf("\"")) > -1) {
//We found the beginning of a string
if (startStringIndex == -1) {
startStringIndex = 0;
buf.append( stringFilter(line.substring(start,tempIndex)) );
buf.append(stringStart).append("\"");
line = line.substring(tempIndex+1);
}
//Must be at the end
else {
startStringIndex = -1;
endStringIndex = tempIndex;
buf.append(line.substring(0,endStringIndex+1));
buf.append(stringEnd);
line = line.substring(endStringIndex+1);
}
}
buf.append( keywordFilter(line) );
return buf.toString();
}
/*
* Filters keywords from a line of text and formats them properly.
*/
private String keywordFilter( String line ) {
if( line == null || line.equals("") ) {
return "";
}
StringBuffer buf = new StringBuffer();
HashMap usedReservedWords = new HashMap(); // >= Java2 only (not thread-safe)
//Hashtable usedReservedWords = new Hashtable(); // < Java2 (thread-safe)
int i=0, startAt=0;
char ch;
StringBuffer temp = new StringBuffer();
while( i < line.length() ) {
temp.setLength(0);
ch = line.charAt(i);
startAt = i;
// 65-90, uppercase letters
// 97-122, lowercase letters
while( i<line.length() && ( ( ch >= 65 && ch <= 90 )
|| ( ch >= 97 && ch <= 122 ) ) ) {
temp.append(ch);
i++;
if( i < line.length() ) {
ch = line.charAt(i);
}
}
String tempString = temp.toString();
if( reservedWords.containsKey(tempString) && !usedReservedWords.containsKey(tempString)) {
usedReservedWords.put(tempString,tempString);
line = replace( line, tempString, (reservedWordStart+tempString+reservedWordEnd) );
i += (reservedWordStart.length() + reservedWordEnd.length());
}
else {
i++;
}
}
buf.append(line);
return buf.toString();
}
/*
* All important replace method. Replaces all occurences of oldString in
* line with newString.
*/
private String replace( String line, String oldString, String newString ) {
int i=0;
while( ( i=line.indexOf( oldString, i ) ) >= 0 ) {
line = (new StringBuffer().append(line.substring(0,i)).append(newString).append(line.substring(i+oldString.length()))).toString();
i += newString.length();
}
return line;
}
/*
* Checks to see if some position in a line is between String start and
* ending characters. Not yet used in code or fully working :)
*/
private boolean isInsideString(String line, int position) {
if (line.indexOf("\"") < 0) {
return false;
}
int index;
String left = line.substring(0,position);
String right = line.substring(position);
int leftCount = 0;
int rightCount = 0;
while ((index = left.indexOf("\"")) > -1) {
leftCount ++;
left = left.substring(index+1);
}
while ((index = right.indexOf("\"")) > -1) {
rightCount ++;
right = right.substring(index+1);
}
if (rightCount % 2 != 0 && leftCount % 2 != 0) {
return true;
}
else {
return false;
}
}
/*
* Load Hashtable (or HashMap) with Java reserved words.
*/
private static void loadHash() {
reservedWords.put( "abstract", "abstract" );
reservedWords.put( "do", "do" );
reservedWords.put( "inner", "inner" );
reservedWords.put( "public", "public" );
reservedWords.put( "var", "var" );
reservedWords.put( "boolean", "boolean" );
reservedWords.put( "continue", "continue" );
reservedWords.put( "int", "int" );
reservedWords.put( "return", "return" );
reservedWords.put( "void", "void" );
reservedWords.put( "break", "break" );
reservedWords.put( "else", "else" );
reservedWords.put( "interface", "interface" );
reservedWords.put( "short", "short" );
reservedWords.put( "volatile", "volatile" );
reservedWords.put( "byvalue", "byvalue" );
reservedWords.put( "extends", "extends" );
reservedWords.put( "long", "long" );
reservedWords.put( "static", "static" );
reservedWords.put( "while", "while" );
reservedWords.put( "case", "case" );
reservedWords.put( "final", "final" );
reservedWords.put( "naive", "naive" );
reservedWords.put( "super", "super" );
reservedWords.put( "transient", "transient" );
reservedWords.put( "cast", "cast" );
reservedWords.put( "float", "float" );
reservedWords.put( "new", "new" );
reservedWords.put( "rest", "rest" );
reservedWords.put( "catch", "catch" );
reservedWords.put( "for", "for" );
reservedWords.put( "null", "null" );
reservedWords.put( "synchronized", "synchronized" );
reservedWords.put( "char", "char" );
reservedWords.put( "finally", "finally" );
reservedWords.put( "operator", "operator" );
reservedWords.put( "this", "this" );
reservedWords.put( "class", "class" );
reservedWords.put( "generic", "generic" );
reservedWords.put( "outer", "outer" );
reservedWords.put( "switch", "switch" );
reservedWords.put( "const", "const" );
reservedWords.put( "goto", "goto" );
reservedWords.put( "package", "package" );
reservedWords.put( "throw", "throw" );
reservedWords.put( "double", "double" );
reservedWords.put( "if", "if" );
reservedWords.put( "private", "private" );
reservedWords.put( "true", "true" );
reservedWords.put( "default", "default" );
reservedWords.put( "import", "import" );
reservedWords.put( "protected", "protected" );
reservedWords.put( "try", "try" );
}
}

198
swingset2/ColorChooserDemo.java

@ -0,0 +1,198 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ColorChooserDemo.java 1.7 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JColorChooserDemo
*
* @version 1.1 07/16/99
* @author Jeff Dinkins
*/
public class ColorChooserDemo extends DemoModule {
BezierAnimationPanel bezAnim;
JButton outerColorButton = null;
JButton backgroundColorButton = null;
JButton gradientAButton = null;
JButton gradientBButton = null;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ColorChooserDemo demo = new ColorChooserDemo(null);
demo.mainImpl();
}
/**
* ColorChooserDemo Constructor
*/
public ColorChooserDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "ColorChooserDemo", "toolbar/JColorChooser.gif");
// Create the bezier animation panel to put in the center of the panel.
bezAnim = new BezierAnimationPanel();
outerColorButton = new JButton(getString("ColorChooserDemo.outer_line"));
outerColorButton.setIcon(new ColorSwatch("OuterLine", bezAnim));
backgroundColorButton = new JButton(getString("ColorChooserDemo.background"));
backgroundColorButton.setIcon(new ColorSwatch("Background", bezAnim));
gradientAButton = new JButton(getString("ColorChooserDemo.grad_a"));
gradientAButton.setIcon(new ColorSwatch("GradientA", bezAnim));
gradientBButton = new JButton(getString("ColorChooserDemo.grad_b"));
gradientBButton.setIcon(new ColorSwatch("GradientB", bezAnim));
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color current = bezAnim.getOuterColor();
if(e.getSource() == backgroundColorButton) {
current = bezAnim.getBackgroundColor();
} else if(e.getSource() == gradientAButton) {
current = bezAnim.getGradientColorA();
} else if(e.getSource() == gradientBButton) {
current = bezAnim.getGradientColorB();
}
// Bring up a color chooser
Color c = JColorChooser.showDialog(
getDemoPanel(),
getString("ColorChooserDemo.chooser_title"),
current
);
if(e.getSource() == outerColorButton) {
bezAnim.setOuterColor(c);
} else if(e.getSource() == backgroundColorButton) {
bezAnim.setBackgroundColor(c);
} else if(e.getSource() == gradientAButton) {
bezAnim.setGradientColorA(c);
} else {
bezAnim.setGradientColorB(c);
}
}
};
outerColorButton.addActionListener(l);
backgroundColorButton.addActionListener(l);
gradientAButton.addActionListener(l);
gradientBButton.addActionListener(l);
// Add everything to the panel
JPanel p = getDemoPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
// Add control buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(backgroundColorButton);
buttonPanel.add(Box.createRigidArea(new Dimension(15, 1)));
buttonPanel.add(gradientAButton);
buttonPanel.add(Box.createRigidArea(new Dimension(15, 1)));
buttonPanel.add(gradientBButton);
buttonPanel.add(Box.createRigidArea(new Dimension(15, 1)));
buttonPanel.add(outerColorButton);
// Add the panel midway down the panel
p.add(Box.createRigidArea(new Dimension(1, 10)));
p.add(buttonPanel);
p.add(Box.createRigidArea(new Dimension(1, 5)));
p.add(bezAnim);
}
class ColorSwatch implements Icon {
String gradient;
BezierAnimationPanel bez;
public ColorSwatch(String g, BezierAnimationPanel b) {
bez = b;
gradient = g;
}
public int getIconWidth() {
return 11;
}
public int getIconHeight() {
return 11;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.black);
g.fillRect(x, y, getIconWidth(), getIconHeight());
if(gradient.equals("GradientA")) {
g.setColor(bez.getGradientColorA());
} else if(gradient.equals("GradientB")) {
g.setColor(bez.getGradientColorB());
} else if(gradient.equals("Background")) {
g.setColor(bez.getBackgroundColor());
} else if(gradient.equals("OuterLine")) {
g.setColor(bez.getOuterColor());
}
g.fillRect(x+2, y+2, getIconWidth()-4, getIconHeight()-4);
}
}
}

409
swingset2/ComboBoxDemo.java

@ -0,0 +1,409 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ComboBoxDemo.java 1.10 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JComboBox Demo
*
* @version 1.10 01/23/03
* @author Jeff Dinkins
*/
public class ComboBoxDemo extends DemoModule implements ActionListener {
Face face;
JLabel faceLabel;
JComboBox hairCB;
JComboBox eyesCB;
JComboBox mouthCB;
JComboBox presetCB;
Hashtable parts = new Hashtable();
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ComboBoxDemo demo = new ComboBoxDemo(null);
demo.mainImpl();
}
/**
* ComboBoxDemo Constructor
*/
public ComboBoxDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "ComboBoxDemo", "toolbar/JComboBox.gif");
createComboBoxDemo();
}
public void createComboBoxDemo() {
JPanel demo = getDemoPanel();
JPanel demoPanel = getDemoPanel();
demoPanel.setLayout(new BoxLayout(demoPanel, BoxLayout.Y_AXIS));
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS));
demoPanel.add(Box.createRigidArea(VGAP20));
demoPanel.add(innerPanel);
demoPanel.add(Box.createRigidArea(VGAP20));
innerPanel.add(Box.createRigidArea(HGAP20));
// Create a panel to hold buttons
JPanel comboBoxPanel = new JPanel() {
public Dimension getMaximumSize() {
return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
}
};
comboBoxPanel.setLayout(new BoxLayout(comboBoxPanel, BoxLayout.Y_AXIS));
comboBoxPanel.add(Box.createRigidArea(VGAP15));
JLabel l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.presets")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
presetCB = (JComboBox) comboBoxPanel.add(createPresetComboBox());
presetCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(presetCB);
comboBoxPanel.add(Box.createRigidArea(VGAP30));
l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.hair_description")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
hairCB = (JComboBox) comboBoxPanel.add(createHairComboBox());
hairCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(hairCB);
comboBoxPanel.add(Box.createRigidArea(VGAP15));
l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.eyes_description")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
eyesCB = (JComboBox) comboBoxPanel.add(createEyesComboBox());
eyesCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(eyesCB);
comboBoxPanel.add(Box.createRigidArea(VGAP15));
l = (JLabel) comboBoxPanel.add(new JLabel(getString("ComboBoxDemo.mouth_description")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
mouthCB = (JComboBox) comboBoxPanel.add(createMouthComboBox());
mouthCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(mouthCB);
comboBoxPanel.add(Box.createRigidArea(VGAP15));
// Fill up the remaining space
comboBoxPanel.add(new JPanel(new BorderLayout()));
// Create and place the Face.
face = new Face();
JPanel facePanel = new JPanel();
facePanel.setLayout(new BorderLayout());
facePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
faceLabel = new JLabel(face);
facePanel.add(faceLabel, BorderLayout.CENTER);
// Indicate that the face panel is controlled by the hair, eyes and
// mouth combo boxes.
Object [] controlledByObjects = new Object[3];
controlledByObjects[0] = hairCB;
controlledByObjects[1] = eyesCB;
controlledByObjects[2] = mouthCB;
AccessibleRelation controlledByRelation =
new AccessibleRelation(AccessibleRelation.CONTROLLED_BY_PROPERTY,
controlledByObjects);
facePanel.getAccessibleContext().getAccessibleRelationSet().add(controlledByRelation);
// Indicate that the hair, eyes and mouth combo boxes are controllers
// for the face panel.
AccessibleRelation controllerForRelation =
new AccessibleRelation(AccessibleRelation.CONTROLLER_FOR_PROPERTY,
facePanel);
hairCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation);
eyesCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation);
mouthCB.getAccessibleContext().getAccessibleRelationSet().add(controllerForRelation);
// add buttons and image panels to inner panel
innerPanel.add(comboBoxPanel);
innerPanel.add(Box.createRigidArea(HGAP30));
innerPanel.add(facePanel);
innerPanel.add(Box.createRigidArea(HGAP20));
// load up the face parts
addFace("brent", getString("ComboBoxDemo.brent"));
addFace("georges", getString("ComboBoxDemo.georges"));
addFace("hans", getString("ComboBoxDemo.hans"));
addFace("howard", getString("ComboBoxDemo.howard"));
addFace("james", getString("ComboBoxDemo.james"));
addFace("jeff", getString("ComboBoxDemo.jeff"));
addFace("jon", getString("ComboBoxDemo.jon"));
addFace("lara", getString("ComboBoxDemo.lara"));
addFace("larry", getString("ComboBoxDemo.larry"));
addFace("lisa", getString("ComboBoxDemo.lisa"));
addFace("michael", getString("ComboBoxDemo.michael"));
addFace("philip", getString("ComboBoxDemo.philip"));
addFace("scott", getString("ComboBoxDemo.scott"));
// set the default face
presetCB.setSelectedIndex(0);
}
void addFace(String name, String i18n_name) {
ImageIcon i;
String i18n_hair = getString("ComboBoxDemo.hair");
String i18n_eyes = getString("ComboBoxDemo.eyes");
String i18n_mouth = getString("ComboBoxDemo.mouth");
parts.put(i18n_name, name); // i18n name lookup
parts.put(name, i18n_name); // reverse name lookup
i = createImageIcon("combobox/" + name + "hair.jpg", i18n_name + i18n_hair);
parts.put(name + "hair", i);
i = createImageIcon("combobox/" + name + "eyes.jpg", i18n_name + i18n_eyes);
parts.put(name + "eyes", i);
i = createImageIcon("combobox/" + name + "mouth.jpg", i18n_name + i18n_mouth);
parts.put(name + "mouth", i);
}
Face getFace() {
return face;
}
JComboBox createHairComboBox() {
JComboBox cb = new JComboBox();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
JComboBox createEyesComboBox() {
JComboBox cb = new JComboBox();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
JComboBox createNoseComboBox() {
JComboBox cb = new JComboBox();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
JComboBox createMouthComboBox() {
JComboBox cb = new JComboBox();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
JComboBox createPresetComboBox() {
JComboBox cb = new JComboBox();
cb.addItem(getString("ComboBoxDemo.preset1"));
cb.addItem(getString("ComboBoxDemo.preset2"));
cb.addItem(getString("ComboBoxDemo.preset3"));
cb.addItem(getString("ComboBoxDemo.preset4"));
cb.addItem(getString("ComboBoxDemo.preset5"));
cb.addItem(getString("ComboBoxDemo.preset6"));
cb.addItem(getString("ComboBoxDemo.preset7"));
cb.addItem(getString("ComboBoxDemo.preset8"));
cb.addItem(getString("ComboBoxDemo.preset9"));
cb.addItem(getString("ComboBoxDemo.preset10"));
cb.addActionListener(this);
return cb;
}
void fillComboBox(JComboBox cb) {
cb.addItem(getString("ComboBoxDemo.brent"));
cb.addItem(getString("ComboBoxDemo.georges"));
cb.addItem(getString("ComboBoxDemo.hans"));
cb.addItem(getString("ComboBoxDemo.howard"));
cb.addItem(getString("ComboBoxDemo.james"));
cb.addItem(getString("ComboBoxDemo.jeff"));
cb.addItem(getString("ComboBoxDemo.jon"));
cb.addItem(getString("ComboBoxDemo.lara"));
cb.addItem(getString("ComboBoxDemo.larry"));
cb.addItem(getString("ComboBoxDemo.lisa"));
cb.addItem(getString("ComboBoxDemo.michael"));
cb.addItem(getString("ComboBoxDemo.philip"));
cb.addItem(getString("ComboBoxDemo.scott"));
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == hairCB) {
String name = (String) parts.get((String) hairCB.getSelectedItem());
face.setHair((ImageIcon) parts.get(name + "hair"));
faceLabel.repaint();
} else if(e.getSource() == eyesCB) {
String name = (String) parts.get((String) eyesCB.getSelectedItem());
face.setEyes((ImageIcon) parts.get(name + "eyes"));
faceLabel.repaint();
} else if(e.getSource() == mouthCB) {
String name = (String) parts.get((String) mouthCB.getSelectedItem());
face.setMouth((ImageIcon) parts.get(name + "mouth"));
faceLabel.repaint();
} else if(e.getSource() == presetCB) {
String hair = null;
String eyes = null;
String mouth = null;
switch(presetCB.getSelectedIndex()) {
case 0:
hair = (String) parts.get("philip");
eyes = (String) parts.get("howard");
mouth = (String) parts.get("jeff");
break;
case 1:
hair = (String) parts.get("jeff");
eyes = (String) parts.get("larry");
mouth = (String) parts.get("philip");
break;
case 2:
hair = (String) parts.get("howard");
eyes = (String) parts.get("scott");
mouth = (String) parts.get("hans");
break;
case 3:
hair = (String) parts.get("philip");
eyes = (String) parts.get("jeff");
mouth = (String) parts.get("hans");
break;
case 4:
hair = (String) parts.get("brent");
eyes = (String) parts.get("jon");
mouth = (String) parts.get("scott");
break;
case 5:
hair = (String) parts.get("lara");
eyes = (String) parts.get("larry");
mouth = (String) parts.get("lisa");
break;
case 6:
hair = (String) parts.get("james");
eyes = (String) parts.get("philip");
mouth = (String) parts.get("michael");
break;
case 7:
hair = (String) parts.get("philip");
eyes = (String) parts.get("lisa");
mouth = (String) parts.get("brent");
break;
case 8:
hair = (String) parts.get("james");
eyes = (String) parts.get("philip");
mouth = (String) parts.get("jon");
break;
case 9:
hair = (String) parts.get("lara");
eyes = (String) parts.get("jon");
mouth = (String) parts.get("scott");
break;
}
if(hair != null) {
hairCB.setSelectedItem(hair);
eyesCB.setSelectedItem(eyes);
mouthCB.setSelectedItem(mouth);
faceLabel.repaint();
}
}
}
class Face implements Icon {
ImageIcon hair;
ImageIcon eyes;
ImageIcon mouth;
void setHair(ImageIcon i) {
hair = i;
}
void setEyes(ImageIcon i) {
eyes = i;
}
void setMouth(ImageIcon i) {
mouth = i;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
int height = y;
x = c.getWidth()/2 - getIconWidth()/2;
if(hair != null) {
hair.paintIcon(c, g, x, height); height += hair.getIconHeight();
}
if(eyes != null) {
eyes.paintIcon(c, g, x, height); height += eyes.getIconHeight();
}
if(mouth != null) {
mouth.paintIcon(c, g, x, height);
}
}
public int getIconWidth() {
return 344;
}
public int getIconHeight() {
return 455;
}
}
}

108
swingset2/ContrastTheme.java

@ -0,0 +1,108 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ContrastTheme.java 1.8 03/01/23
*/
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
/**
* This class describes a higher-contrast Metal Theme.
*
* @version 1.8 01/23/03
* @author Michael C. Albers
*/
public class ContrastTheme extends DefaultMetalTheme {
public String getName() { return "Contrast"; }
private final ColorUIResource primary1 = new ColorUIResource(0, 0, 0);
private final ColorUIResource primary2 = new ColorUIResource(204, 204, 204);
private final ColorUIResource primary3 = new ColorUIResource(255, 255, 255);
private final ColorUIResource primaryHighlight = new ColorUIResource(102,102,102);
private final ColorUIResource secondary2 = new ColorUIResource(204, 204, 204);
private final ColorUIResource secondary3 = new ColorUIResource(255, 255, 255);
private final ColorUIResource controlHighlight = new ColorUIResource(102,102,102);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
public ColorUIResource getPrimaryControlHighlight() { return primaryHighlight;}
protected ColorUIResource getSecondary2() { return secondary2; }
protected ColorUIResource getSecondary3() { return secondary3; }
public ColorUIResource getControlHighlight() { return super.getSecondary3(); }
public ColorUIResource getFocusColor() { return getBlack(); }
public ColorUIResource getTextHighlightColor() { return getBlack(); }
public ColorUIResource getHighlightedTextColor() { return getWhite(); }
public ColorUIResource getMenuSelectedBackground() { return getBlack(); }
public ColorUIResource getMenuSelectedForeground() { return getWhite(); }
public ColorUIResource getAcceleratorForeground() { return getBlack(); }
public ColorUIResource getAcceleratorSelectedForeground() { return getWhite(); }
public void addCustomEntriesToTable(UIDefaults table) {
Border blackLineBorder = new BorderUIResource(new LineBorder( getBlack() ));
Object textBorder = new BorderUIResource( new CompoundBorder(
blackLineBorder,
new BasicBorders.MarginBorder()));
table.put( "ToolTip.border", blackLineBorder);
table.put( "TitledBorder.border", blackLineBorder);
table.put( "TextField.border", textBorder);
table.put( "PasswordField.border", textBorder);
table.put( "TextArea.border", textBorder);
table.put( "TextPane.border", textBorder);
table.put( "EditorPane.border", textBorder);
}
}

248
swingset2/DemoModule.java

@ -0,0 +1,248 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)DemoModule.java 1.14 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* A generic SwingSet2 demo module
*
* @version 1.14 01/23/03
* @author Jeff Dinkins
*/
public class DemoModule extends JApplet {
// The preferred size of the demo
private int PREFERRED_WIDTH = 680;
private int PREFERRED_HEIGHT = 600;
Border loweredBorder = new CompoundBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED),
new EmptyBorder(5,5,5,5));
// Premade convenience dimensions, for use wherever you need 'em.
public static Dimension HGAP2 = new Dimension(2,1);
public static Dimension VGAP2 = new Dimension(1,2);
public static Dimension HGAP5 = new Dimension(5,1);
public static Dimension VGAP5 = new Dimension(1,5);
public static Dimension HGAP10 = new Dimension(10,1);
public static Dimension VGAP10 = new Dimension(1,10);
public static Dimension HGAP15 = new Dimension(15,1);
public static Dimension VGAP15 = new Dimension(1,15);
public static Dimension HGAP20 = new Dimension(20,1);
public static Dimension VGAP20 = new Dimension(1,20);
public static Dimension HGAP25 = new Dimension(25,1);
public static Dimension VGAP25 = new Dimension(1,25);
public static Dimension HGAP30 = new Dimension(30,1);
public static Dimension VGAP30 = new Dimension(1,30);
private SwingSet2 swingset = null;
private JPanel panel = null;
private String resourceName = null;
private String iconPath = null;
private String sourceCode = null;
// Resource bundle for internationalized and accessible text
private ResourceBundle bundle = null;
public DemoModule(SwingSet2 swingset) {
this(swingset, null, null);
}
public DemoModule(SwingSet2 swingset, String resourceName, String iconPath) {
panel = new JPanel();
panel.setLayout(new BorderLayout());
this.resourceName = resourceName;
this.iconPath = iconPath;
this.swingset = swingset;
loadSourceCode();
}
public String getResourceName() {
return resourceName;
}
public JPanel getDemoPanel() {
return panel;
}
public SwingSet2 getSwingSet2() {
return swingset;
}
public String getString(String key) {
String value = "nada";
if(bundle == null) {
if(getSwingSet2() != null) {
bundle = getSwingSet2().getResourceBundle();
} else {
bundle = ResourceBundle.getBundle("resources.swingset");
}
}
try {
value = bundle.getString(key);
} catch (MissingResourceException e) {
System.out.println("java.util.MissingResourceException: Couldn't find value for: " + key);
}
return value;
}
public char getMnemonic(String key) {
return (getString(key)).charAt(0);
}
public ImageIcon createImageIcon(String filename, String description) {
if(getSwingSet2() != null) {
return getSwingSet2().createImageIcon(filename, description);
} else {
String path = "/resources/images/" + filename;
return new ImageIcon(getClass().getResource(path), description);
}
}
public String getSourceCode() {
return sourceCode;
}
public void loadSourceCode() {
if(getResourceName() != null) {
String filename = "src/" + getResourceName() + ".java";
sourceCode = new String("<html><body bgcolor=\"#ffffff\"><pre>");
char[] buff = new char[50000];
InputStream is;
InputStreamReader isr;
CodeViewer cv = new CodeViewer();
URL url;
try {
url = getClass().getResource(filename);
is = url.openStream();
isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
// Read one line at a time, htmlize using super-spiffy
// html java code formating utility from www.CoolServlets.com
String line = reader.readLine();
while(line != null) {
sourceCode += cv.syntaxHighlight(line) + " \n ";
line = reader.readLine();
}
sourceCode += new String("</pre></body></html>");
} catch (Exception ex) {
sourceCode = "Could not load file: " + filename;
}
}
}
public String getName() {
return getString(getResourceName() + ".name");
};
public Icon getIcon() {
return createImageIcon(iconPath, getResourceName() + ".name");
};
public String getToolTip() {
return getString(getResourceName() + ".tooltip");
};
public void mainImpl() {
JFrame frame = new JFrame(getName());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(getDemoPanel(), BorderLayout.CENTER);
getDemoPanel().setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
frame.pack();
frame.show();
}
public JPanel createHorizontalPanel(boolean threeD) {
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setAlignmentY(TOP_ALIGNMENT);
p.setAlignmentX(LEFT_ALIGNMENT);
if(threeD) {
p.setBorder(loweredBorder);
}
return p;
}
public JPanel createVerticalPanel(boolean threeD) {
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setAlignmentY(TOP_ALIGNMENT);
p.setAlignmentX(LEFT_ALIGNMENT);
if(threeD) {
p.setBorder(loweredBorder);
}
return p;
}
public static void main(String[] args) {
DemoModule demo = new DemoModule(null);
demo.mainImpl();
}
public void init() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(getDemoPanel(), BorderLayout.CENTER);
}
}

167
swingset2/DirectionPanel.java

@ -0,0 +1,167 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)DirectionPanel.java 1.5 03/01/23
*/
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* @version 1.5 01/23/03
* @author Jeff Dinkins
* @author Chester Rose
* @author Brian Beck
*/
public class DirectionPanel extends JPanel {
private ButtonGroup group;
public DirectionPanel(boolean enable, String selection, ActionListener l) {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setAlignmentY(TOP_ALIGNMENT);
setAlignmentX(LEFT_ALIGNMENT);
Box firstThree = Box.createHorizontalBox();
Box secondThree = Box.createHorizontalBox();
Box thirdThree = Box.createHorizontalBox();
if(!enable) {
selection = "None";
}
group = new ButtonGroup();
DirectionButton b;
b = (DirectionButton) firstThree.add(new DirectionButton( tl_dot, tldn_dot, "NW", "Sets the orientation to the North-West", l, group, selection.equals("NW")));
b.setEnabled(enable);
b = (DirectionButton) firstThree.add(new DirectionButton( tm_dot, tmdn_dot, "N", "Sets the orientation to the North", l, group, selection.equals("N")));
b.setEnabled(enable);
b = (DirectionButton) firstThree.add(new DirectionButton( tr_dot, trdn_dot, "NE", "Sets the orientation to the North-East", l, group, selection.equals("NE")));
b.setEnabled(enable);
b = (DirectionButton) secondThree.add(new DirectionButton( ml_dot, mldn_dot, "W", "Sets the orientation to the West", l, group, selection.equals("W")));
b.setEnabled(enable);
b = (DirectionButton) secondThree.add(new DirectionButton( c_dot, cdn_dot, "C", "Sets the orientation to the Center", l, group, selection.equals("C")));
b.setEnabled(enable);
b = (DirectionButton) secondThree.add(new DirectionButton( mr_dot, mrdn_dot, "E", "Sets the orientation to the East", l, group, selection.equals("E")));
b.setEnabled(enable);
b = (DirectionButton) thirdThree.add(new DirectionButton( bl_dot, bldn_dot, "SW", "Sets the orientation to the South-West", l, group, selection.equals("SW")));
b.setEnabled(enable);
b = (DirectionButton) thirdThree.add(new DirectionButton( bm_dot, bmdn_dot, "S", "Sets the orientation to the South", l, group, selection.equals("S")));
b.setEnabled(enable);
b = (DirectionButton) thirdThree.add(new DirectionButton( br_dot, brdn_dot, "SE", "Sets the orientation to the South-East", l, group, selection.equals("SE")));
b.setEnabled(enable);
add(firstThree);
add(secondThree);
add(thirdThree);
}
public String getSelection() {
return group.getSelection().getActionCommand();
}
public void setSelection( String selection ) {
Enumeration e = group.getElements();
while( e.hasMoreElements() ) {
JRadioButton b = (JRadioButton)e.nextElement();
if( b.getActionCommand().equals(selection) ) {
b.setSelected(true);
}
}
}
// Chester's way cool layout buttons
public ImageIcon bl_dot = loadImageIcon("bl.gif","bottom left layout button");
public ImageIcon bldn_dot = loadImageIcon("bldn.gif","selected bottom left layout button");
public ImageIcon bm_dot = loadImageIcon("bm.gif","bottom middle layout button");
public ImageIcon bmdn_dot = loadImageIcon("bmdn.gif","selected bottom middle layout button");
public ImageIcon br_dot = loadImageIcon("br.gif","bottom right layout button");
public ImageIcon brdn_dot = loadImageIcon("brdn.gif","selected bottom right layout button");
public ImageIcon c_dot = loadImageIcon("c.gif","center layout button");
public ImageIcon cdn_dot = loadImageIcon("cdn.gif","selected center layout button");
public ImageIcon ml_dot = loadImageIcon("ml.gif","middle left layout button");
public ImageIcon mldn_dot = loadImageIcon("mldn.gif","selected middle left layout button");
public ImageIcon mr_dot = loadImageIcon("mr.gif","middle right layout button");
public ImageIcon mrdn_dot = loadImageIcon("mrdn.gif","selected middle right layout button");
public ImageIcon tl_dot = loadImageIcon("tl.gif","top left layout button");
public ImageIcon tldn_dot = loadImageIcon("tldn.gif","selected top left layout button");
public ImageIcon tm_dot = loadImageIcon("tm.gif","top middle layout button");
public ImageIcon tmdn_dot = loadImageIcon("tmdn.gif","selected top middle layout button");
public ImageIcon tr_dot = loadImageIcon("tr.gif","top right layout button");
public ImageIcon trdn_dot = loadImageIcon("trdn.gif","selected top right layout button");
public ImageIcon loadImageIcon(String filename, String description) {
String path = "/resources/images/buttons/" + filename;
return new ImageIcon(getClass().getResource(path), description);
}
public class DirectionButton extends JRadioButton {
/**
* A layout direction button
*/
public DirectionButton(Icon icon, Icon downIcon, String direction,
String description, ActionListener l,
ButtonGroup group, boolean selected)
{
super();
this.addActionListener(l);
setFocusPainted(false);
setHorizontalTextPosition(CENTER);
group.add(this);
setIcon(icon);
setSelectedIcon(downIcon);
setActionCommand(direction);
getAccessibleContext().setAccessibleName(direction);
getAccessibleContext().setAccessibleDescription(description);
setSelected(selected);
}
public boolean isFocusTraversable() {
return false;
}
public void setBorder(Border b) {
}
}
}

64
swingset2/EmeraldTheme.java

@ -0,0 +1,64 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)EmeraldTheme.java 1.7 03/01/23
*/
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
/**
* This class describes a theme using glowing green colors.
*
* @version 1.7 01/23/03
* @author Jeff Dinkins
*/
public class EmeraldTheme extends DefaultMetalTheme {
public String getName() { return "Emerald"; }
private final ColorUIResource primary1 = new ColorUIResource(51, 142, 71);
private final ColorUIResource primary2 = new ColorUIResource(102, 193, 122);
private final ColorUIResource primary3 = new ColorUIResource(153, 244, 173);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
}

273
swingset2/ExampleFileFilter.java

@ -0,0 +1,273 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ExampleFileFilter.java 1.6 03/01/23
*/
import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.filechooser.*;
/**
* A convenience implementation of FileFilter that filters out
* all files except for those type extensions that it knows about.
*
* Extensions are of the type ".foo", which is typically found on
* Windows and Unix boxes, but not on Macinthosh. Case is ignored.
*
* Example - create a new filter that filerts out all files
* but gif and jpg image files:
*
* JFileChooser chooser = new JFileChooser();
* ExampleFileFilter filter = new ExampleFileFilter(
* new String{"gif", "jpg"}, "JPEG & GIF Images")
* chooser.addChoosableFileFilter(filter);
* chooser.showOpenDialog(this);
*
* @version 1.6 01/23/03
* @author Jeff Dinkins
*/
public class ExampleFileFilter extends FileFilter {
private static String TYPE_UNKNOWN = "Type Unknown";
private static String HIDDEN_FILE = "Hidden File";
private Hashtable filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
/**
* Creates a file filter. If no filters are added, then all
* files are accepted.
*
* @see #addExtension
*/
public ExampleFileFilter() {
this.filters = new Hashtable();
}
/**
* Creates a file filter that accepts files with the given extension.
* Example: new ExampleFileFilter("jpg");
*
* @see #addExtension
*/
public ExampleFileFilter(String extension) {
this(extension,null);
}
/**
* Creates a file filter that accepts the given file type.
* Example: new ExampleFileFilter("jpg", "JPEG Image Images");
*
* Note that the "." before the extension is not needed. If
* provided, it will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String extension, String description) {
this();
if(extension!=null) addExtension(extension);
if(description!=null) setDescription(description);
}
/**
* Creates a file filter from the given string array.
* Example: new ExampleFileFilter(String {"gif", "jpg"});
*
* Note that the "." before the extension is not needed adn
* will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String[] filters) {
this(filters, null);
}
/**
* Creates a file filter from the given string array and description.
* Example: new ExampleFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
*
* Note that the "." before the extension is not needed and will be ignored.
*
* @see #addExtension
*/
public ExampleFileFilter(String[] filters, String description) {
this();
for (int i = 0; i < filters.length; i++) {
// add filters one by one
addExtension(filters[i]);
}
if(description!=null) setDescription(description);
}
/**
* Return true if this file should be shown in the directory pane,
* false if it shouldn't.
*
* Files that begin with "." are ignored.
*
* @see #getExtension
* @see FileFilter#accepts
*/
public boolean accept(File f) {
if(f != null) {
if(f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if(extension != null && filters.get(getExtension(f)) != null) {
return true;
};
}
return false;
}
/**
* Return the extension portion of the file's name .
*
* @see #getExtension
* @see FileFilter#accept
*/
public String getExtension(File f) {
if(f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
return filename.substring(i+1).toLowerCase();
};
}
return null;
}
/**
* Adds a filetype "dot" extension to filter against.
*
* For example: the following code will create a filter that filters
* out all files except those that end in ".jpg" and ".tif":
*
* ExampleFileFilter filter = new ExampleFileFilter();
* filter.addExtension("jpg");
* filter.addExtension("tif");
*
* Note that the "." before the extension is not needed and will be ignored.
*/
public void addExtension(String extension) {
if(filters == null) {
filters = new Hashtable(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
/**
* Returns the human readable description of this filter. For
* example: "JPEG and GIF Image Files (*.jpg, *.gif)"
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
* @see FileFilter#getDescription
*/
public String getDescription() {
if(fullDescription == null) {
if(description == null || isExtensionListInDescription()) {
fullDescription = description==null ? "(" : description + " (";
// build the description from the extension list
Enumeration extensions = filters.keys();
if(extensions != null) {
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", ." + (String) extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
/**
* Sets the human readable description of this filter. For
* example: filter.setDescription("Gif and JPG Images");
*
* @see setDescription
* @see setExtensionListInDescription
* @see isExtensionListInDescription
*/
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
/**
* Determines whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see isExtensionListInDescription
*/
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
/**
* Returns whether the extension list (.jpg, .gif, etc) should
* show up in the human readable description.
*
* Only relevent if a description was provided in the constructor
* or using setDescription();
*
* @see getDescription
* @see setDescription
* @see setExtensionListInDescription
*/
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}

200
swingset2/ExampleFileView.java

@ -0,0 +1,200 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ExampleFileView.java 1.6 03/01/23
*/
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.File;
import java.util.Hashtable;
/**
* A convenience implementation of the FileView interface that
* manages name, icon, traversable, and file type information.
*
* This this implemention will work well with file systems that use
* "dot" extensions to indicate file type. For example: "picture.gif"
* as a gif image.
*
* If the java.io.File ever contains some of this information, such as
* file type, icon, and hidden file inforation, this implementation may
* become obsolete. At minimum, it should be rewritten at that time to
* use any new type information provided by java.io.File
*
* Example:
* JFileChooser chooser = new JFileChooser();
* fileView = new ExampleFileView();
* fileView.putIcon("jpg", new ImageIcon("images/jpgIcon.jpg"));
* fileView.putIcon("gif", new ImageIcon("images/gifIcon.gif"));
* chooser.setFileView(fileView);
*
* @version 1.6 01/23/03
* @author Jeff Dinkins
*/
public class ExampleFileView extends FileView {
private Hashtable icons = new Hashtable(5);
private Hashtable fileDescriptions = new Hashtable(5);
private Hashtable typeDescriptions = new Hashtable(5);
/**
* The name of the file. Do nothing special here. Let
* the system file view handle this.
* @see #setName
* @see FileView#getName
*/
public String getName(File f) {
return null;
}
/**
* Adds a human readable description of the file.
*/
public void putDescription(File f, String fileDescription) {
fileDescriptions.put(fileDescription, f);
}
/**
* A human readable description of the file.
*
* @see FileView#getDescription
*/
public String getDescription(File f) {
return (String) fileDescriptions.get(f);
};
/**
* Adds a human readable type description for files. Based on "dot"
* extension strings, e.g: ".gif". Case is ignored.
*/
public void putTypeDescription(String extension, String typeDescription) {
typeDescriptions.put(typeDescription, extension);
}
/**
* Adds a human readable type description for files of the type of
* the passed in file. Based on "dot" extension strings, e.g: ".gif".
* Case is ignored.
*/
public void putTypeDescription(File f, String typeDescription) {
putTypeDescription(getExtension(f), typeDescription);
}
/**
* A human readable description of the type of the file.
*
* @see FileView#getTypeDescription
*/
public String getTypeDescription(File f) {
return (String) typeDescriptions.get(getExtension(f));
}
/**
* Conveinience method that returnsa the "dot" extension for the
* given file.
*/
public String getExtension(File f) {
String name = f.getName();
if(name != null) {
int extensionIndex = name.lastIndexOf('.');
if(extensionIndex < 0) {
return null;
}
return name.substring(extensionIndex+1).toLowerCase();
}
return null;
}
/**
* Adds an icon based on the file type "dot" extension
* string, e.g: ".gif". Case is ignored.
*/
public void putIcon(String extension, Icon icon) {
icons.put(extension, icon);
}
/**
* Icon that reperesents this file. Default implementation returns
* null. You might want to override this to return something more
* interesting.
*
* @see FileView#getIcon
*/
public Icon getIcon(File f) {
Icon icon = null;
String extension = getExtension(f);
if(extension != null) {
icon = (Icon) icons.get(extension);
}
return icon;
}
/**
* Whether the file is hidden or not. This implementation returns
* true if the filename starts with a "."
*
* @see FileView#isHidden
*/
public Boolean isHidden(File f) {
String name = f.getName();
if(name != null && !name.equals("") && name.charAt(0) == '.') {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
};
/**
* Whether the directory is traversable or not. Generic implementation
* returns true for all directories and special folders.
*
* You might want to subtype ExampleFileView to do somethimg more interesting,
* such as recognize compound documents directories; in such a case you might
* return a special icon for the diretory that makes it look like a regular
* document, and return false for isTraversable to not allow users to
* descend into the directory.
*
* @see FileView#isTraversable
*/
public Boolean isTraversable(File f) {
// if (some_reason) {
// return Boolean.FALSE;
// }
return null; // Use default from FileSystemView
};
}

421
swingset2/FileChooserDemo.java

@ -0,0 +1,421 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)FileChooserDemo.java 1.13 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JFileChooserDemo
*
* @version 1.1 07/16/99
* @author Jeff Dinkins
*/
public class FileChooserDemo extends DemoModule {
JLabel theImage;
Icon jpgIcon;
Icon gifIcon;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
FileChooserDemo demo = new FileChooserDemo(null);
demo.mainImpl();
}
/**
* FileChooserDemo Constructor
*/
public FileChooserDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "FileChooserDemo", "toolbar/JFileChooser.gif");
createFileChooserDemo();
}
public void createFileChooserDemo() {
theImage = new JLabel("");
jpgIcon = createImageIcon("filechooser/jpgIcon.jpg", "jpg image");
gifIcon = createImageIcon("filechooser/gifIcon.gif", "gif image");
JPanel demoPanel = getDemoPanel();
demoPanel.setLayout(new BoxLayout(demoPanel, BoxLayout.Y_AXIS));
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS));
demoPanel.add(Box.createRigidArea(VGAP20));
demoPanel.add(innerPanel);
demoPanel.add(Box.createRigidArea(VGAP20));
innerPanel.add(Box.createRigidArea(HGAP20));
// Create a panel to hold buttons
JPanel buttonPanel = new JPanel() {
public Dimension getMaximumSize() {
return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
}
};
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(Box.createRigidArea(VGAP15));
buttonPanel.add(createPlainFileChooserButton());
buttonPanel.add(Box.createRigidArea(VGAP15));
buttonPanel.add(createPreviewFileChooserButton());
buttonPanel.add(Box.createRigidArea(VGAP15));
buttonPanel.add(createCustomFileChooserButton());
buttonPanel.add(Box.createVerticalGlue());
// Create a panel to hold the image
JPanel imagePanel = new JPanel();
imagePanel.setLayout(new BorderLayout());
imagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
JScrollPane scroller = new JScrollPane(theImage);
scroller.getVerticalScrollBar().setUnitIncrement(10);
scroller.getHorizontalScrollBar().setUnitIncrement(10);
imagePanel.add(scroller, BorderLayout.CENTER);
// add buttons and image panels to inner panel
innerPanel.add(buttonPanel);
innerPanel.add(Box.createRigidArea(HGAP30));
innerPanel.add(imagePanel);
innerPanel.add(Box.createRigidArea(HGAP20));
}
public JFileChooser createFileChooser() {
// create a filechooser
JFileChooser fc = new JFileChooser();
// set the current directory to be the images directory
File swingFile = new File("resources/images/About.jpg");
if(swingFile.exists()) {
fc.setCurrentDirectory(swingFile);
fc.setSelectedFile(swingFile);
}
return fc;
}
public JButton createPlainFileChooserButton() {
Action a = new AbstractAction(getString("FileChooserDemo.plainbutton")) {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = createFileChooser();
// show the filechooser
int result = fc.showOpenDialog(getDemoPanel());
// if we selected an image, load the image
if(result == JFileChooser.APPROVE_OPTION) {
loadImage(fc.getSelectedFile().getPath());
}
}
};
return createButton(a);
}
public JButton createPreviewFileChooserButton() {
Action a = new AbstractAction(getString("FileChooserDemo.previewbutton")) {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = createFileChooser();
// Add filefilter & fileview
ExampleFileFilter filter = new ExampleFileFilter(
new String[] {"jpg", "gif"}, getString("FileChooserDemo.filterdescription")
);
ExampleFileView fileView = new ExampleFileView();
fileView.putIcon("jpg", jpgIcon);
fileView.putIcon("gif", gifIcon);
fc.setFileView(fileView);
fc.addChoosableFileFilter(filter);
fc.setFileFilter(filter);
// add preview accessory
fc.setAccessory(new FilePreviewer(fc));
// show the filechooser
int result = fc.showOpenDialog(getDemoPanel());
// if we selected an image, load the image
if(result == JFileChooser.APPROVE_OPTION) {
loadImage(fc.getSelectedFile().getPath());
}
}
};
return createButton(a);
}
JDialog dialog;
JFileChooser fc;
public JButton createCustomFileChooserButton() {
Action a = new AbstractAction(getString("FileChooserDemo.custombutton")) {
public void actionPerformed(ActionEvent e) {
fc = createFileChooser();
// Add filefilter & fileview
ExampleFileFilter filter = new ExampleFileFilter(
new String[] {"jpg", "gif"}, getString("FileChooserDemo.filterdescription")
);
ExampleFileView fileView = new ExampleFileView();
fileView.putIcon("jpg", jpgIcon);
fileView.putIcon("gif", gifIcon);
fc.setFileView(fileView);
fc.addChoosableFileFilter(filter);
// add preview accessory
fc.setAccessory(new FilePreviewer(fc));
// remove the approve/cancel buttons
fc.setControlButtonsAreShown(false);
// make custom controls
//wokka
JPanel custom = new JPanel();
custom.setLayout(new BoxLayout(custom, BoxLayout.Y_AXIS));
custom.add(Box.createRigidArea(VGAP10));
JLabel description = new JLabel(getString("FileChooserDemo.description"));
description.setAlignmentX(JLabel.CENTER_ALIGNMENT);
custom.add(description);
custom.add(Box.createRigidArea(VGAP10));
custom.add(fc);
Action okAction = createOKAction();
fc.addActionListener(okAction);
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
buttons.add(Box.createRigidArea(HGAP10));
buttons.add(createImageButton(createFindAction()));
buttons.add(Box.createRigidArea(HGAP10));
buttons.add(createButton(createAboutAction()));
buttons.add(Box.createRigidArea(HGAP10));
buttons.add(createButton(okAction));
buttons.add(Box.createRigidArea(HGAP10));
buttons.add(createButton(createCancelAction()));
buttons.add(Box.createRigidArea(HGAP10));
buttons.add(createImageButton(createHelpAction()));
buttons.add(Box.createRigidArea(HGAP10));
custom.add(buttons);
custom.add(Box.createRigidArea(VGAP10));
// show the filechooser
Frame parent = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, getDemoPanel());
dialog = new JDialog(parent, getString("FileChooserDemo.dialogtitle"), true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.getContentPane().add(custom, BorderLayout.CENTER);
dialog.pack();
dialog.setLocationRelativeTo(getDemoPanel());
dialog.show();
}
};
return createButton(a);
}
public Action createAboutAction() {
return new AbstractAction(getString("FileChooserDemo.about")) {
public void actionPerformed(ActionEvent e) {
File file = fc.getSelectedFile();
String text;
if(file == null) {
text = getString("FileChooserDemo.nofileselected");
} else {
text = "<html>" + getString("FileChooserDemo.thefile");
text += "<br><font color=green>" + file.getName() + "</font><br>";
text += getString("FileChooserDemo.isprobably") + "</html>";
}
JOptionPane.showMessageDialog(getDemoPanel(), text);
}
};
}
public Action createOKAction() {
return new AbstractAction(getString("FileChooserDemo.ok")) {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
if (!e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)
&& fc.getSelectedFile() != null) {
loadImage(fc.getSelectedFile().getPath());
}
}
};
}
public Action createCancelAction() {
return new AbstractAction(getString("FileChooserDemo.cancel")) {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
};
}
public Action createFindAction() {
Icon icon = createImageIcon("filechooser/find.gif", getString("FileChooserDemo.find"));
return new AbstractAction("", icon) {
public void actionPerformed(ActionEvent e) {
String result = JOptionPane.showInputDialog(getDemoPanel(), getString("FileChooserDemo.findquestion"));
if (result != null) {
JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.findresponse"));
}
}
};
}
public Action createHelpAction() {
Icon icon = createImageIcon("filechooser/help.gif", getString("FileChooserDemo.help"));
return new AbstractAction("", icon) {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.helptext"));
}
};
}
class MyImageIcon extends ImageIcon {
public MyImageIcon(String filename) {
super(filename);
};
public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.white);
g.fillRect(0,0, c.getWidth(), c.getHeight());
if(getImageObserver() == null) {
g.drawImage(
getImage(),
c.getWidth()/2 - getIconWidth()/2,
c.getHeight()/2 - getIconHeight()/2,
c
);
} else {
g.drawImage(
getImage(),
c.getWidth()/2 - getIconWidth()/2,
c.getHeight()/2 - getIconHeight()/2,
getImageObserver()
);
}
}
}
public void loadImage(String filename) {
theImage.setIcon(new MyImageIcon(filename));
}
public JButton createButton(Action a) {
JButton b = new JButton(a) {
public Dimension getMaximumSize() {
int width = Short.MAX_VALUE;
int height = super.getMaximumSize().height;
return new Dimension(width, height);
}
};
return b;
}
public JButton createImageButton(Action a) {
JButton b = new JButton(a);
b.setMargin(new Insets(0,0,0,0));
return b;
}
}
class FilePreviewer extends JComponent implements PropertyChangeListener {
ImageIcon thumbnail = null;
public FilePreviewer(JFileChooser fc) {
setPreferredSize(new Dimension(100, 50));
fc.addPropertyChangeListener(this);
setBorder(new BevelBorder(BevelBorder.LOWERED));
}
public void loadImage(File f) {
if (f == null) {
thumbnail = null;
} else {
ImageIcon tmpIcon = new ImageIcon(f.getPath());
if(tmpIcon.getIconWidth() > 90) {
thumbnail = new ImageIcon(
tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
} else {
thumbnail = tmpIcon;
}
}
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if(prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
if(isShowing()) {
loadImage((File) e.getNewValue());
repaint();
}
}
}
public void paint(Graphics g) {
super.paint(g);
if(thumbnail != null) {
int x = getWidth()/2 - thumbnail.getIconWidth()/2;
int y = getHeight()/2 - thumbnail.getIconHeight()/2;
if(y < 0) {
y = 0;
}
if(x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
}
}
}

133
swingset2/HtmlDemo.java

@ -0,0 +1,133 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)HtmlDemo.java 1.8 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* Html Demo
*
* @version 1.8 03/01/23
* @author Jeff Dinkins
*/
public class HtmlDemo extends DemoModule {
JEditorPane html;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
HtmlDemo demo = new HtmlDemo(null);
demo.mainImpl();
}
/**
* HtmlDemo Constructor
*/
public HtmlDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "HtmlDemo", "toolbar/JEditorPane.gif");
try {
URL url = null;
// System.getProperty("user.dir") +
// System.getProperty("file.separator");
String path = null;
try {
path = "/resources/index.html";
url = getClass().getResource(path);
} catch (Exception e) {
System.err.println("Failed to open " + path);
url = null;
}
if(url != null) {
html = new JEditorPane(url);
html.setEditable(false);
html.addHyperlinkListener(createHyperLinkListener());
JScrollPane scroller = new JScrollPane();
JViewport vp = scroller.getViewport();
vp.add(html);
getDemoPanel().add(scroller, BorderLayout.CENTER);
}
} catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e);
} catch (IOException e) {
System.out.println("IOException: " + e);
}
}
public HyperlinkListener createHyperLinkListener() {
return new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (e instanceof HTMLFrameHyperlinkEvent) {
((HTMLDocument)html.getDocument()).processHTMLFrameHyperlinkEvent(
(HTMLFrameHyperlinkEvent)e);
} else {
try {
html.setPage(e.getURL());
} catch (IOException ioe) {
System.out.println("IOE: " + ioe);
}
}
}
}
};
}
}

331
swingset2/InternalFrameDemo.java

@ -0,0 +1,331 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)InternalFrameDemo.java 1.10 03/01/23
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* Internal Frames Demo
*
* @version 1.10 01/23/03
* @author Jeff Dinkins
*/
public class InternalFrameDemo extends DemoModule {
int windowCount = 0;
JDesktopPane desktop = null;
ImageIcon icon1, icon2, icon3, icon4;
ImageIcon smIcon1, smIcon2, smIcon3, smIcon4;
public Integer FIRST_FRAME_LAYER = new Integer(1);
public Integer DEMO_FRAME_LAYER = new Integer(2);
public Integer PALETTE_LAYER = new Integer(3);
public int FRAME0_X = 15;
public int FRAME0_Y = 280;
public int FRAME0_WIDTH = 320;
public int FRAME0_HEIGHT = 230;
public int FRAME_WIDTH = 225;
public int FRAME_HEIGHT = 150;
public int PALETTE_X = 375;
public int PALETTE_Y = 20;
public int PALETTE_WIDTH = 260;
public int PALETTE_HEIGHT = 230;
JCheckBox windowResizable = null;
JCheckBox windowClosable = null;
JCheckBox windowIconifiable = null;
JCheckBox windowMaximizable = null;
JTextField windowTitleField = null;
JLabel windowTitleLabel = null;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
InternalFrameDemo demo = new InternalFrameDemo(null);
demo.mainImpl();
}
/**
* InternalFrameDemo Constructor
*/
public InternalFrameDemo(SwingSet2 swingset) {
super(swingset, "InternalFrameDemo", "toolbar/JDesktop.gif");
// preload all the icons we need for this demo
icon1 = createImageIcon("ImageClub/misc/fish.gif", getString("InternalFrameDemo.fish"));
icon2 = createImageIcon("ImageClub/misc/moon.gif", getString("InternalFrameDemo.moon"));
icon3 = createImageIcon("ImageClub/misc/sun.gif", getString("InternalFrameDemo.sun"));
icon4 = createImageIcon("ImageClub/misc/cab.gif", getString("InternalFrameDemo.cab"));
smIcon1 = createImageIcon("ImageClub/misc/fish_small.gif", getString("InternalFrameDemo.fish"));
smIcon2 = createImageIcon("ImageClub/misc/moon_small.gif", getString("InternalFrameDemo.moon"));
smIcon3 = createImageIcon("ImageClub/misc/sun_small.gif", getString("InternalFrameDemo.sun"));
smIcon4 = createImageIcon("ImageClub/misc/cab_small.gif", getString("InternalFrameDemo.cab"));
// Create the desktop pane
desktop = new JDesktopPane();
getDemoPanel().add(desktop, BorderLayout.CENTER);
// Create the "frame maker" palette
createInternalFramePalette();
// Create an initial internal frame to show
JInternalFrame frame1 = createInternalFrame(icon1, FIRST_FRAME_LAYER, 1, 1);
frame1.setBounds(FRAME0_X, FRAME0_Y, FRAME0_WIDTH, FRAME0_HEIGHT);
// Create four more starter windows
createInternalFrame(icon1, DEMO_FRAME_LAYER, FRAME_WIDTH, FRAME_HEIGHT);
createInternalFrame(icon3, DEMO_FRAME_LAYER, FRAME_WIDTH, FRAME_HEIGHT);
createInternalFrame(icon4, DEMO_FRAME_LAYER, FRAME_WIDTH, FRAME_HEIGHT);
createInternalFrame(icon2, DEMO_FRAME_LAYER, FRAME_WIDTH, FRAME_HEIGHT);
}
/**
* Create an internal frame and add a scrollable imageicon to it
*/
public JInternalFrame createInternalFrame(Icon icon, Integer layer, int width, int height) {
JInternalFrame jif = new JInternalFrame();
if(!windowTitleField.getText().equals(getString("InternalFrameDemo.frame_label"))) {
jif.setTitle(windowTitleField.getText() + " ");
} else {
jif = new JInternalFrame(getString("InternalFrameDemo.frame_label") + " " + windowCount + " ");
}
// set properties
jif.setClosable(windowClosable.isSelected());
jif.setMaximizable(windowMaximizable.isSelected());
jif.setIconifiable(windowIconifiable.isSelected());
jif.setResizable(windowResizable.isSelected());
jif.setBounds(20*(windowCount%10), 20*(windowCount%10), width, height);
jif.setContentPane(new ImageScroller(this, icon, 0, windowCount));
windowCount++;
desktop.add(jif, layer);
// Set this internal frame to be selected
try {
jif.setSelected(true);
} catch (java.beans.PropertyVetoException e2) {
}
jif.show();
return jif;
}
public JInternalFrame createInternalFramePalette() {
JInternalFrame palette = new JInternalFrame(
getString("InternalFrameDemo.palette_label")
);
palette.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE);
palette.getContentPane().setLayout(new BorderLayout());
palette.setBounds(PALETTE_X, PALETTE_Y, PALETTE_WIDTH, PALETTE_HEIGHT);
palette.setResizable(true);
palette.setIconifiable(true);
desktop.add(palette, PALETTE_LAYER);
// *************************************
// * Create create frame maker buttons *
// *************************************
JButton b1 = new JButton(smIcon1);
JButton b2 = new JButton(smIcon2);
JButton b3 = new JButton(smIcon3);
JButton b4 = new JButton(smIcon4);
// add frame maker actions
b1.addActionListener(new ShowFrameAction(this, icon1));
b2.addActionListener(new ShowFrameAction(this, icon2));
b3.addActionListener(new ShowFrameAction(this, icon3));
b4.addActionListener(new ShowFrameAction(this, icon4));
// add frame maker buttons to panel
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
JPanel buttons1 = new JPanel();
buttons1.setLayout(new BoxLayout(buttons1, BoxLayout.X_AXIS));
JPanel buttons2 = new JPanel();
buttons2.setLayout(new BoxLayout(buttons2, BoxLayout.X_AXIS));
buttons1.add(b1);
buttons1.add(Box.createRigidArea(HGAP15));
buttons1.add(b2);
buttons2.add(b3);
buttons2.add(Box.createRigidArea(HGAP15));
buttons2.add(b4);
p.add(Box.createRigidArea(VGAP10));
p.add(buttons1);
p.add(Box.createRigidArea(VGAP15));
p.add(buttons2);
p.add(Box.createRigidArea(VGAP10));
palette.getContentPane().add(p, BorderLayout.NORTH);
// ************************************
// * Create frame property checkboxes *
// ************************************
p = new JPanel() {
Insets insets = new Insets(10,15,10,5);
public Insets getInsets() {
return insets;
}
};
p.setLayout(new GridLayout(1,2));
Box box = new Box(BoxLayout.Y_AXIS);
windowResizable = new JCheckBox(getString("InternalFrameDemo.resizable_label"), true);
windowIconifiable = new JCheckBox(getString("InternalFrameDemo.iconifiable_label"), true);
box.add(windowResizable);
box.add(windowIconifiable);
p.add(box);
box = new Box(BoxLayout.Y_AXIS);
windowClosable = new JCheckBox(getString("InternalFrameDemo.closable_label"), true);
windowMaximizable = new JCheckBox(getString("InternalFrameDemo.maximizable_label"), true);
box.add(windowClosable);
box.add(windowMaximizable);
p.add(box);
palette.getContentPane().add(p, BorderLayout.CENTER);
// ************************************
// * Create Frame title textfield *
// ************************************
p = new JPanel() {
Insets insets = new Insets(0,0,10,0);
public Insets getInsets() {
return insets;
}
};
windowTitleField = new JTextField(getString("InternalFrameDemo.frame_label"));
windowTitleLabel = new JLabel(getString("InternalFrameDemo.title_text_field_label"));
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(Box.createRigidArea(HGAP5));
p.add(windowTitleLabel, BorderLayout.WEST);
p.add(Box.createRigidArea(HGAP5));
p.add(windowTitleField, BorderLayout.CENTER);
p.add(Box.createRigidArea(HGAP5));
palette.getContentPane().add(p, BorderLayout.SOUTH);
palette.show();
return palette;
}
class ShowFrameAction extends AbstractAction {
InternalFrameDemo demo;
Icon icon;
public ShowFrameAction(InternalFrameDemo demo, Icon icon) {
this.demo = demo;
this.icon = icon;
}
public void actionPerformed(ActionEvent e) {
demo.createInternalFrame(icon,
getDemoFrameLayer(),
getFrameWidth(),
getFrameHeight()
);
}
}
public int getFrameWidth() {
return FRAME_WIDTH;
}
public int getFrameHeight() {
return FRAME_HEIGHT;
}
public Integer getDemoFrameLayer() {
return DEMO_FRAME_LAYER;
}
class ImageScroller extends JScrollPane {
public ImageScroller(InternalFrameDemo demo, Icon icon, int layer, int count) {
super();
JPanel p = new JPanel();
p.setBackground(Color.white);
p.setLayout(new BorderLayout() );
p.add(new JLabel(icon), BorderLayout.CENTER);
getViewport().add(p);
getHorizontalScrollBar().setUnitIncrement(10);
getVerticalScrollBar().setUnitIncrement(10);
}
public Dimension getMinimumSize() {
return new Dimension(25, 25);
}
}
}

341
swingset2/LayoutControlPanel.java

@ -0,0 +1,341 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)LayoutControlPanel.java 1.6 03/01/23
*/
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/*
* The LayoutControlPanel contains controls for setting an
* AbstractButton's horizontal and vertical text position and
* horizontal and vertical alignment.
*/
public class LayoutControlPanel extends JPanel implements SwingConstants {
private boolean absolutePositions;
private DirectionPanel textPosition = null;
private DirectionPanel labelAlignment = null;
private ButtonDemo demo = null;
// private ComponentOrientChanger componentOrientChanger = null;
LayoutControlPanel(ButtonDemo demo) {
this.demo = demo;
// this.componentOrientationChanger = componentOrientationChanger;
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setAlignmentX(LEFT_ALIGNMENT);
setAlignmentY(TOP_ALIGNMENT);
JLabel l;
// If SwingSet has a ComponentOrientationChanger, then include control
// for choosing between absolute and relative positioning. This will
// only happen when we're running on JDK 1.2 or above.
//
// if(componentOrientationChanger != null ) {
// l = new JLabel("Positioning:");
// add(l);
//
// ButtonGroup group = new ButtonGroup();
// PositioningListener positioningListener = new PositioningListener();
// JRadioButton absolutePos = new JRadioButton("Absolute");
// absolutePos.setMnemonic('a');
// absolutePos.setToolTipText("Text/Content positioning is independant of line direction");
// group.add(absolutePos);
// absolutePos.addItemListener(positioningListener);
// add(absolutePos);
//
// JRadioButton relativePos = new JRadioButton("Relative");
// relativePos.setMnemonic('r');
// relativePos.setToolTipText("Text/Content positioning depends on line direction.");
// group.add(relativePos);
// relativePos.addItemListener(positioningListener);
// add(relativePos);
//
// add(Box.createRigidArea(demo.VGAP20));
//
// absolutePositions = false;
// relativePos.setSelected(true);
//
// componentOrientationChanger.addActionListener( new OrientationChangeListener() );
//} else {
absolutePositions = true;
//}
textPosition = new DirectionPanel(true, "E", new TextPositionListener());
labelAlignment = new DirectionPanel(true, "C", new LabelAlignmentListener());
// Make sure the controls' text position and label alignment match
// the initial value of the associated direction panel.
for(int i = 0; i < demo.getCurrentControls().size(); i++) {
Component c = (Component) demo.getCurrentControls().elementAt(i);
setPosition(c, RIGHT, CENTER);
setAlignment(c,CENTER,CENTER);
}
l = new JLabel("Text Position:");
add(l);
add(textPosition);
add(Box.createRigidArea(demo.VGAP20));
l = new JLabel("Content Alignment:");
add(l);
add(labelAlignment);
add(Box.createGlue());
}
class OrientationChangeListener implements ActionListener {
public void actionPerformed( ActionEvent e ) {
if( !e.getActionCommand().equals("OrientationChanged") ){
return;
}
if( absolutePositions ){
return;
}
String currentTextPosition = textPosition.getSelection();
if( currentTextPosition.equals("NW") )
textPosition.setSelection("NE");
else if( currentTextPosition.equals("NE") )
textPosition.setSelection("NW");
else if( currentTextPosition.equals("E") )
textPosition.setSelection("W");
else if( currentTextPosition.equals("W") )
textPosition.setSelection("E");
else if( currentTextPosition.equals("SE") )
textPosition.setSelection("SW");
else if( currentTextPosition.equals("SW") )
textPosition.setSelection("SE");
String currentLabelAlignment = labelAlignment.getSelection();
if( currentLabelAlignment.equals("NW") )
labelAlignment.setSelection("NE");
else if( currentLabelAlignment.equals("NE") )
labelAlignment.setSelection("NW");
else if( currentLabelAlignment.equals("E") )
labelAlignment.setSelection("W");
else if( currentLabelAlignment.equals("W") )
labelAlignment.setSelection("E");
else if( currentLabelAlignment.equals("SE") )
labelAlignment.setSelection("SW");
else if( currentLabelAlignment.equals("SW") )
labelAlignment.setSelection("SE");
}
}
class PositioningListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JRadioButton rb = (JRadioButton) e.getSource();
if(rb.getText().equals("Absolute") && rb.isSelected()) {
absolutePositions = true;
} else if(rb.getText().equals("Relative") && rb.isSelected()) {
absolutePositions = false;
}
for(int i = 0; i < demo.getCurrentControls().size(); i++) {
Component c = (Component) demo.getCurrentControls().elementAt(i);
int hPos, vPos, hAlign, vAlign;
if( c instanceof AbstractButton ) {
hPos = ((AbstractButton)c).getHorizontalTextPosition();
vPos = ((AbstractButton)c).getVerticalTextPosition();
hAlign = ((AbstractButton)c).getHorizontalAlignment();
vAlign = ((AbstractButton)c).getVerticalAlignment();
} else if( c instanceof JLabel ) {
hPos = ((JLabel)c).getHorizontalTextPosition();
vPos = ((JLabel)c).getVerticalTextPosition();
hAlign = ((JLabel)c).getHorizontalAlignment();
vAlign = ((JLabel)c).getVerticalAlignment();
} else {
continue;
}
setPosition(c, hPos, vPos);
setAlignment(c, hAlign, vAlign);
}
demo.invalidate();
demo.validate();
demo.repaint();
}
};
// Text Position Listener
class TextPositionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JRadioButton rb = (JRadioButton) e.getSource();
if(!rb.isSelected()) {
return;
}
String cmd = rb.getActionCommand();
int hPos, vPos;
if(cmd.equals("NW")) {
hPos = LEFT; vPos = TOP;
} else if(cmd.equals("N")) {
hPos = CENTER; vPos = TOP;
} else if(cmd.equals("NE")) {
hPos = RIGHT; vPos = TOP;
} else if(cmd.equals("W")) {
hPos = LEFT; vPos = CENTER;
} else if(cmd.equals("C")) {
hPos = CENTER; vPos = CENTER;
} else if(cmd.equals("E")) {
hPos = RIGHT; vPos = CENTER;
} else if(cmd.equals("SW")) {
hPos = LEFT; vPos = BOTTOM;
} else if(cmd.equals("S")) {
hPos = CENTER; vPos = BOTTOM;
} else /*if(cmd.equals("SE"))*/ {
hPos = RIGHT; vPos = BOTTOM;
}
for(int i = 0; i < demo.getCurrentControls().size(); i++) {
Component c = (Component) demo.getCurrentControls().elementAt(i);
setPosition(c, hPos, vPos);
}
demo.invalidate();
demo.validate();
demo.repaint();
}
};
// Label Alignment Listener
class LabelAlignmentListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JRadioButton rb = (JRadioButton) e.getSource();
if(!rb.isSelected()) {
return;
}
String cmd = rb.getActionCommand();
int hPos, vPos;
if(cmd.equals("NW")) {
hPos = LEFT; vPos = TOP;
} else if(cmd.equals("N")) {
hPos = CENTER; vPos = TOP;
} else if(cmd.equals("NE")) {
hPos = RIGHT; vPos = TOP;
} else if(cmd.equals("W")) {
hPos = LEFT; vPos = CENTER;
} else if(cmd.equals("C")) {
hPos = CENTER; vPos = CENTER;
} else if(cmd.equals("E")) {
hPos = RIGHT; vPos = CENTER;
} else if(cmd.equals("SW")) {
hPos = LEFT; vPos = BOTTOM;
} else if(cmd.equals("S")) {
hPos = CENTER; vPos = BOTTOM;
} else /*if(cmd.equals("SE"))*/ {
hPos = RIGHT; vPos = BOTTOM;
}
for(int i = 0; i < demo.getCurrentControls().size(); i++) {
Component c = (Component) demo.getCurrentControls().elementAt(i);
setAlignment(c,hPos,vPos);
c.invalidate();
}
demo.invalidate();
demo.validate();
demo.repaint();
}
};
// Position
void setPosition(Component c, int hPos, int vPos) {
boolean ltr = true;
ltr = c.getComponentOrientation().isLeftToRight();
if( absolutePositions ) {
if( hPos == LEADING ) {
hPos = ltr ? LEFT : RIGHT;
} else if( hPos == TRAILING ) {
hPos = ltr ? RIGHT : LEFT;
}
} else {
if( hPos == LEFT ) {
hPos = ltr ? LEADING : TRAILING;
} else if( hPos == RIGHT ) {
hPos = ltr ? TRAILING : LEADING;
}
}
if(c instanceof AbstractButton) {
AbstractButton x = (AbstractButton) c;
x.setHorizontalTextPosition(hPos);
x.setVerticalTextPosition(vPos);
} else if(c instanceof JLabel) {
JLabel x = (JLabel) c;
x.setHorizontalTextPosition(hPos);
x.setVerticalTextPosition(vPos);
}
}
void setAlignment(Component c, int hPos, int vPos) {
boolean ltr = true;
ltr = c.getComponentOrientation().isLeftToRight();
if( absolutePositions ) {
if( hPos == LEADING ) {
hPos = ltr ? LEFT : RIGHT;
} else if( hPos == TRAILING ) {
hPos = ltr ? RIGHT : LEFT;
}
} else {
if( hPos == LEFT ) {
hPos = ltr ? LEADING : TRAILING;
} else if( hPos == RIGHT ) {
hPos = ltr ? TRAILING : LEADING;
}
}
if(c instanceof AbstractButton) {
AbstractButton x = (AbstractButton) c;
x.setHorizontalAlignment(hPos);
x.setVerticalAlignment(vPos);
} else if(c instanceof JLabel) {
JLabel x = (JLabel) c;
x.setHorizontalAlignment(hPos);
x.setVerticalAlignment(vPos);
}
}
}

378
swingset2/ListDemo.java

@ -0,0 +1,378 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ListDemo.java 1.11 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* List Demo. This demo shows that it is not
* always necessary to have an array of objects
* as big as the size of the list stored.
*
* Indeed, in this example, there is no array
* kept for the list data, rather it is generated
* on the fly as only those elements are needed.
*
* @version 1.11 01/23/03
* @author Jeff Dinkins
*/
public class ListDemo extends DemoModule {
JList list;
JPanel prefixList;
JPanel suffixList;
Action prefixAction;
Action suffixAction;
GeneratedListModel listModel;
Vector checkboxes = new Vector();
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ListDemo demo = new ListDemo(null);
demo.mainImpl();
}
/**
* ListDemo Constructor
*/
public ListDemo(SwingSet2 swingset) {
super(swingset, "ListDemo", "toolbar/JList.gif");
loadImages();
JLabel description = new JLabel(getString("ListDemo.description"));
getDemoPanel().add(description, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
centerPanel.add(Box.createRigidArea(HGAP10));
getDemoPanel().add(centerPanel, BorderLayout.CENTER);
JPanel listPanel = new JPanel();
listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.Y_AXIS));
listPanel.add(Box.createRigidArea(VGAP10));
centerPanel.add(listPanel);
centerPanel.add(Box.createRigidArea(HGAP30));
// Create the list
list = new JList();
list.setCellRenderer(new CompanyLogoListCellRenderer());
listModel = new GeneratedListModel(this);
list.setModel(listModel);
// Set the preferred row count. This affects the preferredSize
// of the JList when it's in a scrollpane.
list.setVisibleRowCount(22);
// Add list to a scrollpane
JScrollPane scrollPane = new JScrollPane(list);
listPanel.add(scrollPane);
listPanel.add(Box.createRigidArea(VGAP10));
// Add the control panel (holds the prefix/suffix list and prefix/suffix checkboxes)
JPanel controlPanel = createControlPanel();
centerPanel.add(createControlPanel());
// create prefixes and suffixes
addPrefix("Tera", true);
addPrefix("Micro", false);
addPrefix("Southern", false);
addPrefix("Net", true);
addPrefix("YoYo", true);
addPrefix("Northern", false);
addPrefix("Tele", false);
addPrefix("Eastern", false);
addPrefix("Neo", false);
addPrefix("Digi", false);
addPrefix("National", false);
addPrefix("Compu", true);
addPrefix("Meta", true);
addPrefix("Info", false);
addPrefix("Western", false);
addPrefix("Data", false);
addPrefix("Atlantic", false);
addPrefix("Advanced", false);
addPrefix("Euro", false);
addPrefix("Pacific", false);
addPrefix("Mobile", false);
addPrefix("In", false);
addPrefix("Computa", false);
addPrefix("Digital", false);
addPrefix("Analog", false);
addSuffix("Tech", true);
addSuffix("Soft", true);
addSuffix("Telecom", true);
addSuffix("Solutions", false);
addSuffix("Works", true);
addSuffix("Dyne", false);
addSuffix("Services", false);
addSuffix("Vers", false);
addSuffix("Devices", false);
addSuffix("Software", false);
addSuffix("Serv", false);
addSuffix("Systems", true);
addSuffix("Dynamics", true);
addSuffix("Net", false);
addSuffix("Sys", false);
addSuffix("Computing", false);
addSuffix("Scape", false);
addSuffix("Com", false);
addSuffix("Ware", false);
addSuffix("Widgets", false);
addSuffix("Media", false);
addSuffix("Computer", false);
addSuffix("Hardware", false);
addSuffix("Gizmos", false);
addSuffix("Concepts", false);
}
public JPanel createControlPanel() {
JPanel controlPanel = new JPanel() {
Insets insets = new Insets(0, 4, 10, 10);
public Insets getInsets() {
return insets;
}
};
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS));
JPanel prefixPanel = new JPanel();
prefixPanel.setLayout(new BoxLayout(prefixPanel, BoxLayout.Y_AXIS));
prefixPanel.add(new JLabel(getString("ListDemo.prefixes")));
JPanel suffixPanel = new JPanel();
suffixPanel.setLayout(new BoxLayout(suffixPanel, BoxLayout.Y_AXIS));
suffixPanel.add(new JLabel(getString("ListDemo.suffixes")));
prefixList = new JPanel() {
Insets insets = new Insets(0, 4, 0, 0);
public Insets getInsets() {
return insets;
}
};
prefixList.setLayout(new BoxLayout(prefixList, BoxLayout.Y_AXIS));
JScrollPane scrollPane = new JScrollPane(prefixList);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
prefixPanel.add(scrollPane);
prefixPanel.add(Box.createRigidArea(HGAP10));
suffixList = new JPanel() {
Insets insets = new Insets(0, 4, 0, 0);
public Insets getInsets() {
return insets;
}
};
suffixList.setLayout(new BoxLayout(suffixList, BoxLayout.Y_AXIS));
scrollPane = new JScrollPane(suffixList);
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
suffixPanel.add(scrollPane);
suffixPanel.add(Box.createRigidArea(HGAP10));
controlPanel.add(prefixPanel);
controlPanel.add(Box.createRigidArea(HGAP15));
controlPanel.add(suffixPanel);
return controlPanel;
}
public void addPrefix(String prefix, boolean selected) {
if(prefixAction == null) {
prefixAction = new UpdatePrefixListAction(listModel);
}
JCheckBox cb = (JCheckBox) prefixList.add(new JCheckBox(prefix));
checkboxes.addElement(cb);
cb.setSelected(selected);
cb.addActionListener(prefixAction);
if(selected) {
listModel.addPrefix(prefix);
}
}
public void addSuffix(String suffix, boolean selected) {
if(suffixAction == null) {
suffixAction = new UpdateSuffixListAction(listModel);
}
JCheckBox cb = (JCheckBox) suffixList.add(new JCheckBox(suffix));
checkboxes.addElement(cb);
cb.setSelected(selected);
cb.addActionListener(suffixAction);
if(selected) {
listModel.addSuffix(suffix);
}
}
class UpdatePrefixListAction extends AbstractAction {
GeneratedListModel listModel;
protected UpdatePrefixListAction(GeneratedListModel listModel) {
this.listModel = listModel;
}
public void actionPerformed(ActionEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
if(cb.isSelected()) {
listModel.addPrefix(cb.getText());
} else {
listModel.removePrefix(cb.getText());
}
}
}
class UpdateSuffixListAction extends AbstractAction {
GeneratedListModel listModel;
protected UpdateSuffixListAction(GeneratedListModel listModel) {
this.listModel = listModel;
}
public void actionPerformed(ActionEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
if(cb.isSelected()) {
listModel.addSuffix(cb.getText());
} else {
listModel.removeSuffix(cb.getText());
}
}
}
class GeneratedListModel extends AbstractListModel {
ListDemo demo;
Permuter permuter;
public Vector prefix = new Vector();
public Vector suffix = new Vector();
public GeneratedListModel (ListDemo demo) {
this.demo = demo;
}
private void update() {
permuter = new Permuter(getSize());
fireContentsChanged(this, 0, getSize());
}
public void addPrefix(String s) {
if(!prefix.contains(s)) {
prefix.addElement(s);
update();
}
}
public void removePrefix(String s) {
prefix.removeElement(s);
update();
}
public void addSuffix(String s) {
if(!suffix.contains(s)) {
suffix.addElement(s);
update();
}
}
public void removeSuffix(String s) {
suffix.removeElement(s);
update();
}
public int getSize() {
return prefix.size() * suffix.size();
}
public Object getElementAt(int index) {
if(permuter == null) {
update();
}
// morph the index to another int -- this has the benefit of
// causing the list to look random.
int j = permuter.map(index);
int ps = prefix.size();
int ss = suffix.size();
return (String) prefix.elementAt(j%ps) + (String) suffix.elementAt((j/ps)%ss);
}
}
ImageIcon images[] = new ImageIcon[7];
void loadImages() {
images[0] = createImageIcon("list/red.gif", getString("ListDemo.red"));
images[1] = createImageIcon("list/blue.gif", getString("ListDemo.blue"));
images[2] = createImageIcon("list/yellow.gif", getString("ListDemo.yellow"));
images[3] = createImageIcon("list/green.gif", getString("ListDemo.green"));
images[4] = createImageIcon("list/gray.gif", getString("ListDemo.gray"));
images[5] = createImageIcon("list/cyan.gif", getString("ListDemo.cyan"));
images[6] = createImageIcon("list/magenta.gif", getString("ListDemo.magenta"));
}
class CompanyLogoListCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
Component retValue = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus
);
setIcon(images[index%7]);
return retValue;
}
}
}

235
swingset2/OptionPaneDemo.java

@ -0,0 +1,235 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)OptionPaneDemo.java 1.7 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JOptionPaneDemo
*
* @version 1.7 01/23/03
* @author Jeff Dinkins
*/
public class OptionPaneDemo extends DemoModule {
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
OptionPaneDemo demo = new OptionPaneDemo(null);
demo.mainImpl();
}
/**
* OptionPaneDemo Constructor
*/
public OptionPaneDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "OptionPaneDemo", "toolbar/JOptionPane.gif");
JPanel demo = getDemoPanel();
demo.setLayout(new BoxLayout(demo, BoxLayout.X_AXIS));
JPanel bp = new JPanel() {
public Dimension getMaximumSize() {
return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
}
};
bp.setLayout(new BoxLayout(bp, BoxLayout.Y_AXIS));
bp.add(Box.createRigidArea(VGAP30));
bp.add(Box.createRigidArea(VGAP30));
bp.add(createInputDialogButton()); bp.add(Box.createRigidArea(VGAP15));
bp.add(createWarningDialogButton()); bp.add(Box.createRigidArea(VGAP15));
bp.add(createMessageDialogButton()); bp.add(Box.createRigidArea(VGAP15));
bp.add(createComponentDialogButton()); bp.add(Box.createRigidArea(VGAP15));
bp.add(createConfirmDialogButton()); bp.add(Box.createVerticalGlue());
demo.add(Box.createHorizontalGlue());
demo.add(bp);
demo.add(Box.createHorizontalGlue());
}
public JButton createWarningDialogButton() {
Action a = new AbstractAction(getString("OptionPaneDemo.warningbutton")) {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
getDemoPanel(),
getString("OptionPaneDemo.warningtext"),
getString("OptionPaneDemo.warningtitle"),
JOptionPane.WARNING_MESSAGE
);
}
};
return createButton(a);
}
public JButton createMessageDialogButton() {
Action a = new AbstractAction(getString("OptionPaneDemo.messagebutton")) {
URL img = getClass().getResource("/resources/images/optionpane/bottle.gif");
String imagesrc = "<img src=\"" + img + "\" width=\"284\" height=\"100\">";
String message = getString("OptionPaneDemo.messagetext");
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
getDemoPanel(),
"<html>" + imagesrc + "<br><center>" + message + "</center><br></html>"
);
}
};
return createButton(a);
}
public JButton createConfirmDialogButton() {
Action a = new AbstractAction(getString("OptionPaneDemo.confirmbutton")) {
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(getDemoPanel(), getString("OptionPaneDemo.confirmquestion"));
if(result == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.confirmyes"));
} else if(result == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.confirmno"));
}
}
};
return createButton(a);
}
public JButton createInputDialogButton() {
Action a = new AbstractAction(getString("OptionPaneDemo.inputbutton")) {
public void actionPerformed(ActionEvent e) {
String result = JOptionPane.showInputDialog(getDemoPanel(), getString("OptionPaneDemo.inputquestion"));
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.inputresponse"));
}
};
return createButton(a);
}
public JButton createComponentDialogButton() {
Action a = new AbstractAction(getString("OptionPaneDemo.componentbutton")) {
public void actionPerformed(ActionEvent e) {
// In a ComponentDialog, you can show as many message components and
// as many options as you want:
// Messages
Object[] message = new Object[4];
message[0] = getString("OptionPaneDemo.componentmessage");
message[1] = new JTextField(getString("OptionPaneDemo.componenttextfield"));
JComboBox cb = new JComboBox();
cb.addItem(getString("OptionPaneDemo.component_cb1"));
cb.addItem(getString("OptionPaneDemo.component_cb2"));
cb.addItem(getString("OptionPaneDemo.component_cb3"));
message[2] = cb;
message[3] = getString("OptionPaneDemo.componentmessage2");
// Options
String[] options = {
getString("OptionPaneDemo.component_op1"),
getString("OptionPaneDemo.component_op2"),
getString("OptionPaneDemo.component_op3"),
getString("OptionPaneDemo.component_op4"),
getString("OptionPaneDemo.component_op5")
};
int result = JOptionPane.showOptionDialog(
getDemoPanel(), // the parent that the dialog blocks
message, // the dialog message array
getString("OptionPaneDemo.componenttitle"), // the title of the dialog window
JOptionPane.DEFAULT_OPTION, // option type
JOptionPane.INFORMATION_MESSAGE, // message type
null, // optional icon, use null to use the default icon
options, // options string array, will be made into buttons
options[3] // option that should be made into a default button
);
switch(result) {
case 0: // yes
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.component_r1"));
break;
case 1: // no
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.component_r2"));
break;
case 2: // maybe
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.component_r3"));
break;
case 3: // probably
JOptionPane.showMessageDialog(getDemoPanel(), getString("OptionPaneDemo.component_r4"));
break;
default:
break;
}
}
};
return createButton(a);
}
public JButton createButton(Action a) {
JButton b = new JButton() {
public Dimension getMaximumSize() {
int width = Short.MAX_VALUE;
int height = super.getMaximumSize().height;
return new Dimension(width, height);
}
};
// setting the following client property informs the button to show
// the action text as it's name. The default is to not show the
// action text.
b.putClientProperty("displayActionText", Boolean.TRUE);
b.setAction(a);
// b.setAlignmentX(JButton.CENTER_ALIGNMENT);
return b;
}
}

119
swingset2/Permuter.java

@ -0,0 +1,119 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)Permuter.java 1.6 03/01/23
*/
import java.util.Random;
/**
* An object that implements a cheesy pseudorandom permutation of the integers
* from zero to some user-specified value. (The permutation is a linear
* function.)
*
* @version 1.6 01/23/03
* @author Josh Bloch
*/
class Permuter {
/**
* The size of the permutation.
*/
private int modulus;
/**
* Nonnegative integer less than n that is relatively prime to m.
*/
private int multiplier;
/**
* Pseudorandom nonnegative integer less than n.
*/
private int addend = 22;
public Permuter(int n) {
if (n<0) {
throw new IllegalArgumentException();
}
modulus = n;
if (n==1) {
return;
}
// Initialize the multiplier and offset
multiplier = (int) Math.sqrt(n);
while (gcd(multiplier, n) != 1) {
if (++multiplier == n) {
multiplier = 1;
}
}
}
/**
* Returns the integer to which this permuter maps the specified integer.
* The specified integer must be between 0 and n-1, and the returned
* integer will be as well.
*/
public int map(int i) {
return (multiplier * i + addend) % modulus;
}
/**
* Calculate GCD of a and b, which are assumed to be non-negative.
*/
private static int gcd(int a, int b) {
while(b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
/**
* Simple test. Takes modulus on command line and prints out permutation.
*/
public static void main(String[] args) {
int modulus = Integer.parseInt(args[0]);
Permuter p = new Permuter(modulus);
for (int i=0; i<modulus; i++) {
System.out.print(p.map(i)+" ");
}
System.out.println();
}
}

199
swingset2/ProgressBarDemo.java

@ -0,0 +1,199 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ProgressBarDemo.java 1.7 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JProgressBar Demo
*
* @version 1.7 01/23/03
* @author Jeff Dinkins
# @author Peter Korn (accessibility support)
*/
public class ProgressBarDemo extends DemoModule {
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ProgressBarDemo demo = new ProgressBarDemo(null);
demo.mainImpl();
}
/**
* ProgressBarDemo Constructor
*/
public ProgressBarDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "ProgressBarDemo", "toolbar/JProgressBar.gif");
createProgressPanel();
}
javax.swing.Timer timer;
Action loadAction;
Action stopAction;
JProgressBar progressBar;
JTextArea progressTextArea;
public void createProgressPanel() {
getDemoPanel().setLayout(new BorderLayout());
JPanel textWrapper = new JPanel(new BorderLayout());
textWrapper.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
textWrapper.setAlignmentX(LEFT_ALIGNMENT);
progressTextArea = new MyTextArea();
progressTextArea.getAccessibleContext().setAccessibleName(getString("ProgressBarDemo.accessible_text_area_name"));
progressTextArea.getAccessibleContext().setAccessibleName(getString("ProgressBarDemo.accessible_text_area_description"));
textWrapper.add(new JScrollPane(progressTextArea), BorderLayout.CENTER);
getDemoPanel().add(textWrapper, BorderLayout.CENTER);
JPanel progressPanel = new JPanel();
getDemoPanel().add(progressPanel, BorderLayout.SOUTH);
progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, text.length()) {
public Dimension getPreferredSize() {
return new Dimension(300, super.getPreferredSize().height);
}
};
progressBar.getAccessibleContext().setAccessibleName(getString("ProgressBarDemo.accessible_text_loading_progress"));
progressPanel.add(progressBar);
progressPanel.add(createLoadButton());
progressPanel.add(createStopButton());
}
public JButton createLoadButton() {
loadAction = new AbstractAction(getString("ProgressBarDemo.start_button")) {
public void actionPerformed(ActionEvent e) {
if(timer == null) {
loadAction.setEnabled(false);
stopAction.setEnabled(true);
timer = new javax.swing.Timer(18, createTextLoadAction());
timer.start();
}
}
};
return createButton(loadAction);
}
public JButton createStopButton() {
stopAction = new AbstractAction(getString("ProgressBarDemo.stop_button")) {
public void actionPerformed(ActionEvent e) {
if(timer != null) {
timer.stop();
timer = null;
}
loadAction.setEnabled(true);
stopAction.setEnabled(false);
}
};
return createButton(stopAction);
}
public JButton createButton(Action a) {
JButton b = new JButton();
// setting the following client property informs the button to show
// the action text as it's name. The default is to not show the
// action text.
b.putClientProperty("displayActionText", Boolean.TRUE);
b.setAction(a);
return b;
}
int textLocation = 0;
String text = getString("ProgressBarDemo.text");
public Action createTextLoadAction() {
return new AbstractAction("text load action") {
public void actionPerformed (ActionEvent e) {
if(progressBar.getValue() < progressBar.getMaximum()) {
progressBar.setValue(progressBar.getValue() + 1);
progressTextArea.append(text.substring(textLocation, textLocation+1));
textLocation++;
} else {
if(timer != null) {
timer.stop();
timer = null;
loadAction.setEnabled(true);
stopAction.setEnabled(false);
}
}
}
};
}
class MyTextArea extends JTextArea {
public MyTextArea() {
super(null, 0, 0);
setEditable(false);
setText("");
}
public float getAlignmentX () {
return LEFT_ALIGNMENT;
}
public float getAlignmentY () {
return TOP_ALIGNMENT;
}
}
}

64
swingset2/RubyTheme.java

@ -0,0 +1,64 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)RubyTheme.java 1.7 03/01/23
*/
import javax.swing.plaf.*;
import javax.swing.plaf.metal.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
/**
* This class describes a theme using red colors.
*
* @version 1.7 01/23/03
* @author Jeff Dinkins
*/
public class RubyTheme extends DefaultMetalTheme {
public String getName() { return "Ruby"; }
private final ColorUIResource primary1 = new ColorUIResource(80, 10, 22);
private final ColorUIResource primary2 = new ColorUIResource(193, 10, 44);
private final ColorUIResource primary3 = new ColorUIResource(244, 10, 66);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
}

131
swingset2/ScrollPaneDemo.java

@ -0,0 +1,131 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ScrollPaneDemo.java 1.6 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* Scroll Pane Demo
*
* @version 1.6 01/23/03
* @author Jeff Dinkins
*/
public class ScrollPaneDemo extends DemoModule {
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ScrollPaneDemo demo = new ScrollPaneDemo(null);
demo.mainImpl();
}
/**
* ScrollPaneDemo Constructor
*/
public ScrollPaneDemo(SwingSet2 swingset) {
super(swingset, "ScrollPaneDemo", "toolbar/JScrollPane.gif");
ImageIcon crayons = createImageIcon("scrollpane/crayons.jpg", getString("ScrollPaneDemo.crayons"));
getDemoPanel().add(new ImageScroller(this, crayons), BorderLayout.CENTER);
}
/**
* ScrollPane class that demonstrates how to set the various column and row headers
* and corners.
*/
class ImageScroller extends JScrollPane {
public ImageScroller(ScrollPaneDemo demo, Icon icon) {
super();
// Panel to hold the icon image
JPanel p = new JPanel(new BorderLayout());
p.add(new JLabel(icon), BorderLayout.CENTER);
getViewport().add(p);
// Create and add a column header to the scrollpane
JLabel colHeader = new JLabel(
demo.createImageIcon("scrollpane/colheader.jpg", getString("ScrollPaneDemo.colheader")));
setColumnHeaderView(colHeader);
// Create and add a row header to the scrollpane
JLabel rowHeader = new JLabel(
demo.createImageIcon("scrollpane/rowheader.jpg", getString("ScrollPaneDemo.rowheader")));
setRowHeaderView(rowHeader);
// Create and add the upper left corner
JLabel cornerUL = new JLabel(
demo.createImageIcon("scrollpane/upperleft.jpg", getString("ScrollPaneDemo.upperleft")));
setCorner(UPPER_LEFT_CORNER, cornerUL);
// Create and add the upper right corner
JLabel cornerUR = new JLabel(
demo.createImageIcon("scrollpane/upperright.jpg", getString("ScrollPaneDemo.upperright")));
setCorner(UPPER_RIGHT_CORNER, cornerUR);
// Create and add the lower left corner
JLabel cornerLL = new JLabel(
demo.createImageIcon("scrollpane/lowerleft.jpg", getString("ScrollPaneDemo.lowerleft")));
setCorner(LOWER_LEFT_CORNER, cornerLL);
JScrollBar vsb = getVerticalScrollBar();
JScrollBar hsb = getHorizontalScrollBar();
vsb.setValue(icon.getIconHeight());
hsb.setValue(icon.getIconWidth()/10);
}
}
}

293
swingset2/SliderDemo.java

@ -0,0 +1,293 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)SliderDemo.java 1.6 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JSlider Demo
*
* @version 1.6 01/23/03
* @author Dave Kloba
* @author Jeff Dinkins
*/
public class SliderDemo extends DemoModule {
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
SliderDemo demo = new SliderDemo(null);
demo.mainImpl();
}
/**
* SliderDemo Constructor
*/
public SliderDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "SliderDemo", "toolbar/JSlider.gif");
createSliderDemo();
}
public void createSliderDemo() {
JSlider s;
JPanel hp;
JPanel vp;
GridLayout g;
JPanel tp;
JLabel tf;
ChangeListener listener;
getDemoPanel().setLayout(new BorderLayout());
tf = new JLabel(getString("SliderDemo.slidervalue"));
getDemoPanel().add(tf, BorderLayout.SOUTH);
tp = new JPanel();
g = new GridLayout(1, 2);
g.setHgap(5);
g.setVgap(5);
tp.setLayout(g);
getDemoPanel().add(tp, BorderLayout.CENTER);
listener = new SliderListener(tf);
BevelBorder border = new BevelBorder(BevelBorder.LOWERED);
hp = new JPanel();
hp.setLayout(new BoxLayout(hp, BoxLayout.Y_AXIS));
hp.setBorder(new TitledBorder(
border,
getString("SliderDemo.horizontal"),
TitledBorder.LEFT,
TitledBorder.ABOVE_TOP));
tp.add(hp);
vp = new JPanel();
vp.setLayout(new BoxLayout(vp, BoxLayout.X_AXIS));
vp.setBorder(new TitledBorder(
border,
getString("SliderDemo.vertical"),
TitledBorder.LEFT,
TitledBorder.ABOVE_TOP));
tp.add(vp);
// Horizontal Slider 1
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.plain")));
s = new JSlider(-10, 100, 20);
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.plain"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.a_plain_slider"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(VGAP5));
p.add(s);
p.add(Box.createRigidArea(VGAP5));
hp.add(p);
hp.add(Box.createRigidArea(VGAP10));
// Horizontal Slider 2
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.majorticks")));
s = new JSlider(100, 1000, 400);
s.setPaintTicks(true);
s.setMajorTickSpacing(100);
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.majorticks"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.majorticksdescription"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(VGAP5));
p.add(s);
p.add(Box.createRigidArea(VGAP5));
hp.add(p);
hp.add(Box.createRigidArea(VGAP10));
// Horizontal Slider 3
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.ticks")));
s = new JSlider(0, 11, 6);
s.putClientProperty("JSlider.isFilled", Boolean.TRUE );
s.setPaintTicks(true);
s.setMajorTickSpacing(5);
s.setMinorTickSpacing(1);
s.setPaintLabels( true );
s.setSnapToTicks( true );
s.getLabelTable().put(new Integer(11), new JLabel(new Integer(11).toString(), JLabel.CENTER));
s.setLabelTable( s.getLabelTable() );
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.minorticks"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.minorticksdescription"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(VGAP5));
p.add(s);
p.add(Box.createRigidArea(VGAP5));
hp.add(p);
hp.add(Box.createRigidArea(VGAP10));
// Horizontal Slider 4
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.disabled")));
BoundedRangeModel brm = new DefaultBoundedRangeModel(80, 0, 0, 100);
s = new JSlider(brm);
s.setPaintTicks(true);
s.setMajorTickSpacing(20);
s.setMinorTickSpacing(5);
s.setEnabled(false);
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.disabled"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.disableddescription"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(VGAP5));
p.add(s);
p.add(Box.createRigidArea(VGAP5));
hp.add(p);
//////////////////////////////////////////////////////////////////////////////
// Vertical Slider 1
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.plain")));
s = new JSlider(JSlider.VERTICAL, -10, 100, 20);
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.plain"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.a_plain_slider"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(HGAP10));
p.add(s);
p.add(Box.createRigidArea(HGAP10));
vp.add(p);
vp.add(Box.createRigidArea(HGAP10));
// Vertical Slider 2
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.majorticks")));
s = new JSlider(JSlider.VERTICAL, 100, 1000, 400);
s.putClientProperty( "JSlider.isFilled", Boolean.TRUE );
s.setPaintTicks(true);
s.setMajorTickSpacing(100);
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.majorticks"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.majorticksdescription"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(HGAP25));
p.add(s);
p.add(Box.createRigidArea(HGAP25));
vp.add(p);
vp.add(Box.createRigidArea(HGAP5));
// Vertical Slider 3
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.minorticks")));
s = new JSlider(JSlider.VERTICAL, 0, 100, 60);
s.setPaintTicks(true);
s.setMajorTickSpacing(20);
s.setMinorTickSpacing(5);
s.setPaintLabels( true );
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.minorticks"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.minorticksdescription"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(HGAP10));
p.add(s);
p.add(Box.createRigidArea(HGAP10));
vp.add(p);
vp.add(Box.createRigidArea(HGAP5));
// Vertical Slider 4
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.setBorder(new TitledBorder(getString("SliderDemo.disabled")));
s = new JSlider(JSlider.VERTICAL, 0, 100, 80);
s.setPaintTicks(true);
s.setMajorTickSpacing(20);
s.setMinorTickSpacing(5);
s.setEnabled(false);
s.getAccessibleContext().setAccessibleName(getString("SliderDemo.disabled"));
s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.disableddescription"));
s.addChangeListener(listener);
p.add(Box.createRigidArea(HGAP20));
p.add(s);
p.add(Box.createRigidArea(HGAP20));
vp.add(p);
}
class SliderListener implements ChangeListener {
JLabel tf;
public SliderListener(JLabel f) {
tf = f;
}
public void stateChanged(ChangeEvent e) {
JSlider s1 = (JSlider)e.getSource();
tf.setText(getString("SliderDemo.slidervalue") + s1.getValue());
}
}
}

275
swingset2/SplitPaneDemo.java

@ -0,0 +1,275 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)SplitPaneDemo.java 1.8 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* Split Pane demo
*
* @version 1.8 01/23/03
* @author Scott Violet
* @author Jeff Dinkins
*/
public class SplitPaneDemo extends DemoModule {
JSplitPane splitPane = null;
JLabel earth = null;
JLabel moon = null;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
SplitPaneDemo demo = new SplitPaneDemo(null);
demo.mainImpl();
}
/**
* SplitPaneDemo Constructor
*/
public SplitPaneDemo(SwingSet2 swingset) {
super(swingset, "SplitPaneDemo", "toolbar/JSplitPane.gif");
earth = new JLabel(createImageIcon("splitpane/earth.jpg", getString("SplitPaneDemo.earth")));
earth.setMinimumSize(new Dimension(20, 20));
moon = new JLabel(createImageIcon("splitpane/moon.jpg", getString("SplitPaneDemo.moon")));
moon.setMinimumSize(new Dimension(20, 20));
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, earth, moon);
splitPane.setContinuousLayout(true);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
getDemoPanel().add(splitPane, BorderLayout.CENTER);
getDemoPanel().setBackground(Color.black);
getDemoPanel().add(createSplitPaneControls(), BorderLayout.SOUTH);
}
/**
* Creates controls to alter the JSplitPane.
*/
protected JPanel createSplitPaneControls() {
JPanel wrapper = new JPanel();
ButtonGroup group = new ButtonGroup();
JRadioButton button;
Box buttonWrapper = new Box(BoxLayout.X_AXIS);
wrapper.setLayout(new GridLayout(0, 1));
/* Create a radio button to vertically split the split pane. */
button = new JRadioButton(getString("SplitPaneDemo.vert_split"));
button.setMnemonic(getMnemonic("SplitPaneDemo.vert_split_mnemonic"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
}
});
group.add(button);
buttonWrapper.add(button);
/* Create a radio button the horizontally split the split pane. */
button = new JRadioButton(getString("SplitPaneDemo.horz_split"));
button.setMnemonic(getMnemonic("SplitPaneDemo.horz_split_mnemonic"));
button.setSelected(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
}
});
group.add(button);
buttonWrapper.add(button);
/* Create a check box as to whether or not the split pane continually
lays out the component when dragging. */
JCheckBox checkBox = new JCheckBox(getString("SplitPaneDemo.cont_layout"));
checkBox.setMnemonic(getMnemonic("SplitPaneDemo.cont_layout_mnemonic"));
checkBox.setSelected(true);
checkBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
splitPane.setContinuousLayout(
((JCheckBox)e.getSource()).isSelected());
}
});
buttonWrapper.add(checkBox);
/* Create a check box as to whether or not the split pane divider
contains the oneTouchExpandable buttons. */
checkBox = new JCheckBox(getString("SplitPaneDemo.one_touch_expandable"));
checkBox.setMnemonic(getMnemonic("SplitPaneDemo.one_touch_expandable_mnemonic"));
checkBox.setSelected(true);
checkBox.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
splitPane.setOneTouchExpandable(
((JCheckBox) e.getSource()).isSelected());
}
});
buttonWrapper.add(checkBox);
wrapper.add(buttonWrapper);
/* Create a text field to change the divider size. */
JPanel tfWrapper;
JTextField tf;
JLabel label;
tf = new JTextField();
tf.setText(new Integer(splitPane.getDividerSize()).toString());
tf.setColumns(5);
tf.getAccessibleContext().setAccessibleName(getString("SplitPaneDemo.divider_size"));
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = ((JTextField)e.getSource()).getText();
int newSize;
try {
newSize = Integer.parseInt(value);
} catch (Exception ex) {
newSize = -1;
}
if(newSize > 0) {
splitPane.setDividerSize(newSize);
} else {
JOptionPane.showMessageDialog(splitPane,
getString("SplitPaneDemo.invalid_divider_size"),
getString("SplitPaneDemo.error"),
JOptionPane.ERROR_MESSAGE);
}
}
});
label = new JLabel(getString("SplitPaneDemo.divider_size"));
tfWrapper = new JPanel(new FlowLayout(FlowLayout.LEFT));
tfWrapper.add(label);
tfWrapper.add(tf);
label.setLabelFor(tf);
label.setDisplayedMnemonic(getMnemonic("SplitPaneDemo.divider_size_mnemonic"));
wrapper.add(tfWrapper);
/* Create a text field that will change the preferred/minimum size
of the earth component. */
tf = new JTextField(String.valueOf(earth.getMinimumSize().width));
tf.setColumns(5);
tf.getAccessibleContext().setAccessibleName(getString("SplitPaneDemo.first_component_min_size"));
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = ((JTextField)e.getSource()).getText();
int newSize;
try {
newSize = Integer.parseInt(value);
} catch (Exception ex) {
newSize = -1;
}
if(newSize > 10) {
earth.setMinimumSize(new Dimension(newSize, newSize));
} else {
JOptionPane.showMessageDialog(splitPane,
getString("SplitPaneDemo.invalid_min_size") +
getString("SplitPaneDemo.must_be_greater_than") + 10,
getString("SplitPaneDemo.error"),
JOptionPane.ERROR_MESSAGE);
}
}
});
label = new JLabel(getString("SplitPaneDemo.first_component_min_size"));
tfWrapper = new JPanel(new FlowLayout(FlowLayout.LEFT));
tfWrapper.add(label);
tfWrapper.add(tf);
label.setLabelFor(tf);
label.setDisplayedMnemonic(getMnemonic("SplitPaneDemo.first_component_min_size_mnemonic"));
wrapper.add(tfWrapper);
/* Create a text field that will change the preferred/minimum size
of the moon component. */
tf = new JTextField(String.valueOf(moon.getMinimumSize().width));
tf.setColumns(5);
tf.getAccessibleContext().setAccessibleName(getString("SplitPaneDemo.second_component_min_size"));
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value = ((JTextField)e.getSource()).getText();
int newSize;
try {
newSize = Integer.parseInt(value);
} catch (Exception ex) {
newSize = -1;
}
if(newSize > 10) {
moon.setMinimumSize(new Dimension(newSize, newSize));
} else {
JOptionPane.showMessageDialog(splitPane,
getString("SplitPaneDemo.invalid_min_size") +
getString("SplitPaneDemo.must_be_greater_than") + 10,
getString("SplitPaneDemo.error"),
JOptionPane.ERROR_MESSAGE);
}
}
});
label = new JLabel(getString("SplitPaneDemo.second_component_min_size"));
tfWrapper = new JPanel(new FlowLayout(FlowLayout.LEFT));
tfWrapper.add(label);
tfWrapper.add(tf);
label.setLabelFor(tf);
label.setDisplayedMnemonic(getMnemonic("SplitPaneDemo.second_component_min_size_mnemonic"));
wrapper.add(tfWrapper);
return wrapper;
}
}

1347
swingset2/SwingSet2.java

File diff suppressed because it is too large Load Diff

86
swingset2/SwingSet2Applet.java

@ -0,0 +1,86 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)SwingSet2Applet.java 1.7 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
*
*
* @version 1.7 01/23/03
* @author Jeff Dinkins
*/
public class SwingSet2Applet extends JApplet {
public void init() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(new SwingSet2(this), BorderLayout.CENTER);
}
public URL getURL(String filename) {
URL codeBase = this.getCodeBase();
URL url = null;
try {
url = new URL(codeBase, filename);
System.out.println(url);
} catch (java.net.MalformedURLException e) {
System.out.println("Error: badly specified URL");
return null;
}
return url;
}
}

242
swingset2/TabbedPaneDemo.java

@ -0,0 +1,242 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)TabbedPaneDemo.java 1.8 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JTabbedPane Demo
*
* @version 1.8 01/23/03
* @author Jeff Dinkins
*/
public class TabbedPaneDemo extends DemoModule implements ActionListener {
HeadSpin spin;
JTabbedPane tabbedpane;
ButtonGroup group;
JRadioButton top;
JRadioButton bottom;
JRadioButton left;
JRadioButton right;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
TabbedPaneDemo demo = new TabbedPaneDemo(null);
demo.mainImpl();
}
/**
* TabbedPaneDemo Constructor
*/
public TabbedPaneDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "TabbedPaneDemo", "toolbar/JTabbedPane.gif");
// create tab position controls
JPanel tabControls = new JPanel();
tabControls.add(new JLabel(getString("TabbedPaneDemo.label")));
top = (JRadioButton) tabControls.add(new JRadioButton(getString("TabbedPaneDemo.top")));
left = (JRadioButton) tabControls.add(new JRadioButton(getString("TabbedPaneDemo.left")));
bottom = (JRadioButton) tabControls.add(new JRadioButton(getString("TabbedPaneDemo.bottom")));
right = (JRadioButton) tabControls.add(new JRadioButton(getString("TabbedPaneDemo.right")));
getDemoPanel().add(tabControls, BorderLayout.NORTH);
group = new ButtonGroup();
group.add(top);
group.add(bottom);
group.add(left);
group.add(right);
top.setSelected(true);
top.addActionListener(this);
bottom.addActionListener(this);
left.addActionListener(this);
right.addActionListener(this);
// create tab
tabbedpane = new JTabbedPane();
getDemoPanel().add(tabbedpane, BorderLayout.CENTER);
String name = getString("TabbedPaneDemo.laine");
JLabel pix = new JLabel(createImageIcon("tabbedpane/laine.jpg", name));
tabbedpane.add(name, pix);
name = getString("TabbedPaneDemo.ewan");
pix = new JLabel(createImageIcon("tabbedpane/ewan.jpg", name));
tabbedpane.add(name, pix);
name = getString("TabbedPaneDemo.hania");
pix = new JLabel(createImageIcon("tabbedpane/hania.jpg", name));
tabbedpane.add(name, pix);
name = getString("TabbedPaneDemo.bounce");
spin = new HeadSpin();
tabbedpane.add(name, spin);
tabbedpane.getModel().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
SingleSelectionModel model = (SingleSelectionModel) e.getSource();
if(model.getSelectedIndex() == tabbedpane.getTabCount()-1) {
spin.go();
}
}
}
);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == top) {
tabbedpane.setTabPlacement(JTabbedPane.TOP);
} else if(e.getSource() == left) {
tabbedpane.setTabPlacement(JTabbedPane.LEFT);
} else if(e.getSource() == bottom) {
tabbedpane.setTabPlacement(JTabbedPane.BOTTOM);
} else if(e.getSource() == right) {
tabbedpane.setTabPlacement(JTabbedPane.RIGHT);
}
}
class HeadSpin extends JComponent implements ActionListener {
javax.swing.Timer animator;
ImageIcon icon[] = new ImageIcon[6];
int tmpScale;
final static int numImages = 6;
double x[] = new double[numImages];
double y[] = new double[numImages];
int xh[] = new int[numImages];
int yh[] = new int[numImages];
double scale[] = new double[numImages];
public HeadSpin() {
setBackground(Color.black);
icon[0] = createImageIcon("tabbedpane/ewan.gif", getString("TabbedPaneDemo.ewan"));
icon[1] = createImageIcon("tabbedpane/stephen.gif", getString("TabbedPaneDemo.stephen"));
icon[2] = createImageIcon("tabbedpane/david.gif", getString("TabbedPaneDemo.david"));
icon[3] = createImageIcon("tabbedpane/matthew.gif", getString("TabbedPaneDemo.matthew"));
icon[4] = createImageIcon("tabbedpane/blake.gif", getString("TabbedPaneDemo.blake"));
icon[5] = createImageIcon("tabbedpane/brooke.gif", getString("TabbedPaneDemo.brooke"));
/*
for(int i = 0; i < 6; i++) {
x[i] = (double) rand.nextInt(500);
y[i] = (double) rand.nextInt(500);
}
*/
}
public void go() {
animator = new javax.swing.Timer(22 + 22 + 22, this);
animator.start();
}
public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
for(int i = 0; i < numImages; i++) {
if(x[i] > 3*i) {
nudge(i);
squish(g, icon[i], xh[i], yh[i], scale[i]);
} else {
x[i] += .05;
y[i] += .05;
}
}
}
Random rand = new Random();
public void nudge(int i) {
x[i] += (double) rand.nextInt(1000) / 8756;
y[i] += (double) rand.nextInt(1000) / 5432;
int tmpScale = (int) (Math.abs(Math.sin(x[i])) * 10);
scale[i] = (double) tmpScale / 10;
int nudgeX = (int) (((double) getWidth()/2) * .8);
int nudgeY = (int) (((double) getHeight()/2) * .60);
xh[i] = (int) (Math.sin(x[i]) * nudgeX) + nudgeX;
yh[i] = (int) (Math.sin(y[i]) * nudgeY) + nudgeY;
}
public void squish(Graphics g, ImageIcon icon, int x, int y, double scale) {
if(isVisible()) {
g.drawImage(icon.getImage(), x, y,
(int) (icon.getIconWidth()*scale),
(int) (icon.getIconHeight()*scale),
this);
}
}
public void actionPerformed(ActionEvent e) {
if(isVisible()) {
repaint();
} else {
animator.stop();
}
}
}
}

610
swingset2/TableDemo.java

@ -0,0 +1,610 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)TableDemo.java 1.12 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* Table demo
*
* @version 1.12 01/23/03
* @author Philip Milne
* @author Steve Wilson
*/
public class TableDemo extends DemoModule {
JTable tableView;
JScrollPane scrollpane;
Dimension origin = new Dimension(0, 0);
JCheckBox isColumnReorderingAllowedCheckBox;
JCheckBox showHorizontalLinesCheckBox;
JCheckBox showVerticalLinesCheckBox;
JCheckBox isColumnSelectionAllowedCheckBox;
JCheckBox isRowSelectionAllowedCheckBox;
// JCheckBox isRowAndColumnSelectionAllowedCheckBox;
JLabel interCellSpacingLabel;
JLabel rowHeightLabel;
JSlider interCellSpacingSlider;
JSlider rowHeightSlider;
JComboBox selectionModeComboBox = null;
JComboBox resizeModeComboBox = null;
JPanel controlPanel;
JScrollPane tableAggregate;
String path = "ImageClub/food/";
final int INITIAL_ROWHEIGHT = 33;
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
TableDemo demo = new TableDemo(null);
demo.mainImpl();
}
/**
* TableDemo Constructor
*/
public TableDemo(SwingSet2 swingset) {
super(swingset, "TableDemo", "toolbar/JTable.gif");
getDemoPanel().setLayout(new BorderLayout());
controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel column1 = new JPanel (new ColumnLayout() );
JPanel column2 = new JPanel (new ColumnLayout() );
JPanel column3 = new JPanel (new ColumnLayout() );
getDemoPanel().add(controlPanel, BorderLayout.NORTH);
Vector relatedComponents = new Vector();
// start column 1
isColumnReorderingAllowedCheckBox = new JCheckBox(getString("TableDemo.reordering_allowed"), true);
column1.add(isColumnReorderingAllowedCheckBox);
isColumnReorderingAllowedCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean flag = ((JCheckBox)e.getSource()).isSelected();
tableView.getTableHeader().setReorderingAllowed(flag);
tableView.repaint();
}
});
showHorizontalLinesCheckBox = new JCheckBox(getString("TableDemo.horz_lines"), true);
column1.add(showHorizontalLinesCheckBox);
showHorizontalLinesCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean flag = ((JCheckBox)e.getSource()).isSelected();
tableView.setShowHorizontalLines(flag); ;
tableView.repaint();
}
});
showVerticalLinesCheckBox = new JCheckBox(getString("TableDemo.vert_lines"), true);
column1.add(showVerticalLinesCheckBox);
showVerticalLinesCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean flag = ((JCheckBox)e.getSource()).isSelected();
tableView.setShowVerticalLines(flag); ;
tableView.repaint();
}
});
// Show that showHorizontal/Vertical controls are related
relatedComponents.removeAllElements();
relatedComponents.add(showHorizontalLinesCheckBox);
relatedComponents.add(showVerticalLinesCheckBox);
buildAccessibleGroup(relatedComponents);
interCellSpacingLabel = new JLabel(getString("TableDemo.intercell_spacing_colon"));
column1.add(interCellSpacingLabel);
interCellSpacingSlider = new JSlider(JSlider.HORIZONTAL, 0, 10, 1);
interCellSpacingSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.intercell_spacing"));
interCellSpacingLabel.setLabelFor(interCellSpacingSlider);
column1.add(interCellSpacingSlider);
interCellSpacingSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int spacing = ((JSlider)e.getSource()).getValue();
tableView.setIntercellSpacing(new Dimension(spacing, spacing));
tableView.repaint();
}
});
controlPanel.add(column1);
// start column 2
isColumnSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.column_selection"), false);
column2.add(isColumnSelectionAllowedCheckBox);
isColumnSelectionAllowedCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean flag = ((JCheckBox)e.getSource()).isSelected();
tableView.setColumnSelectionAllowed(flag); ;
tableView.repaint();
}
});
isRowSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.row_selection"), true);
column2.add(isRowSelectionAllowedCheckBox);
isRowSelectionAllowedCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean flag = ((JCheckBox)e.getSource()).isSelected();
tableView.setRowSelectionAllowed(flag); ;
tableView.repaint();
}
});
// Show that row/column selections are related
relatedComponents.removeAllElements();
relatedComponents.add(isColumnSelectionAllowedCheckBox);
relatedComponents.add(isRowSelectionAllowedCheckBox);
buildAccessibleGroup(relatedComponents);
/*
isRowAndColumnSelectionAllowedCheckBox = new JCheckBox(getString("TableDemo.cell_selection"), false);
column2.add(isRowAndColumnSelectionAllowedCheckBox);
isRowAndColumnSelectionAllowedCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean flag = ((JCheckBox)e.getSource()).isSelected();
tableView.setCellSelectionEnabled(flag); ;
tableView.repaint();
}
});
*/
rowHeightLabel = new JLabel(getString("TableDemo.row_height_colon"));
column2.add(rowHeightLabel);
rowHeightSlider = new JSlider(JSlider.HORIZONTAL, 5, 100, INITIAL_ROWHEIGHT);
rowHeightSlider.getAccessibleContext().setAccessibleName(getString("TableDemo.row_height"));
rowHeightLabel.setLabelFor(rowHeightSlider);
column2.add(rowHeightSlider);
rowHeightSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int height = ((JSlider)e.getSource()).getValue();
tableView.setRowHeight(height);
tableView.repaint();
}
});
controlPanel.add(column2);
// Show that spacing controls are related
relatedComponents.removeAllElements();
relatedComponents.add(interCellSpacingSlider);
relatedComponents.add(rowHeightSlider);
buildAccessibleGroup(relatedComponents);
// Create the table.
tableAggregate = createTable();
getDemoPanel().add(tableAggregate, BorderLayout.CENTER);
// ComboBox for selection modes.
JPanel selectMode = new JPanel();
column3.setLayout(new ColumnLayout());
selectMode.setBorder(new TitledBorder(getString("TableDemo.selection_mode")));
selectionModeComboBox = new JComboBox();
selectionModeComboBox.addItem(getString("TableDemo.single"));
selectionModeComboBox.addItem(getString("TableDemo.one_range"));
selectionModeComboBox.addItem(getString("TableDemo.multiple_ranges"));
selectionModeComboBox.setSelectedIndex(tableView.getSelectionModel().getSelectionMode());
selectionModeComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JComboBox source = (JComboBox)e.getSource();
tableView.setSelectionMode(source.getSelectedIndex());
}
});
selectMode.add(selectionModeComboBox);
column3.add(selectMode);
// Combo box for table resize mode.
JPanel resizeMode = new JPanel();
resizeMode.setBorder(new TitledBorder(getString("TableDemo.autoresize_mode")));
resizeModeComboBox = new JComboBox();
resizeModeComboBox.addItem(getString("TableDemo.off"));
resizeModeComboBox.addItem(getString("TableDemo.column_boundries"));
resizeModeComboBox.addItem(getString("TableDemo.subsequent_columns"));
resizeModeComboBox.addItem(getString("TableDemo.last_column"));
resizeModeComboBox.addItem(getString("TableDemo.all_columns"));
resizeModeComboBox.setSelectedIndex(tableView.getAutoResizeMode());
resizeModeComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JComboBox source = (JComboBox)e.getSource();
tableView.setAutoResizeMode(source.getSelectedIndex());
}
});
resizeMode.add(resizeModeComboBox);
column3.add(resizeMode);
controlPanel.add(column3);
setTableControllers(); // Set accessibility information
} // TableDemo()
/**
* Sets the Accessibility MEMBER_OF property to denote that
* these components work together as a group. Each object
* is set to be a MEMBER_OF an array that contains all of
* the objects in the group, including itself.
*
* @param components The list of objects that are related
*/
void buildAccessibleGroup(Vector components) {
AccessibleContext context = null;
int numComponents = components.size();
Object[] group = components.toArray();
Object object = null;
for (int i = 0; i < numComponents; ++i) {
object = components.elementAt(i);
if (object instanceof Accessible) {
context = ((Accessible)components.elementAt(i)).
getAccessibleContext();
context.getAccessibleRelationSet().add(
new AccessibleRelation(
AccessibleRelation.MEMBER_OF, group));
}
}
} // buildAccessibleGroup()
/**
* This sets CONTROLLER_FOR on the controls that manipulate the
* table and CONTROLLED_BY relationships on the table to point
* back to the controllers.
*/
private void setTableControllers() {
// Set up the relationships to show what controls the table
setAccessibleController(isColumnReorderingAllowedCheckBox,
tableAggregate);
setAccessibleController(showHorizontalLinesCheckBox,
tableAggregate);
setAccessibleController(showVerticalLinesCheckBox,
tableAggregate);
setAccessibleController(isColumnSelectionAllowedCheckBox,
tableAggregate);
setAccessibleController(isRowSelectionAllowedCheckBox,
tableAggregate);
setAccessibleController(interCellSpacingSlider,
tableAggregate);
setAccessibleController(rowHeightSlider,
tableAggregate);
setAccessibleController(selectionModeComboBox,
tableAggregate);
setAccessibleController(resizeModeComboBox,
tableAggregate);
} // setTableControllers()
/**
* Sets up accessibility relationships to denote that one
* object controls another. The CONTROLLER_FOR property is
* set on the controller object, and the CONTROLLED_BY
* property is set on the target object.
*/
private void setAccessibleController(JComponent controller,
JComponent target) {
AccessibleRelationSet controllerRelations =
controller.getAccessibleContext().getAccessibleRelationSet();
AccessibleRelationSet targetRelations =
target.getAccessibleContext().getAccessibleRelationSet();
controllerRelations.add(
new AccessibleRelation(
AccessibleRelation.CONTROLLER_FOR, target));
targetRelations.add(
new AccessibleRelation(
AccessibleRelation.CONTROLLED_BY, controller));
} // setAccessibleController()
public JScrollPane createTable() {
// final
final String[] names = {
getString("TableDemo.first_name"),
getString("TableDemo.last_name"),
getString("TableDemo.favorite_color"),
getString("TableDemo.favorite_movie"),
getString("TableDemo.favorite_number"),
getString("TableDemo.favorite_food")
};
ImageIcon apple = createImageIcon("ImageClub/food/apple.jpg", getString("TableDemo.apple"));
ImageIcon asparagus = createImageIcon("ImageClub/food/asparagus.jpg", getString("TableDemo.asparagus"));
ImageIcon banana = createImageIcon("ImageClub/food/banana.jpg", getString("TableDemo.banana"));
ImageIcon broccoli = createImageIcon("ImageClub/food/broccoli.jpg", getString("TableDemo.broccoli"));
ImageIcon cantaloupe = createImageIcon("ImageClub/food/cantaloupe.jpg", getString("TableDemo.cantaloupe"));
ImageIcon carrot = createImageIcon("ImageClub/food/carrot.jpg", getString("TableDemo.carrot"));
ImageIcon corn = createImageIcon("ImageClub/food/corn.jpg", getString("TableDemo.corn"));
ImageIcon grapes = createImageIcon("ImageClub/food/grapes.jpg", getString("TableDemo.grapes"));
ImageIcon grapefruit = createImageIcon("ImageClub/food/grapefruit.jpg", getString("TableDemo.grapefruit"));
ImageIcon kiwi = createImageIcon("ImageClub/food/kiwi.jpg", getString("TableDemo.kiwi"));
ImageIcon onion = createImageIcon("ImageClub/food/onion.jpg", getString("TableDemo.onion"));
ImageIcon pear = createImageIcon("ImageClub/food/pear.jpg", getString("TableDemo.pear"));
ImageIcon peach = createImageIcon("ImageClub/food/peach.jpg", getString("TableDemo.peach"));
ImageIcon pepper = createImageIcon("ImageClub/food/pepper.jpg", getString("TableDemo.pepper"));
ImageIcon pickle = createImageIcon("ImageClub/food/pickle.jpg", getString("TableDemo.pickle"));
ImageIcon pineapple = createImageIcon("ImageClub/food/pineapple.jpg", getString("TableDemo.pineapple"));
ImageIcon raspberry = createImageIcon("ImageClub/food/raspberry.jpg", getString("TableDemo.raspberry"));
ImageIcon sparegrass = createImageIcon("ImageClub/food/asparagus.jpg", getString("TableDemo.sparegrass"));
ImageIcon strawberry = createImageIcon("ImageClub/food/strawberry.jpg", getString("TableDemo.strawberry"));
ImageIcon tomato = createImageIcon("ImageClub/food/tomato.jpg", getString("TableDemo.tomato"));
ImageIcon watermelon = createImageIcon("ImageClub/food/watermelon.jpg", getString("TableDemo.watermelon"));
NamedColor aqua = new NamedColor(new Color(127, 255, 212), getString("TableDemo.aqua"));
NamedColor beige = new NamedColor(new Color(245, 245, 220), getString("TableDemo.beige"));
NamedColor black = new NamedColor(Color.black, getString("TableDemo.black"));
NamedColor blue = new NamedColor(new Color(0, 0, 222), getString("TableDemo.blue"));
NamedColor eblue = new NamedColor(Color.blue, getString("TableDemo.eblue"));
NamedColor jfcblue = new NamedColor(new Color(204, 204, 255), getString("TableDemo.jfcblue"));
NamedColor jfcblue2 = new NamedColor(new Color(153, 153, 204), getString("TableDemo.jfcblue2"));
NamedColor cybergreen = new NamedColor(Color.green.darker().brighter(), getString("TableDemo.cybergreen"));
NamedColor darkgreen = new NamedColor(new Color(0, 100, 75), getString("TableDemo.darkgreen"));
NamedColor forestgreen = new NamedColor(Color.green.darker(), getString("TableDemo.forestgreen"));
NamedColor gray = new NamedColor(Color.gray, getString("TableDemo.gray"));
NamedColor green = new NamedColor(Color.green, getString("TableDemo.green"));
NamedColor orange = new NamedColor(new Color(255, 165, 0), getString("TableDemo.orange"));
NamedColor purple = new NamedColor(new Color(160, 32, 240), getString("TableDemo.purple"));
NamedColor red = new NamedColor(Color.red, getString("TableDemo.red"));
NamedColor rustred = new NamedColor(Color.red.darker(), getString("TableDemo.rustred"));
NamedColor sunpurple = new NamedColor(new Color(100, 100, 255), getString("TableDemo.sunpurple"));
NamedColor suspectpink = new NamedColor(new Color(255, 105, 180), getString("TableDemo.suspectpink"));
NamedColor turquoise = new NamedColor(new Color(0, 255, 255), getString("TableDemo.turquoise"));
NamedColor violet = new NamedColor(new Color(238, 130, 238), getString("TableDemo.violet"));
NamedColor yellow = new NamedColor(Color.yellow, getString("TableDemo.yellow"));
// Create the dummy data (a few rows of names)
final Object[][] data = {
{"Mike", "Albers", green, getString("TableDemo.brazil"), new Double(44.0), strawberry},
{"Mark", "Andrews", blue, getString("TableDemo.curse"), new Double(3), grapes},
{"Brian", "Beck", black, getString("TableDemo.bluesbros"), new Double(2.7182818285), raspberry},
{"Lara", "Bunni", red, getString("TableDemo.airplane"), new Double(15), strawberry},
{"Roger", "Brinkley", blue, getString("TableDemo.man"), new Double(13), peach},
{"Brent", "Christian", black, getString("TableDemo.bladerunner"), new Double(23), broccoli},
{"Mark", "Davidson", darkgreen, getString("TableDemo.brazil"), new Double(27), asparagus},
{"Jeff", "Dinkins", blue, getString("TableDemo.ladyvanishes"), new Double(8), kiwi},
{"Ewan", "Dinkins", yellow, getString("TableDemo.bugs"), new Double(2), strawberry},
{"Amy", "Fowler", violet, getString("TableDemo.reservoir"), new Double(3), raspberry},
{"Hania", "Gajewska", purple, getString("TableDemo.jules"), new Double(5), raspberry},
{"David", "Geary", blue, getString("TableDemo.pulpfiction"), new Double(3), watermelon},
// {"James", "Gosling", pink, getString("TableDemo.tennis"), new Double(21), donut},
{"Eric", "Hawkes", blue, getString("TableDemo.bladerunner"), new Double(.693), pickle},
{"Shannon", "Hickey", green, getString("TableDemo.shawshank"), new Integer(2), grapes},
{"Earl", "Johnson", green, getString("TableDemo.pulpfiction"), new Double(8), carrot},
{"Robi", "Kahn", green, getString("TableDemo.goodfellas"), new Double(89), apple},
{"Robert", "Kim", blue, getString("TableDemo.mohicans"), new Double(655321), strawberry},
{"Janet", "Koenig", turquoise, getString("TableDemo.lonestar"), new Double(7), peach},
{"Jeff", "Kesselman", blue, getString("TableDemo.stuntman"), new Double(17), pineapple},
{"Onno", "Kluyt", orange, getString("TableDemo.oncewest"), new Double(8), broccoli},
{"Peter", "Korn", sunpurple, getString("TableDemo.musicman"), new Double(12), sparegrass},
{"Rick", "Levenson", black, getString("TableDemo.harold"), new Double(1327), raspberry},
{"Brian", "Lichtenwalter", jfcblue, getString("TableDemo.fifthelement"), new Double(22), pear},
{"Malini", "Minasandram", beige, getString("TableDemo.joyluck"), new Double(9), corn},
{"Michael", "Martak", green, getString("TableDemo.city"), new Double(3), strawberry},
{"David", "Mendenhall", forestgreen, getString("TableDemo.schindlerslist"), new Double(7), peach},
{"Phil", "Milne", suspectpink, getString("TableDemo.withnail"), new Double(3), banana},
{"Lynn", "Monsanto", cybergreen, getString("TableDemo.dasboot"), new Double(52), peach},
{"Hans", "Muller", rustred, getString("TableDemo.eraserhead"), new Double(0), pineapple},
{"Joshua", "Outwater", blue, getString("TableDemo.labyrinth"), new Integer(3), pineapple},
{"Tim", "Prinzing", blue, getString("TableDemo.firstsight"), new Double(69), pepper},
{"Raj", "Premkumar", jfcblue2, getString("TableDemo.none"), new Double(7), broccoli},
{"Howard", "Rosen", green, getString("TableDemo.defending"), new Double(7), strawberry},
{"Ray", "Ryan", black, getString("TableDemo.buckaroo"),
new Double(3.141592653589793238462643383279502884197169399375105820974944), banana},
{"Georges", "Saab", aqua, getString("TableDemo.bicycle"), new Double(290), cantaloupe},
{"Tom", "Santos", blue, getString("TableDemo.spinaltap"), new Double(241), pepper},
{"Rich", "Schiavi", blue, getString("TableDemo.repoman"), new Double(0xFF), pepper},
{"Nancy", "Schorr", green, getString("TableDemo.fifthelement"), new Double(47), watermelon},
{"Keith", "Sprochi", darkgreen, getString("TableDemo.2001"), new Integer(13), watermelon},
{"Matt", "Tucker", eblue, getString("TableDemo.starwars"), new Integer(2), broccoli},
{"Dimitri", "Trembovetsky", red, getString("TableDemo.aliens"), new Integer(222), tomato},
{"Scott", "Violet", violet, getString("TableDemo.raiders"), new Integer(-97), banana},
{"Kathy", "Walrath", blue, getString("TableDemo.thinman"), new Integer(8), pear},
{"Nathan", "Walrath", black, getString("TableDemo.chusingura"), new Integer(3), grapefruit},
{"Steve", "Wilson", green, getString("TableDemo.raiders"), new Integer(7), onion},
{"Kathleen", "Zelony", gray, getString("TableDemo.dog"), new Integer(13), grapes}
};
// Create a model of the data.
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return names.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {return data[row][col];}
public String getColumnName(int column) {return names[column];}
public Class getColumnClass(int c) {return getValueAt(0, c).getClass();}
public boolean isCellEditable(int row, int col) {return col != 5;}
public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; }
};
// Create the table
tableView = new JTable(dataModel);
// Show colors by rendering them in their own color.
DefaultTableCellRenderer colorRenderer = new DefaultTableCellRenderer() {
public void setValue(Object value) {
if (value instanceof NamedColor) {
NamedColor c = (NamedColor) value;
setBackground(c);
setForeground(c.getTextColor());
setText(c.toString());
} else {
super.setValue(value);
}
}
};
// Create a combo box to show that you can use one in a table.
JComboBox comboBox = new JComboBox();
comboBox.addItem(aqua);
comboBox.addItem(beige);
comboBox.addItem(black);
comboBox.addItem(blue);
comboBox.addItem(eblue);
comboBox.addItem(jfcblue);
comboBox.addItem(jfcblue2);
comboBox.addItem(cybergreen);
comboBox.addItem(darkgreen);
comboBox.addItem(forestgreen);
comboBox.addItem(gray);
comboBox.addItem(green);
comboBox.addItem(orange);
comboBox.addItem(purple);
comboBox.addItem(red);
comboBox.addItem(rustred);
comboBox.addItem(sunpurple);
comboBox.addItem(suspectpink);
comboBox.addItem(turquoise);
comboBox.addItem(violet);
comboBox.addItem(yellow);
TableColumn colorColumn = tableView.getColumn(getString("TableDemo.favorite_color"));
// Use the combo box as the editor in the "Favorite Color" column.
colorColumn.setCellEditor(new DefaultCellEditor(comboBox));
colorRenderer.setHorizontalAlignment(JLabel.CENTER);
colorColumn.setCellRenderer(colorRenderer);
tableView.setRowHeight(INITIAL_ROWHEIGHT);
scrollpane = new JScrollPane(tableView);
return scrollpane;
}
class NamedColor extends Color {
String name;
public NamedColor(Color color, String name) {
super(color.getRGB());
this.name = name;
}
public Color getTextColor() {
int r = getRed();
int g = getGreen();
int b = getBlue();
if(r > 240 || g > 240) {
return Color.black;
} else {
return Color.white;
}
}
public String toString() {
return name;
}
}
class ColumnLayout implements LayoutManager {
int xInset = 5;
int yInset = 5;
int yGap = 2;
public void addLayoutComponent(String s, Component c) {}
public void layoutContainer(Container c) {
Insets insets = c.getInsets();
int height = yInset + insets.top;
Component[] children = c.getComponents();
Dimension compSize = null;
for (int i = 0; i < children.length; i++) {
compSize = children[i].getPreferredSize();
children[i].setSize(compSize.width, compSize.height);
children[i].setLocation( xInset + insets.left, height);
height += compSize.height + yGap;
}
}
public Dimension minimumLayoutSize(Container c) {
Insets insets = c.getInsets();
int height = yInset + insets.top;
int width = 0 + insets.left + insets.right;
Component[] children = c.getComponents();
Dimension compSize = null;
for (int i = 0; i < children.length; i++) {
compSize = children[i].getPreferredSize();
height += compSize.height + yGap;
width = Math.max(width, compSize.width + insets.left + insets.right + xInset*2);
}
height += insets.bottom;
return new Dimension( width, height);
}
public Dimension preferredLayoutSize(Container c) {
return minimumLayoutSize(c);
}
public void removeLayoutComponent(Component c) {}
}
}

168
swingset2/ToolTipDemo.java

@ -0,0 +1,168 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)ToolTipDemo.java 1.6 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
import javax.swing.colorchooser.*;
import javax.swing.filechooser.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* ToolTip Demo
*
* @version 1.6 01/23/03
* @author Jeff Dinkins
*/
public class ToolTipDemo extends DemoModule {
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
ToolTipDemo demo = new ToolTipDemo(null);
demo.mainImpl();
}
/**
* ToolTipDemo Constructor
*/
public ToolTipDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "ToolTipDemo", "toolbar/ToolTip.gif");
// Set the layout manager.
JPanel p = getDemoPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBackground(Color.white);
// Create a Cow to put in the center of the panel.
Cow cow = new Cow();
cow.getAccessibleContext().setAccessibleName(getString("ToolTipDemo.accessible_cow"));
// Set the tooltip text. Note, for fun, we also set more tooltip text
// descriptions for the cow down below in the Cow.contains() method.
cow.setToolTipText(getString("ToolTipDemo.cow"));
// Add the cow midway down the panel
p.add(Box.createRigidArea(new Dimension(1, 150)));
p.add(cow);
}
class Cow extends JLabel {
Polygon cowgon = new Polygon();
public Cow() {
super(createImageIcon("tooltip/cow.gif", getString("ToolTipDemo.bessie")));
setAlignmentX(CENTER_ALIGNMENT);
// Set polygon points that define the outline of the cow.
cowgon.addPoint(3,20); cowgon.addPoint(44,4);
cowgon.addPoint(79,15); cowgon.addPoint(130,11);
cowgon.addPoint(252,5); cowgon.addPoint(181,17);
cowgon.addPoint(301,45); cowgon.addPoint(292,214);
cowgon.addPoint(269,209); cowgon.addPoint(266,142);
cowgon.addPoint(250,161); cowgon.addPoint(235,218);
cowgon.addPoint(203,206); cowgon.addPoint(215,137);
cowgon.addPoint(195,142); cowgon.addPoint(143,132);
cowgon.addPoint(133,189); cowgon.addPoint(160,200);
cowgon.addPoint(97,196); cowgon.addPoint(107,182);
cowgon.addPoint(118,185); cowgon.addPoint(110,144);
cowgon.addPoint(59,77); cowgon.addPoint(30,82);
cowgon.addPoint(30,35); cowgon.addPoint(15,36);
}
boolean moo = false;
boolean milk = false;
boolean tail = false;
// Use the contains method to set the tooltip text depending
// on where the mouse is over the cow.
public boolean contains(int x, int y) {
if(!cowgon.contains(new Point(x, y))) {
return false;
}
if((x > 30) && (x < 60) && (y > 60) && (y < 85)) {
if(!moo) {
setToolTipText("<html><center><font color=blue size=+2>" +
getString("ToolTipDemo.moo") + "</font></center></html>");
moo = true;
milk = false;
tail = false;
}
} else if((x > 150) && (x < 260) && (y > 90) && (y < 145)) {
if(!milk) {
setToolTipText("<html><center><font face=AvantGarde size=+1 color=white>" +
getString("ToolTipDemo.got_milk") + "</font></center></html>");
milk = true;
moo = false;
tail = false;
}
} else if((x > 280) && (x < 300) && (y > 20) && (y < 175)) {
if(!tail) {
setToolTipText("<html><em><b>" + getString("ToolTipDemo.tail") + "</b></em></html>");
tail = true;
moo = false;
milk = false;
}
} else if(moo || milk || tail) {
setToolTipText(getString("ToolTipDemo.tooltip_features"));
moo = false;
tail = false;
milk = false;
}
return true;
}
}
}

137
swingset2/TreeDemo.java

@ -0,0 +1,137 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)TreeDemo.java 1.7 03/01/23
*/
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.net.*;
/**
* JTree Demo
*
* @version 1.7 01/23/03
* @author Jeff Dinkins
*/
public class TreeDemo extends DemoModule {
/**
* main method allows us to run as a standalone demo.
*/
public static void main(String[] args) {
TreeDemo demo = new TreeDemo(null);
demo.mainImpl();
}
/**
* TreeDemo Constructor
*/
public TreeDemo(SwingSet2 swingset) {
// Set the title for this demo, and an icon used to represent this
// demo inside the SwingSet2 app.
super(swingset, "TreeDemo", "toolbar/JTree.gif");
getDemoPanel().add(createTree(), BorderLayout.CENTER);
}
public JScrollPane createTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode(getString("TreeDemo.music"));
DefaultMutableTreeNode catagory = null ;
DefaultMutableTreeNode artist = null;
DefaultMutableTreeNode record = null;
// open tree data
URL url = getClass().getResource("/resources/tree.txt");
try {
// convert url to buffered string
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
// read one line at a time, put into tree
String line = reader.readLine();
while(line != null) {
// System.out.println("reading in: ->" + line + "<-");
char linetype = line.charAt(0);
switch(linetype) {
case 'C':
catagory = new DefaultMutableTreeNode(line.substring(2));
top.add(catagory);
break;
case 'A':
if(catagory != null) {
catagory.add(artist = new DefaultMutableTreeNode(line.substring(2)));
}
break;
case 'R':
if(artist != null) {
artist.add(record = new DefaultMutableTreeNode(line.substring(2)));
}
break;
case 'S':
if(record != null) {
record.add(new DefaultMutableTreeNode(line.substring(2)));
}
break;
default:
break;
}
line = reader.readLine();
}
} catch (IOException e) {
}
JTree tree = new JTree(top) {
public Insets getInsets() {
return new Insets(5,5,5,5);
}
};
return new JScrollPane(tree);
}
}

121
swingset2/resources/ant.html

@ -0,0 +1,121 @@
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF">
<h1 align="center"><br>
Observ. XLIX. Of an Ant or Pismire.<br>
</h1>
<p align="center"><img src="images/Octavo/ant.jpg" width="481" height="325"></p>
<p align="center">&nbsp;</p>
<blockquote>
<blockquote>
<p><font size="4">This was a creature, more troublesom to be drawn, then any
of the rest, for I could not, for a good while, think of a way to make it
suffer its body to ly quiet in a natural posture; but whil'st it was alive,
if its feet were fetter'd in Wax or Glew, it would so twist and wind its body,
that I could not any wayes get a good view of it; and if I killed it, its
body was so little, that I did often spoile the shape of it, before I could
throughly view it: for this is the nature of these minute Bodies, that as
soon, almost, as ever their life is destroy'd, their parts immediately shrivel,
and lose their beauty; and so is it also with small Plants, as I instanced
before, in the description of Moss. </font></p>
<p><font size="4">And thence also is the reason of the variations in the beards
of wild Oats, and in those of Muskgrass seed, that their bodies, being exceeding
small, those small variations which are made in the surfaces of all bodies,
almost upon every change of Air, especially if the body be porous, do here
become sensible, where the whole body is so small, that it is almost nothing
but surface; for as in vegetable substances, I see no great reason to think,
that the moisture of the Aire (that, sticking to a wreath'd beard, does make
it untwist) should evaporate, or exhale away, any faster then the moisture
of other bodies, but rather that the avolation from, or access of moisture
to, the surfaces of bodies being much the same, those bodies become most
sensible of it, which have the least proportion of body to their surface.
</font></p>
<p><font size="4">So is it also with Animal substances; the dead body of an
Ant, or such little creature, does almost instantly shrivel and dry, and
your object shall be quite another thing, before you can half delineate
it, which proceeds not from the extraordinary exhalation, but from the small
proportion of body and juices, to the usual drying of bodies in the Air,
especially if warm. </font></p>
<p><font size="4">For which inconvenience, where I could not otherwise remove
it, I thought of this expedient. I took the creature, I had design'd to delineate,
and put it into a drop of very well rectified spirit of Wine, this I found
would presently dispatch, as it were, the Animal, and being taken out of
it, and lay'd on a paper,the spirit of Wine would immediately fly away,
and leave the Animal dry, in its natural posture, or at least, in a constitution,
that it might easily with a pin be plac'd, in what posture you desired to
draw it, and the limbs would so remain, without either moving, or shriveling.
</font></p>
<p><font size="4">And thus I dealt with this Ant, which I have here delineated,
which was one of many, of a very large kind, that inhabited under the Roots
of a Tree, from whence they would sally out in great parties, and make most
grievous havock of the Flowers and Fruits, in the ambient Garden, and return back
again very expertly, by the same wayes and paths they went. </font></p>
<p><font size="4">It was more then half the bigness of an Earwig, of a dark
brown, or reddish colour, with long legs, on the hinder of which it would
stand up, and raise its head as high as it could above the ground, that it
might stare the further about it, just after the same manner as I have also
observ'd a hunting Spider to do: and putting my finger towards them, they
have at first all run towards it, till almost at it; and then they would stand
round about it, at a certain distance, and smell, as it were, and consider
whether they should any of them venture any further, till one more bold then
the rest venturing to climb it, all the rest, if I would have suffered them,
would have immediately followed : much such other seemingly rational actions
I have observ'd in this little Vermine with much pleasure, which would be
too long to be here related; those that desire more of them may satisfie
their curiosity in Ligons History of the Barbadoes. </font></p>
<p><font size="4">Having insnar'd several of these into a small Box, I made
choice of the tallest grown among them, and separating it from the rest,
I gave it a Gill of Brandy, or Spirit of Wine, which after a while e'en knock'd
him down dead drunk, so that he became moveless, though at first putting
in he struggled for a pretty while very much, till at last, certain bubbles
issuing out of his mouth, it ceased to move; this (because I had before found
them quickly to recover again, if they were taken out presently) I suffered
to lye above an hour in the Spirit; and after I had taken it out, and put
its body and legs into a natural posture, remained moveless about an hour;
but then, upon a sudden, as if it had been awaken out of a drunken sleep,
it suddenly reviv'd and ran away; being caught, and serv'd as before, he
for a while continued struggling and striving, till at last there issued
several bubbles out of its mouth, and then, tanquam animam expirasset, he
remained moveless for a good while ; but at length again recovering, it was
again redipt, and suffered to lye some hours in the Spirit; notwithstanding
which, after it had layen dry some three or four hours, it again recovered
life and motion: Which kind of Experiments, if prosecuted, which they highly
deserve, seem to me of no inconsiderable use towards the invention of the
Latent Scheme, (as the Noble Ve rulam calls it) or the hidden, unknown Texture
of Bodies. </font></p>
<p><font size="4">Of what Figure this Creature appear'd through the Microscope,
the 32. Scheme (though not so carefully graven as it ought) will represent
to the eye, namely, That it had a large head A A, at the upper end of which
were two protuberant eyes, pearl'd like those of a Fly, but smaller B B;
of the Nose, or foremost part, issued two horns C C, of a shape sufficiently
differing from those of a blew Fly, though indeed they seem to be both the
same kind of Organ, and to serve for a kind of smelling; beyond these were
two indented jaws D D, which he open'd sideways, and was able to gape them
asunder very wide; and the ends of them being armed with teeth, which meeting
went between each other, it was able to grasp and hold a heavy body, three
or four times the bulk and weight of its own body: It had only six legs,
shap'd like those of a Fly, which, as I shewed before, is an Argument that
it is a winged Insect, and though I could not perceive any sign of them in
the middle part of its body (which seem'd to consist of three joints or pieces
E F G, out of which sprung two legs, yet 'tis known that there are of them
that have long wings, and fly up and down in the air. </font></p>
<p><font size="4">The third and last part of its body I I I was bigger and
larger then the other two, unto which it was joyn'd by a very small middle,
and had a kind of loose shell, or another distinct part of its body H, which
seem'd to be interpos'd, and to keep the thorax and belly from touching.
The whole body was cas'd over with a very strong armour, and the belly I
I I was covered likewise with multitudes of small white shining brisles;
the legs, horns, head, and middle parts of its body were bestruck with hairs
also, but smaller and darker. </font></p>
</blockquote>
<p>&nbsp;</p>
<p><a href="seaweed.html"><img src="images/htmldemo/back.jpg" width="146" height="40" align="left" border="0"></a><a href="bug.html"><img src="images/htmldemo/forward.jpg" width="196" height="40" align="right" border="0"></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</blockquote>
</body>
</html>

128
swingset2/resources/bug.html

@ -0,0 +1,128 @@
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF">
<br>
<h1 align="center">Observ. LIV. Of a Louse.<br>
</h1>
<p align="center"><img src="images/Octavo/bug.jpg" width="516" height="445"></p>
<p align="center">&nbsp;</p>
<blockquote>
<blockquote>
<p><font size="4">This is a Creature so officious, that 'twill be known to
every one at one time or other, so busie, and so impudent, that it will
be intruding it self in every ones company, and so proud and aspiring withall,
that it fears not to trample on the best, and affects nothing so much as
a Crown; feeds and lives very high, and that makes it so saucy, as to pull
any one by the ears that comes in its way, and will never be quiet till
it has drawn blood: it is troubled at nothing so much as at a man that scratches
his head, as knowing that man is plotting and contriving some mischief against
it, and that makes it oftentime sculk into some meaner and lower place, and
run behind a mans back, though it go very much against the hair; which ill
conditions of it having made it better known then trusted, would exempt me
from making any further description of it, did not my faithful Mercury, my
Microscope, bring me other information of it. </font></p>
<p><font size="4">For this has discovered to me, by means of a very bright light
cast on it, that it is a Creature of a very odd shape ; it has a head shap'd
like that exprest in 35. Scheme marked with A, which seems almost Conical,
but is a little flatted on the upper and under sides, at the biggest part
of which, on either side behind the head (as it were, being the place where
other Creatures ears stand) are placed its two black shining goggle eyes
B B, looking backwards, and fenced round with several small cilia or hairs
that incompass it, so that it seems this Creature has no very good foresight:
It does not seem to have any eyelids, and therefore perhaps its eyes were
so placed, that it might the better cleanse them with its forelegs; and perhaps
this may be the reason, why they so much avoid and run from the light behind
them, for being made to live in the shady and dark recesses of the hair,
and thence probably their eye having a great aperture, the open and clear
light, especially that of the Sun, must needs very much offend them; to secure
these eyes from receiving any injury from the hairs through which it passes,
it has two horns that grow before it, in the place where one would have thought
the eyes should be; each of these C C have four joynts, which are fringed,
as 'twere, with small brisles, from which to the tip of its snout D, the
head seems very round and tapering, ending in a very sharp nose D, which
seems to have a small hole, and to be the passage through which he sucks
the blood. </font></p>
<p>&nbsp;</p>
<p><img src="images/Octavo/bug2.jpg" width="537" height="348"></p>
<p><font size="4">Now whereas it if be plac'd on its back, with its belly
upwards, as it is in the 35. Scheme, it seems in several Positions to have
a resemblance of chaps, or jaws, as is represented in the Figure by E E,
yet in other postures those dark strokes disappear; and having kept several
of them in a box for two or three dayes, so that for all that time they had
nothing to feed on, I found, upon letting onecreep on my hand, that it immediately
fell to sucking, and did neither seem to thrust its nose very deep into the
skin, nor to open any kind of mouth, but I could plainly perceive a small
current of blood, which came directly from its snout, and past into its belly;
and about A there seem'd a contrivance, somewhat resembling a Pump, pair
of Bellows, or Heart, for by a very swift systole and diastole the blood
seem'd drawn from the nose, and forced into the body. </font></p>
<p><font size="4">It did not seem at all, though I viewed it a good while as
it was sucking, to thrust more of its nose into the skin then the very snout
D, nor did it cause the least discernable pain, and yet the blood seem'd
to run through its head very quick and freely, so that it seems there is
no part of the skin but the blood is dispers'd into, nay, even into the
cuticula; for had it thrust its whole nose in from D to C C, it would not
have amounted to the supposed thickness of that tegument, the length of
the nose being not more then a three hundredth part of an inch. </font></p>
<p><font size="4">It has six legs, covered with a very transparent shell,
and joynted exactly like a Crab's, or Lobster's; each leg is divided into
six parts by these joynts, and those have here and there several small hairs;
and at the end of each leg it has two claws, very properly adapted for its
peculiar use, being thereby inabled to walk very securely both on the skin
and hair; and indeed this contrivance of the feet is very curious, and could
not be made more commodiously and compendiously, for performing both these
requisite motions, of walking and climbing up the hair of a mans head, then
it is : for, by having the lesser claw (a) set so much short of the bigger
(b) when it walks on the skin the shorter touches not, and then the feet
are the same with those of a Mite, and several other small Insects, but by
means of the small joynts of the longer claw it can bend it round, and so
with both claws take hold of a hair, in the manner represented in the Figure,
the long transparent Cylinder F F F, being a Man's hair held by it. </font></p>
<p><font size="4">The Thorax seem'd cas'd with another kind of substance then
the belly, namely, with a thin transparent horny substance, which upon the fasting
of the Creature did not grow flaccid; through this I could plainly see the
blood, suck'd from my hand, to be variously distributed, and mov'd to and
fro; and about G there seem'd a pretty big white substance, which seem'd
to be moved within its thorax; besides, there appear'd very many small milk-white
vessels, which crost over the breast between the legs, out of which, on
either side, are many small branchings, these seem'd to be the veins and
arteries, for that which is analogus to blood in all Insects is milk-white.
</font></p>
<p><font size="4">The belly is covered with a transparent substance likewise,
but more resembling a skin then a shell, for 'tis grain'd all over the belly
just like the skin in the palms of a man's hand, and when the belly is empty,
grows very flaccid and wrinkled ; at the upper end of this is placed the
stomach H H, and perhaps also the white spot I I may be the liver, or pancreas,
which by the peristaltick motion of the guts, is a little mov'd to and fro,
not with a systole and diastole, but rather with a thronging or justling
motion. </font></p>
<p><font size="4">Viewing one of these Creatures, after it had fasted two
dayes, all the hinder part was lank and flaccid, and the white spot I I
hardly mov'd, most of the white branchings disappear'd, and most also of
the redness or sucked blood in the guts, the peristaltick motion of which
was scarce discernable; but upon the suffering it to suck, it presently
fill'd the skin of the belly, and of the six scolop'd embosments on either side,
as full as it could be stuft ; the stomach and guts were as full as they
could hold; the peristaltick motion of the gut grew quick, and the justling
motion of I I accordingly ; multitudes of milk-white vessels seem'd quickly
filled, and turgid, which were perhaps the veins and arteries, and the Creature
was so greedy, that though it could not contain more, yet it continued sucking
as fast as ever, and as fast emptying it self behind : the digestion of this
Creature must needs be very quick, for though I perceiv'd the blood thicker
and blacker when suck'd, yet, when in the guts, it was of a very lovely
ruby colour, and that part of it, which was digested into the veins, seemed
white; whence it appears, that a further digestion of blood may make it
milk, at least of a resembling colour : What is else observable in the figure
of this Creature, maybe seen by the 35. Scheme.</font></p>
</blockquote>
<p>&nbsp;</p>
<p><a href="ant.html"><img src="images/htmldemo/back.jpg" width="146" height="40" align="left" border="0"></a><a href="index.html"><img src="images/htmldemo/forward.jpg" width="196" height="40" align="right" border="0"></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</blockquote>
</body>
</html>

BIN
swingset2/resources/images/About.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

7
swingset2/resources/images/ImageClub/COPYRIGHT

@ -0,0 +1,7 @@
All images in this directory are copyright 1997 by Adobe Systems Incorporated.
Unauthorized reproduction is prohibited.
For more information about Adobe's Clip Art collections, please see:
http://www.imageclub.com

BIN
swingset2/resources/images/ImageClub/food/apple.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
swingset2/resources/images/ImageClub/food/asparagus.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

BIN
swingset2/resources/images/ImageClub/food/banana.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
swingset2/resources/images/ImageClub/food/broccoli.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
swingset2/resources/images/ImageClub/food/cantaloupe.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

BIN
swingset2/resources/images/ImageClub/food/carrot.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

BIN
swingset2/resources/images/ImageClub/food/corn.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
swingset2/resources/images/ImageClub/food/grapefruit.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

BIN
swingset2/resources/images/ImageClub/food/grapes.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

BIN
swingset2/resources/images/ImageClub/food/kiwi.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

BIN
swingset2/resources/images/ImageClub/food/onion.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

BIN
swingset2/resources/images/ImageClub/food/peach.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

BIN
swingset2/resources/images/ImageClub/food/pear.jpg

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save