8153141: Develop initial set of tests for SwingSet

Reviewed-by: prr
This commit is contained in:
Alexander Kouznetsov 2016-03-30 19:05:58 -07:00
parent a02742b2e5
commit 0ab1a9c7a8
413 changed files with 83163 additions and 1 deletions

View File

@ -7,3 +7,5 @@
^make/netbeans/.*/dist/
^.hgtip
.DS_Store
.*/JTreport/.*
.*/JTwork/.*

View File

@ -0,0 +1,15 @@
This NetBeans project corresponds to client sanity test suite in jdk/test/sanity/client.
It simplifies working on the suite in NetBeans.
It also includes the following custom tasks:
prepare-bundle creates dist/sanity.zip containing standalone bundle of the suite
run-jemmy-browser runs Jemmy browser for the ButtonDemo (hardcoded in build.xml file)
The tool allows to explore the UI hierarchy.
There is no task to run tests using JTReg. Please refer to corresponding README file
in the client sanity test suite folder on how to run the tests.
Contact alexander.kouznetsov@oracle.com in case of issues.

View File

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="SanityTests" default="default" basedir=".">
<description>Builds, tests, and runs the project SanityTests.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="SanityTests-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
<target name="prepare-bundle" depends="init">
<zip zipfile="${dist.dir}/sanity.zip">
<fileset dir="../../../test" includes="sanity/client/SwingSet/**"/>
<fileset dir="../../../test" includes="sanity/client/lib/**"/>
<fileset dir="../../../test" includes="sanity/client/ReadMe.txt"/>
<fileset dir="../../../test" includes="sanity/client/TEST.properties"/>
<mappedresources>
<fileset dir="../../../test/sanity/client" includes="TEST.ROOT.template"/>
<globmapper from="TEST.ROOT.template" to="TEST.ROOT" />
</mappedresources>
</zip>
</target>
<target name="run-jemmy-browser" depends="init">
<java
classpath="${run.classpath}"
classname="org.netbeans.jemmy.explorer.GUIBrowser"
args="com.sun.swingset3.demos.button.ButtonDemo"/>
</target>
</project>

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
build.xml.data.CRC32=0f9d9977
build.xml.script.CRC32=f902e8b8
build.xml.stylesheet.CRC32=8064a381@1.75.2.48
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=55414227
nbproject/build-impl.xml.script.CRC32=c12f9d04
nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48

View File

@ -0,0 +1,79 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=SanityTests
application.vendor=akouznet
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# Files in build.classes.dir which should be excluded from distribution jar
dist.archive.excludes=
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/SanityTests.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=*.cfg
includes=**
jar.compress=false
javac.classpath=\
${libs.testng.classpath}
# Space-separated list of extra javac options
javac.compilerargs=-Xmaxwarns 9999 -Xlint:all -Xlint:-serial
javac.deprecation=false
javac.external.vm=false
javac.processorpath=\
${javac.classpath}
javac.source=1.8
javac.target=1.8
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project.
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
# To set system properties for unit tests define test-sys-prop.name=value:
run.jvmargs=-ea
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.src.dir=..\\..\\..\\test\\sanity\\client\\SwingSet\\src
src.src2.dir=..\\..\\..\\test\\sanity\\client\\lib\\SwingSet3\\src
src.src3.dir=..\\..\\..\\test\\sanity\\client\\lib\\jemmy\\src
src.src4.dir=..\\..\\..\\test\\sanity\\client\\lib\\Jemmy2Ext\\src

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>SanityTests</name>
<source-roots>
<root id="src.src3.dir" name="lib\jemmy\src"/>
<root id="src.src4.dir" name="lib\Jemmy2Ext\src"/>
<root id="src.src2.dir" name="lib\SwingSet3\src"/>
<root id="src.src.dir" name="SwingSet\src"/>
</source-roots>
<test-roots/>
</data>
<references xmlns="http://www.netbeans.org/ns/ant-project-references/2"/>
</configuration>
</project>

View File

@ -60,7 +60,8 @@ tier3 = \
:jdk_rmi \
:jdk_beans \
:jdk_imageio \
:jdk_sound
:jdk_sound \
:jdk_client_sanity
###############################################################################
#
@ -351,6 +352,10 @@ jdk_desktop = \
:jdk_sound \
:jdk_imageio
# SwingSet3 tests.
jdk_client_sanity = \
sanity/client/SwingSet
###############################################################################
#
# Serviceability sanity groups

View File

@ -0,0 +1,45 @@
This suite contains automated client sanity tests which can be run using JTReg.
Contact alexander.kouznetsov@oracle.com in case of issues.
-------------------------------------------------------------------------------
How to run:
1) Download/Install the JDK to be tested in the system.
(For example C:/java/jdk1.9.0 in windows or
/export/jdk/jdk1.9.0 in linux/mac/solaris)
2) Download/Install JTReg harness, minimum required version is 4.1 b13.
3) Open terminal(cmd in windows, *not* cygwin) and go to the this directory.
4) To run
- see the notes below on how to prepare for the test run
- set JT_HOME to <path/to/jtreg>, for example
set JT_HOME=C:\Java\client\jtreg (Windows)
- run the command
'sh <path/to/jtreg/bin/jtreg> -ea -k:\!screenshots -jdk:<Path/to/JDK> SwingSet'
For example: 'sh C:/jtreg/bin/jtreg -ea -k:\!screenshots -jdk:C:/java/jdk1.9.0 SwingSet' (Windows)
'sh /export/jtreg/bin/jtreg -ea -k:\!screenshots -jdk:/export/jdk/jdk1.9.0 SwingSet' (Linux/Solaris)
'sh /export/jtreg/bin/jtreg -ea -k:\!screenshots -jdk:/export/jdk/jdk1.9.0/Contents/Home SwingSet' (Mac)
Try to minimize all the other windows for no interference and test stability.
Do not touch keyboard or mouse, open any window, nor lock the screen while the tests are running.
The tests will be executed, and the results will be displayed in the terminal.
A report will be generated under
a) JTReg: "JTReport/index.html".
The failure logs could be found under:
a) JTReg: "JTWork/<testname>/<testname>.jtr"
The following additional options might be useful:
-retain:all to keep work files for passed tests
-k:\!screenshots removal of this option will run tests that require full environment with Robot and screenshots
-g to run JavaTest GUI
-------------------------------------------------------------------------------
The tests in the suite are based on SwingSet3 demo application. They use Jemmy to
operate on controls of the demo and verify that it is behaving as expected. Both
Jemmy and SwingSet3 sources are available as copies in lib folder.
Original Jemmy repository is https://jemmy.java.net
Original SwingSet3 repository is https://java.net/projects/swingset3

View File

@ -0,0 +1,94 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.image.StrictImageComparator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import static org.jemmy2ext.JemmyExt.*;
import org.testng.annotations.Test;
import static com.sun.swingset3.demos.button.ButtonDemo.*;
/*
* @test
* @key headful screenshots
* @summary Verifies buttons on SwingSet3 ButtonDemo page by clicking each
* button, taking its screenshots and checking that pressed button
* image is different from initial button image.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.button.ButtonDemo
* @run testng ButtonDemoScreenshotTest
*/
public class ButtonDemoScreenshotTest {
private static final int BUTTON_COUNT = 6; // TODO: Decide about "open browser" buttons (value was 8 originally)
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
Robot rob = new Robot();
new ClassReference(com.sun.swingset3.demos.button.ButtonDemo.class.getCanonicalName()).startApplication();
JFrameOperator mainFrame = new JFrameOperator(DEMO_TITLE);
waitImageIsStill(rob, mainFrame);
// Check all the buttons
for (int i = 0; i < BUTTON_COUNT; i++) {
checkButton(mainFrame, i, rob);
}
});
}
public void checkButton(JFrameOperator jfo, int i, Robot rob) {
JButtonOperator button = new JButtonOperator(jfo, i);
Point loc = button.getLocationOnScreen();
rob.mouseMove(loc.x, loc.y);
BufferedImage initialButtonImage = capture(rob, button);
assertNotBlack(initialButtonImage);
save(initialButtonImage, "button" + i + "_0initial.png");
rob.mousePress(InputEvent.BUTTON1_MASK);
try {
waitPressed(button);
BufferedImage pressedButtonImage = capture(rob, button);
assertNotBlack(pressedButtonImage);
save(pressedButtonImage, "button" + i + "_1pressed.png");
StrictImageComparator sComparator = new StrictImageComparator();
assertNotEquals("Button " + i + " Test", sComparator, initialButtonImage, pressedButtonImage);
} finally {
rob.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
}

View File

@ -0,0 +1,177 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.JHyperlink;
import com.sun.swingset3.demos.button.ButtonDemo;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.event.ChangeEvent;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.jemmy2ext.JemmyExt.ByToolTipChooser;
import static org.jemmy2ext.JemmyExt.EXACT_STRING_COMPARATOR;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import static com.sun.swingset3.demos.button.ButtonDemo.*;
import org.jemmy2ext.JemmyExt;
import org.jemmy2ext.JemmyExt.MultiThreadedTryCatch;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies buttons on SwingSet3 ButtonDemo page by clicking each button
* and checking model change events. It also verifies tooltips and text
* on buttons before and after click.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.button.ButtonDemo
* @run testng ButtonDemoTest
*/
public class ButtonDemoTest {
private static final String[] BUTTON_TEXT_AFTER = {
DO_IT_AGAIN,};
private static final String[] BUTTON_TEXT_BEFORE = {
DO_IT,
"",
FIND,
GO,
CONNECT,
"",
GET_MORE_INFO,
null
};
private static final String[] BUTTON_TOOLTIP = {
SIMPLE_BUTTON,
IMAGE_BUTTON,
BUTTON_WITH_TEXT_AND_IMAGE,
BUTTON_WITH_BACKGROUND_COLOR,
BUTTON_WITH_NO_BORDER,
BUTTON_WITH_ROLLOVER_IMAGE,
JAVA_SE_URL,
JAVA_BLOGS_URL
};
private static final String[] GOLDEN = {
"isArmed = false, isEnabled = true, isPressed = false, isSelected = false",
"isArmed = true, isEnabled = true, isPressed = false, isSelected = false",
"isArmed = true, isEnabled = true, isPressed = true, isSelected = false",
"isArmed = true, isEnabled = true, isPressed = false, isSelected = false",
"isArmed = false, isEnabled = true, isPressed = false, isSelected = false"
};
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(ButtonDemo.class.getCanonicalName()).startApplication();
JFrameOperator mainFrame = new JFrameOperator(DEMO_TITLE);
mainFrame.setComparator(EXACT_STRING_COMPARATOR);
// Check all the buttons
for (int i = 0; i < BUTTON_TOOLTIP.length; i++) {
String tooltip = BUTTON_TOOLTIP[i];
JButtonOperator button = new JButtonOperator(mainFrame, new ByToolTipChooser(tooltip));
assertEquals(BUTTON_TEXT_BEFORE[i], button.getText());
// Two buttons are hyperlinks, we don't want to click them
if (!button.getSource().getClass().equals(JHyperlink.class)) {
checkButton(button);
}
if (BUTTON_TEXT_AFTER.length > i) {
assertEquals(BUTTON_TEXT_AFTER[i], button.getText());
} else {
assertEquals(BUTTON_TEXT_BEFORE[i], button.getText());
}
}
});
}
private void checkButton(JButtonOperator button) throws Exception {
MultiThreadedTryCatch tryCatch = new JemmyExt.MultiThreadedTryCatch();
try {
BlockingQueue<String> modelStateChanges = new ArrayBlockingQueue<>(GOLDEN.length);
button.getQueueTool().invokeAndWait(() -> {
try {
JButton jButton = (JButton) button.getSource();
ButtonModel model = jButton.getModel();
String line = toString(model);
System.out.println("Inital: " + line);
modelStateChanges.add(line);
model.addChangeListener((ChangeEvent e) -> {
try {
String line2 = toString(model);
System.out.println("ChangeEvent: " + line2);
// We are only interested in the first GOLDEN.length events
if (modelStateChanges.remainingCapacity() > 0) {
modelStateChanges.add(line2);
}
} catch (RuntimeException | Error t) {
tryCatch.register(t);
}
});
} catch (Error error) {
// All exceptions are already handled by Jemmy but Errors are not
tryCatch.register(error);
throw error;
}
});
assertEquals("Initial state check", GOLDEN[0], modelStateChanges.take());
button.clickMouse();
for (int state = 1; state < GOLDEN.length; state++) {
assertEquals(GOLDEN[state], modelStateChanges.take());
}
} catch (RuntimeException | Error | InterruptedException t) {
tryCatch.registerRoot(t);
} finally {
tryCatch.throwRegistered();
}
}
private static String toString(ButtonModel model) {
return "isArmed = " + model.isArmed()
+ ", isEnabled = " + model.isEnabled()
+ ", isPressed = " + model.isPressed()
+ ", isSelected = " + model.isSelected();
}
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.combobox.ComboBoxDemo;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JComboBoxOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import static com.sun.swingset3.demos.combobox.ComboBoxDemo.*;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies ComboBoxes on SwingSet2 ComboBoxDemo page by selecting
* each value of each ComboBox.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.combobox.ComboBoxDemo
* @run testng ComboBoxDemoTest
*/
public class ComboBoxDemoTest {
private static enum ComboBoxInfo {
PRESETS("Presets:"),
HAIR("Hair:"),
EYES_N_NOSE("Eyes & Nose:"),
MOUTH("Mouth:");
private final String comboBoxName;
private ComboBoxInfo(String comboBoxName) {
this.comboBoxName = comboBoxName;
}
}
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(ComboBoxDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
for (ComboBoxInfo comboBoxInfo : ComboBoxInfo.values()) {
comboBoxChecker(frame, comboBoxInfo);
}
});
}
private void comboBoxChecker(JFrameOperator jfo, ComboBoxInfo comboBoxInfo) {
JComboBoxOperator jcbo = new JComboBoxOperator(jfo, comboBoxInfo.ordinal());
for (int i = 0; i < jcbo.getItemCount(); i++) {
jcbo.selectItem(i);
assertEquals(comboBoxInfo.comboBoxName + " ComboBox SelectedIndex is correct", i, jcbo.getSelectedIndex());
}
}
}

View File

@ -0,0 +1,120 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.list.ListDemo;
import static com.sun.swingset3.demos.list.ListDemo.DEMO_TITLE;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import static org.jemmy2ext.JemmyExt.getLabeledContainerOperator;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JCheckBoxOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JListOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 ListDemo page by checking and unchecking all
* the checkboxes on the page and verifying the number of items in the
* list.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.list.ListDemo
* @run testng ListDemoTest
*/
public class ListDemoTest {
private static final int CHECKBOX_COUNT = 50;
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(ListDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
JListOperator listOp = new JListOperator(frame);
// Check *NO* Prefix and Suffixes Marked
for (int i = 0; i < CHECKBOX_COUNT; i++) {
JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i);
checkBox.changeSelection(false);
}
System.out.println("######## Number of Items = " + listOp.getModel().getSize());
assertEquals("Select None number of items is correct", 0, listOp.getModel().getSize());
// Check *ALL* Prefix and Suffixes Marked
for (int i = 0; i < CHECKBOX_COUNT; i++) {
JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i);
checkBox.changeSelection(true);
}
System.out.println("######## Number of Items = " + listOp.getModel().getSize());
assertEquals("Select All number of items is correct", CHECKBOX_COUNT / 2 * CHECKBOX_COUNT / 2, listOp.getModel().getSize());
// Check *ALL* Prefix and *NO* Suffixes Marked
for (int i = 0; i < CHECKBOX_COUNT; i++) {
JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i);
if (i < CHECKBOX_COUNT / 2) {
checkBox.changeSelection(true);
} else {
checkBox.changeSelection(false);
}
}
System.out.println("######## Number of Items = " + listOp.getModel().getSize());
assertEquals("Select All Prefixes and NO Suffixes number of items is correct", 0, listOp.getModel().getSize());
// Check *NO* Prefix and *ALL* Suffixes Marked
for (int i = 0; i < CHECKBOX_COUNT; i++) {
JCheckBoxOperator checkBox = getJCheckBoxOperator(frame, i);
if (i < CHECKBOX_COUNT / 2) {
checkBox.changeSelection(false);
} else {
checkBox.changeSelection(true);
}
}
System.out.println("######## Number of Items = " + listOp.getModel().getSize());
assertEquals("Select NO Prefixes and All Suffixes number of items is correct", 0, listOp.getModel().getSize());
});
}
private JCheckBoxOperator getJCheckBoxOperator(JFrameOperator frame, int index) {
// We map first half of indexes to the Prefixes panel and the second half
// to the Suffixes panel
String labelText;
int subindex;
if (index < CHECKBOX_COUNT / 2) {
labelText = "Prefixes";
subindex = index;
} else {
labelText = "Suffixes";
subindex = index - CHECKBOX_COUNT / 2;
}
return new JCheckBoxOperator(getLabeledContainerOperator(frame, labelText), subindex);
}
}

View File

@ -0,0 +1,339 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.optionpane.OptionPaneDemo;
import static com.sun.swingset3.demos.optionpane.OptionPaneDemo.*;
import javax.swing.UIManager;
import static org.jemmy2ext.JemmyExt.*;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JComboBoxOperator;
import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 OptionPaneDemo page by opening all the dialogs
* and choosing different options in them.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.optionpane.OptionPaneDemo
* @run testng OptionPaneDemoTest
*/
public class OptionPaneDemoTest {
public static final String SOME_TEXT_TO_TYPE = "I am some text";
public static final String MESSAGE = UIManager.getString("OptionPane.messageDialogTitle");
public static final String OK = "OK";
public static final String CANCEL = "Cancel";
public static final String INPUT = UIManager.getString("OptionPane.inputDialogTitle");
public static final String TEXT_TO_TYPE = "Hooray! I'm a textField";
public static final String NO = "No";
public static final String YES = "Yes";
public static final String SELECT_AN__OPTION = UIManager.getString("OptionPane.titleText");
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(OptionPaneDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
showInputDialog(frame);
showWarningDialog(frame);
showMessageDialog(frame);
showComponentDialog(frame);
showConfirmationDialog(frame);
});
}
public void showInputDialog(JFrameOperator jfo) throws Exception {
// Cancel with text case
{
new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(INPUT);
JTextFieldOperator jto = new JTextFieldOperator(jdo);
jto.setText(SOME_TEXT_TO_TYPE);
assertTrue("Show Input Dialog cancel w/ Text", jdo.isShowing());
new JButtonOperator(jdo, CANCEL).push();
assertFalse("Show Input Dialog cancel w/ Text", jdo.isShowing());
}
// Cancel with *NO* text case
{
new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(INPUT);
assertTrue("Show Input Dialog cancel w/o Text", jdo.isShowing());
new JButtonOperator(jdo, CANCEL).push();
assertFalse("Show Input Dialog cancel w/o Text", jdo.isShowing());
}
// Text field has *NO* input
{
new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(INPUT);
assertTrue("Show Input Dialog w/o Input", jdo.isShowing());
new JButtonOperator(jdo, OK).push();
assertFalse("Show Input Dialog w/o Input", jdo.isShowing());
}
// Text field has input
{
final String enteredText = "Rambo";
new JButtonOperator(jfo, INPUT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(INPUT);
JTextFieldOperator jto = new JTextFieldOperator(jdo);
jto.setText(enteredText);
new JButtonOperator(jdo, OK).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Show Input Dialog w/ Input", jdo1.isShowing());
final String labelText = enteredText + INPUT_RESPONSE;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Text from the field made it into the dialog", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Show Input Dialog w/ Input", jdo1.isShowing());
}
}
public void showWarningDialog(JFrameOperator jfo) throws Exception {
new JButtonOperator(jfo, WARNING_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(WARNING_TITLE);
assertTrue("Show Warning Dialog", jdo.isShowing());
new JButtonOperator(jdo, OK).push();
assertFalse("Show Warning Dialog", jdo.isShowing());
}
public void showMessageDialog(JFrameOperator jfo) throws Exception {
new JButtonOperator(jfo, MESSAGE_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(MESSAGE);
assertTrue("Show Message Dialog", jdo.isShowing());
new JButtonOperator(jdo, OK).push();
assertFalse("Show Message Dialog", jdo.isShowing());
}
public void showComponentDialog(JFrameOperator jfo) throws Exception {
// Case: Cancel
{
new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE);
assertTrue("Show Component Dialog Cancel Option", jdo.isShowing());
new JButtonOperator(jdo, COMPONENT_OP5).push();
assertFalse("Show Component Dialog Cancel Option", jdo.isShowing());
}
// Case: Yes option selected
{
new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE);
new JButtonOperator(jdo, COMPONENT_OP1).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Component Dialog Example Yes Option", jdo1.isShowing());
final String labelText = COMPONENT_R1;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Component Dialog Example Yes Option", jdo1.isShowing());
}
// Case: No option selected
{
new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE);
new JButtonOperator(jdo, COMPONENT_OP2).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Component Dialog Example No Option", jdo1.isShowing());
final String labelText = COMPONENT_R2;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Component Dialog Example No Option", jdo1.isShowing());
}
// Case: Maybe option selected
{
new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE);
new JButtonOperator(jdo, COMPONENT_OP3).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Component Dialog Maybe Yes Option", jdo1.isShowing());
final String labelText = COMPONENT_R3;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Component Dialog Maybe Yes Option", jdo1.isShowing());
}
// Case: Probably option selected
{
new JButtonOperator(jfo, COMPONENT_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE);
new JButtonOperator(jdo, COMPONENT_OP4).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Component Dialog Example Probably Option", jdo1.isShowing());
final String labelText = COMPONENT_R4;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Component Dialog Example Probably Option", jdo1.isShowing());
}
// Case TextField and ComboBox functional
{
new JButtonOperator(jfo, COMPONENT_BUTTON).push();
JDialogOperator jdo = new JDialogOperator(COMPONENT_TITLE);
JTextFieldOperator jto = new JTextFieldOperator(jdo);
jto.clearText();
jto.typeText(TEXT_TO_TYPE);
JComboBoxOperator jcbo = new JComboBoxOperator(jdo);
jcbo.selectItem(2);
assertEquals("Show Component Dialog TextField", TEXT_TO_TYPE, jto.getText());
assertEquals("Show Component Dialog ComboBox", 2, jcbo.getSelectedIndex());
new JButtonOperator(jdo, "cancel").push();
}
}
public void showConfirmationDialog(JFrameOperator jfo) throws Exception {
// Case: Yes option selected
{
new JButtonOperator(jfo, CONFIRM_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(SELECT_AN__OPTION);
new JButtonOperator(jdo, YES).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Show Confirmation Dialog Yes Option", jdo1.isShowing());
final String labelText = CONFIRM_YES;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Show Confirmation Dialog Yes Option", jdo1.isShowing());
}
// Case: No option selected
{
new JButtonOperator(jfo, CONFIRM_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(SELECT_AN__OPTION);
new JButtonOperator(jdo, NO).pushNoBlock();
JDialogOperator jdo1 = new JDialogOperator(MESSAGE);
assertTrue("Show Confirmation Dialog No Option", jdo1.isShowing());
final String labelText = CONFIRM_NO;
JLabelOperator jLabelOperator = new JLabelOperator(jdo1, labelText);
assertEquals("Dialog contains appropriate text", labelText, jLabelOperator.getText());
new JButtonOperator(jdo1, OK).push();
assertFalse("Show Confirmation Dialog No Option", jdo1.isShowing());
}
// Case: Cancel option selected
{
new JButtonOperator(jfo, CONFIRM_BUTTON).pushNoBlock();
JDialogOperator jdo = new JDialogOperator(SELECT_AN__OPTION);
assertTrue("Show Confirmation Dialog Cancel Option", jdo.isShowing());
new JButtonOperator(jdo, CANCEL).push();
assertFalse("Show Confirmation Dialog Cancel Option", jdo.isShowing());
}
}
}

View File

@ -0,0 +1,160 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.progressbar.ProgressBarDemo;
import static com.sun.swingset3.demos.progressbar.ProgressBarDemo.*;
import java.awt.Component;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JProgressBarOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 ProgressBarDemo page by pressing start and stop
* buttons and checking the progress bar and the buttons state.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.progressbar.ProgressBarDemo
* @run testng ProgressBarDemoTest
*/
public class ProgressBarDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(ProgressBarDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
JButtonOperator startButton = new JButtonOperator(frame, START_BUTTON);
JButtonOperator stopButton = new JButtonOperator(frame, STOP_BUTTON);
JProgressBarOperator jpbo = new JProgressBarOperator(frame);
// Check that progress completes and corect enable/disable of start/stop buttons
checkCompleteProgress(frame, startButton, stopButton, jpbo);
// Check progess bar progression and start/stop button disabled/enabled states
checkStartStop(frame, startButton, stopButton, jpbo);
});
}
// Check that progress completes and corect enable/disable of start/stop buttons
public void checkStartStop(JFrameOperator frame, JButtonOperator startButton, JButtonOperator stopButton, JProgressBarOperator progressBar) throws Exception {
int initialProgress = progressBar.getValue();
System.out.println("initialProgress = " + initialProgress);
int maximum = progressBar.getMaximum();
startButton.pushNoBlock();
progressBar.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
int value = progressBar.getValue();
System.out.println("checkComponent1 value = " + value);
return value < maximum;
}
@Override
public String getDescription() {
return "Progress < maximum (" + maximum + ")";
}
});
stopButton.waitComponentEnabled();
progressBar.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
int value = progressBar.getValue();
System.out.println("checkComponent2 value = " + value);
return value > 0;
}
@Override
public String getDescription() {
return "Progress > 0";
}
});
int progress = progressBar.getValue();
System.out.println("progress = " + progress);
//Check that progress par has progressed and Start Button Disabled
assertTrue("Progress Bar Progressing (progress > 0, actual value: " + progress + ")", progress > 0);
assertFalse("Start Button Disabled", startButton.isEnabled());
assertTrue("Stop Button Enabled", stopButton.isEnabled());
//Wait a liitle bit longer then Press stop get progress
progressBar.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
return progressBar.getValue() > progress;
}
@Override
public String getDescription() {
return "Progress > " + progress;
}
});
stopButton.pushNoBlock();
startButton.waitComponentEnabled();
int interimProgress = progressBar.getValue();
// Check that progress par has Stopped and Start Button Disabled
assertTrue("Progress Bar Stopped "
+ "(interimProgress, actual value: " + interimProgress + " "
+ "> progress, actual value: " + progress + ")",
interimProgress > progress);
assertTrue("Start Button Enabled", startButton.isEnabled());
assertFalse("Stop Button Disabled", stopButton.isEnabled());
}
// Check progess bar progression and start/stop button disabled/enabled states
public void checkCompleteProgress(JFrameOperator frame, JButtonOperator startButton, JButtonOperator stopButton, JProgressBarOperator progressBar) throws Exception {
startButton.pushNoBlock();
progressBar.waitValue(progressBar.getMaximum());
startButton.waitComponentEnabled();
assertEquals("Complete Progress", progressBar.getMaximum(), progressBar.getValue());
assertTrue("Start Button Enabled", startButton.isEnabled());
assertFalse("Stop Button Disabled", stopButton.isEnabled());
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.scrollpane.ScrollPaneDemo;
import static com.sun.swingset3.demos.scrollpane.ScrollPaneDemo.DEMO_TITLE;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JScrollPaneOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 ScrollPaneDemo by scrolling to bottom, to top,
* to left and to right and checking scroll bar values.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.scrollpane.ScrollPaneDemo
* @run testng ScrollPaneDemoTest
*/
public class ScrollPaneDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(ScrollPaneDemo.class.getName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
JScrollPaneOperator jspo = new JScrollPaneOperator(frame);
// Set initial scrollbar positions
int initialVerticalValue = jspo.getVerticalScrollBar().getValue();
int initialHorizontalValue = jspo.getHorizontalScrollBar().getValue();
System.out.println("Initial Vertical Value = " + jspo.getVerticalScrollBar().getValue());
System.out.println("Initial HoriZontal Value = " + jspo.getHorizontalScrollBar().getValue());
// Check scroll to Bottom
{
jspo.scrollToBottom();
int currentValue = jspo.getVerticalScrollBar().getValue();
System.out.println("Final Value = " + currentValue);
assertTrue("Scroll to Bottom of Pane "
+ "(initialVerticalValue, actual value: " + initialVerticalValue + " "
+ "< currentValue, actual value = " + currentValue + ")",
initialVerticalValue < currentValue);
}
// Check scroll to Top
{
jspo.scrollToTop();
int currentValue = jspo.getVerticalScrollBar().getValue();
System.out.println("Top Scroll Final Value = " + currentValue);
assertTrue("Scroll to Top of Pane "
+ "(initialVerticalValue, actual value: " + initialVerticalValue + " "
+ "> currentValue, actual value = " + currentValue + ")",
initialVerticalValue > currentValue);
}
// Check scroll to Left
{
jspo.scrollToLeft();
int currentValue = jspo.getHorizontalScrollBar().getValue();
System.out.println("Scroll to Left Final Value = " + currentValue);
assertTrue("Scroll to Left of Pane "
+ "(initialHorizontalValue, actual value: " + initialHorizontalValue + " "
+ "> currentValue, actual value = " + currentValue + ")",
initialHorizontalValue > currentValue);
}
// Check scroll to Right
{
jspo.scrollToRight();
int currentValue = jspo.getHorizontalScrollBar().getValue();
System.out.println("Scroll to Right Final Value = " + currentValue);
assertTrue("Scroll to Right of Pane "
+ "(initialHorizontalValue, actual value: " + initialHorizontalValue + " "
+ "< currentValue, actual value = " + currentValue + ")",
initialHorizontalValue < currentValue);
}
});
}
}

View File

@ -0,0 +1,94 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.spinner.SpinnerDemo;
import static com.sun.swingset3.demos.spinner.SpinnerDemo.DEMO_TITLE;
import java.text.DecimalFormat;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JSpinnerOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 SpinnerDemo by adjusting each spinner value via
* the spinner button and checking text field value.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.spinner.SpinnerDemo
* @run testng SpinnerDemoTest
*/
public class SpinnerDemoTest {
private static final int SPINNERS_COUNT = 9;
private static final DecimalFormat decimalFormat = new DecimalFormat();
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(SpinnerDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
// Check changing different spinners
for (int i = 0; i < SPINNERS_COUNT; i++) {
changeValues(frame, i);
}
});
}
private void changeValues(JFrameOperator jfo, int spinnerIndex) throws Exception {
JSpinnerOperator spinner = new JSpinnerOperator(jfo, spinnerIndex);
JTextFieldOperator jtfo = new JTextFieldOperator(spinner);
float originalFieldValue = decimalFormat.parse(jtfo.getText()).floatValue();
float finalFieldValue;
// increment by one the value via spinner
spinner.getIncreaseOperator().push();
finalFieldValue = decimalFormat.parse(jtfo.getText()).floatValue();
// check that the value was increased
assertTrue("Increment Spinner " + spinner
+ " (originalFieldValue, actual value: " + originalFieldValue + " "
+ "< finalFieldValue, actual value = " + finalFieldValue + ")",
originalFieldValue < finalFieldValue);
// decrease value via spinner
spinner.getDecreaseOperator().push();
finalFieldValue = decimalFormat.parse(jtfo.getText()).floatValue();
// check that the value was decrimented
assertTrue("Decrement Spinner " + spinner
+ " (originalFieldValue, actual value: " + originalFieldValue + " "
+ ">= finalFieldValue, actual value = " + finalFieldValue + ")",
originalFieldValue >= finalFieldValue);
}
}

View File

@ -0,0 +1,174 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.splitpane.SplitPaneDemo;
import static com.sun.swingset3.demos.splitpane.SplitPaneDemo.*;
import java.awt.event.KeyEvent;
import javax.swing.JSplitPane;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JCheckBoxOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JRadioButtonOperator;
import org.netbeans.jemmy.operators.JSplitPaneOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import static org.jemmy2ext.JemmyExt.*;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 SplitPaneDemo by performing OneClick expansion,
* changing size of the divier, moving the divider to different positions
* and changing the divider orientation.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.splitpane.SplitPaneDemo
* @run testng SplitPaneDemoTest
*/
public class SplitPaneDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(SplitPaneDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
JSplitPaneOperator splitPane = new JSplitPaneOperator(frame);
// Toggle OneTouch Expandable
checkOneTouch(frame, splitPane, true);
checkOneTouch(frame, splitPane, false);
// Check changing divider size to minimum and maximum values
changeDividerSize(frame, splitPane, 50);
changeDividerSize(frame, splitPane, 6);
// Check moving the divider
checkDividerMoves(frame, splitPane, false);
checkDividerMoves(frame, splitPane, true);
// Check different minumum Day/Night sizes
changeMinimumSizes(frame, splitPane, 100);
changeMinimumSizes(frame, splitPane, 0);
});
}
// Check for different day and night minimum size
public void changeMinimumSizes(JFrameOperator frame, JSplitPaneOperator splitPane, int amount) throws Exception {
for (String label : new String[]{FIRST_COMPONENT_MIN_SIZE, SECOND_COMPONENT_MIN_SIZE}) {
JTextFieldOperator size = new JTextFieldOperator(getLabeledContainerOperator(frame, label));
size.enterText(Integer.toString(amount));
size.pressKey(KeyEvent.VK_ENTER);
}
checkDividerMoves(frame, splitPane, false);
checkDividerMoves(frame, splitPane, true);
}
// Check moving of divider
public void checkDividerMoves(JFrameOperator frame, JSplitPaneOperator splitPane, boolean isVertical) throws Exception {
if (isVertical) {
new JRadioButtonOperator(frame, VERTICAL_SPLIT).doClick();
} else {
new JRadioButtonOperator(frame, HORIZONTAL_SPLIT).doClick();
}
splitPane.moveDivider(0.0);
assertEquals("Move Minimum, dividerLocation is at minimumDividerLocation",
splitPane.getMinimumDividerLocation(), splitPane.getDividerLocation());
// use getMaximumDividerLocation() to move divider to here because using proportion 1.0 does not work
splitPane.moveDivider(1.0);
assertEquals("Move Maximum, dividerLocation is at maximumDividerLocation",
splitPane.getMaximumDividerLocation(), splitPane.getDividerLocation());
splitPane.moveDivider(0.5);
assertEquals("Move Middle, dividerLocation is at the artithmetic average of minimum and maximum DividerLocations",
(splitPane.getMaximumDividerLocation() + splitPane.getMinimumDividerLocation()) / 2, splitPane.getDividerLocation());
}
// Check changing the size of the divider
public void changeDividerSize(JFrameOperator frame, JSplitPaneOperator splitPane, int amount) throws Exception {
JTextFieldOperator size = new JTextFieldOperator(getLabeledContainerOperator(frame, DIVIDER_SIZE));
size.clearText();
size.typeText(Integer.toString(amount));
size.pressKey(KeyEvent.VK_ENTER);
assertEquals("Change Divider Size", amount, splitPane.getDividerSize());
}
public void checkOneTouch(JFrameOperator frame, JSplitPaneOperator splitPane, boolean oneTouch) throws Exception {
JCheckBoxOperator checkBox = new JCheckBoxOperator(frame, ONE_TOUCH_EXPANDABLE);
JButtonOperator buttonLeft = new JButtonOperator(splitPane.getDivider(), 0);
JButtonOperator buttonRight = new JButtonOperator(splitPane.getDivider(), 1);
int initDividerLocation = splitPane.getDividerLocation();
if (oneTouch) {
if (!checkBox.isSelected()) {
// uncheck
checkBox.doClick();
}
int left = getUIValue(splitPane, (JSplitPane sp) -> sp.getInsets().left);
System.out.println("left = " + left);
int right = getUIValue(splitPane, (JSplitPane sp) -> sp.getInsets().right);
System.out.println("right = " + right);
// expand full left
buttonLeft.push();
assertEquals("Expandable Left", left, splitPane.getDividerLocation());
// expand back from full left
buttonRight.push();
assertEquals("Expandable Back to Original from Left",
initDividerLocation, splitPane.getDividerLocation());
// expand all the way right
buttonRight.push();
assertEquals("Expandable Right",
splitPane.getWidth() - splitPane.getDividerSize() - right,
splitPane.getDividerLocation());
// Click to move back from right expansion
buttonLeft.push();
assertEquals("Expandable Back to Original from Right",
initDividerLocation, splitPane.getDividerLocation());
}
// Test for case where one touch expandable is disabled
if (!oneTouch) {
if (checkBox.isSelected()) {
// uncheck
checkBox.doClick();
}
assertFalse("One Touch Expandable Off", splitPane.isOneTouchExpandable());
}
}
}

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.tabbedpane.TabbedPaneDemo;
import static com.sun.swingset3.demos.tabbedpane.TabbedPaneDemo.*;
import static org.jemmy2ext.JemmyExt.getLabeledContainerOperator;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JRadioButtonOperator;
import org.netbeans.jemmy.operators.JTabbedPaneOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 TabbedPaneDemo by iterating through tab placement
* positions, opening each tab and verifying the the tab gets selected.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.tabbedpane.TabbedPaneDemo
* @run testng TabbedPaneDemoTest
*/
public class TabbedPaneDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(TabbedPaneDemo.class.getCanonicalName()).startApplication();
JFrameOperator mainFrame = new JFrameOperator(DEMO_TITLE);
for (String tp : new String[]{TOP, LEFT, BOTTOM, RIGHT}) {
testTabs(mainFrame, tp);
}
});
}
public void testTabs(JFrameOperator mainFrame, String tabPlacement) throws Exception {
ContainerOperator<?> rbCont = getLabeledContainerOperator(mainFrame, TAB_PLACEMENT);
new JRadioButtonOperator(rbCont, tabPlacement).doClick();
final String[] tabTitles = new String[]{CAMILLE, MIRANDA, EWAN, BOUNCE};
for (int i = 0; i < tabTitles.length; i++) {
String pageTitle = tabTitles[i];
JTabbedPaneOperator tabOperator = new JTabbedPaneOperator(mainFrame);
tabOperator.selectPage(pageTitle);
assertEquals("Selected tab is selected", i, tabOperator.getSelectedIndex());
}
}
}

View File

@ -0,0 +1,135 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.textfield.JHistoryTextField;
import com.sun.swingset3.demos.textfield.TextFieldDemo;
import static com.sun.swingset3.demos.textfield.TextFieldDemo.*;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import javax.swing.JFormattedTextField;
import static org.jemmy2ext.JemmyExt.*;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.QueueTool;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JPasswordFieldOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 TextFieldDemo by entering text in each field and
* checking that app reacts accordingly.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.textfield.TextFieldDemo
* @run testng TextFieldDemoTest
*/
public class TextFieldDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(TextFieldDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
historyTextField(frame);
dateTextField(frame);
passwordField(frame);
});
}
private void historyTextField(JFrameOperator jfo) throws Exception {
JTextFieldOperator jtfo = new JTextFieldOperator(jfo, new ByClassChooser(JHistoryTextField.class));
jtfo.typeText("cat");
jtfo.pressKey(KeyEvent.VK_DOWN);
jtfo.pressKey(KeyEvent.VK_DOWN);
jtfo.pressKey(KeyEvent.VK_ENTER);
final String expectedValue = "category";
jtfo.waitText(expectedValue);
assertEquals("Select History Item", expectedValue, jtfo.getText());
}
public void dateTextField(JFrameOperator jfo) throws Exception {
JTextFieldOperator jtfo = new JTextFieldOperator(jfo,
new ByClassChooser(JFormattedTextField.class));
ContainerOperator<?> containerOperator = new ContainerOperator<>(jtfo.getParent());
JButtonOperator jbo = new JButtonOperator(containerOperator, GO);
JLabelOperator dowLabel = new JLabelOperator(containerOperator);
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
// Check default date Day of the Week
jbo.push();
assertEquals("Default DOW",
calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH),
dowLabel.getText());
// Check Custom Day of the Week
calendar.set(2012, 9, 11); // Represents "Oct 11, 2012"
Date date = calendar.getTime();
String dateString = jtfo.getQueueTool().invokeAndWait(
new QueueTool.QueueAction<String>("Formatting the value using JFormattedTextField formatter") {
@Override
public String launch() throws Exception {
return ((JFormattedTextField) jtfo.getSource()).getFormatter().valueToString(date);
}
});
System.out.println("dateString = " + dateString);
jtfo.enterText(dateString);
jbo.push();
assertEquals("Custom DOW", "Thursday", dowLabel.getText());
}
public void passwordField(JFrameOperator jfo) throws Exception {
JPasswordFieldOperator password1 = new JPasswordFieldOperator(jfo, 0);
JPasswordFieldOperator password2 = new JPasswordFieldOperator(jfo, 1);
password1.typeText("password");
password2.typeText("password");
// Check Matching Passwords
assertEquals("Matching Passwords", Color.green, password1.getBackground());
assertEquals("Matching Passwords", Color.green, password2.getBackground());
// Check non-matching passwords
password2.typeText("passwereertegrs");
assertEquals("Non-Matching Passwords", Color.white, password1.getBackground());
assertEquals("Non-Matching Passwords", Color.white, password2.getBackground());
}
}

View File

@ -0,0 +1,194 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.togglebutton.DirectionPanel;
import com.sun.swingset3.demos.togglebutton.LayoutControlPanel;
import com.sun.swingset3.demos.togglebutton.ToggleButtonDemo;
import static com.sun.swingset3.demos.togglebutton.ToggleButtonDemo.*;
import java.util.function.BiFunction;
import org.jemmy2ext.JemmyExt.ByClassChooser;
import static org.jemmy2ext.JemmyExt.EXACT_STRING_COMPARATOR;
import static org.jemmy2ext.JemmyExt.getBorderTitledJPanelOperator;
import static org.jemmy2ext.JemmyExt.getLabeledContainerOperator;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JCheckBoxOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JRadioButtonOperator;
import org.netbeans.jemmy.operators.JTabbedPaneOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 ToggleButtonDemo by toggling each radio button,
* each checkbox and each location of the direction dial toggle.
* It verifies initial selected values for all the elements and checks
* that those change upon clicking. When toggling radio buttons it
* verifies that other radio buttons in the same group are not longer
* selected.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.togglebutton.ToggleButtonDemo
* @run testng ToggleButtonDemoTest
*/
public class ToggleButtonDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(ToggleButtonDemo.class.getCanonicalName()).startApplication();
JFrameOperator mainFrame = new JFrameOperator(ToggleButtonDemo.class.getAnnotation(DemoProperties.class).value());
JTabbedPaneOperator tabPane = new JTabbedPaneOperator(mainFrame);
// Radio Button Toggles
testRadioButtons(getBorderTitledJPanelOperator(mainFrame, TEXT_RADIO_BUTTONS), 3, null);
testRadioButtons(getBorderTitledJPanelOperator(mainFrame, IMAGE_RADIO_BUTTONS), 3, null);
testRadioButtons(getLabeledContainerOperator(mainFrame, PAD_AMOUNT), 3, (t, i) -> DEFAULT.equals(t));
// switch to the Check Boxes Tab
tabPane.selectPage(CHECK_BOXES);
// Check Box Toggles
ContainerOperator<?> textCheckBoxesJPanel = getBorderTitledJPanelOperator(mainFrame, TEXT_CHECKBOXES);
testCheckBox(textCheckBoxesJPanel, CHECK1, false);
testCheckBox(textCheckBoxesJPanel, CHECK2, false);
testCheckBox(textCheckBoxesJPanel, CHECK3, false);
ContainerOperator<?> imageCheckBoxesJPanel = getBorderTitledJPanelOperator(mainFrame, IMAGE_CHECKBOXES);
testCheckBox(imageCheckBoxesJPanel, CHECK1, false);
testCheckBox(imageCheckBoxesJPanel, CHECK2, false);
testCheckBox(imageCheckBoxesJPanel, CHECK3, false);
ContainerOperator<?> displayOptionsContainer = getLabeledContainerOperator(mainFrame, DISPLAY_OPTIONS);
testCheckBox(displayOptionsContainer, PAINT_BORDER, false);
testCheckBox(displayOptionsContainer, PAINT_FOCUS, true);
testCheckBox(displayOptionsContainer, ENABLED, true);
testCheckBox(displayOptionsContainer, CONTENT_FILLED, true);
// Direction Button Toggles
testToggleButtons(mainFrame);
});
}
/**
* The interface is invoked for each radio button providing its name and
* index and it should return whether the radio button has to be selected.
*/
private static interface SelectedRadioButton extends BiFunction<String, Integer, Boolean> {
}
/**
* Tests a group of radio buttons
*
* @param parent container containing the buttons
* @param radioButtonCount number of radio buttons
* @param selectedRadioButton initial selected radio button
*/
private void testRadioButtons(ContainerOperator<?> parent, int radioButtonCount, SelectedRadioButton selectedRadioButton) {
JRadioButtonOperator[] jrbo = new JRadioButtonOperator[radioButtonCount];
for (int i = 0; i < radioButtonCount; i++) {
jrbo[i] = new JRadioButtonOperator(parent, i);
if (selectedRadioButton != null && selectedRadioButton.apply(jrbo[i].getText(), i)) {
assertTrue("Radio Button " + i + " is initially selected", jrbo[i].isSelected());
} else {
assertFalse("Radio Button " + i + " is initially not selected", jrbo[i].isSelected());
}
}
for (int i = 0; i < radioButtonCount; i++) {
jrbo[i].doClick();
assertTrue("Radio Button " + i + " is selected", jrbo[i].isSelected());
for (int j = 0; j < radioButtonCount; j++) {
if (i != j) {
assertFalse("Radio Button " + j + " is not selected", jrbo[j].isSelected());
}
}
}
}
/**
* Will change the state of the CheckBox then change back to initial state.
*
* @param parent
* @param text
* @param expectedValue
* @throws Exception
*/
private void testCheckBox(ContainerOperator<?> parent, String text, boolean expectedValue) {
parent.setComparator(EXACT_STRING_COMPARATOR);
JCheckBoxOperator jcbo = new JCheckBoxOperator(parent, text);
assertEquals("Initial selection state of the checkbox '" + text + "'", expectedValue, jcbo.isSelected());
// click check box (toggle the state)
jcbo.doClick();
assertEquals("Selection state of the checkbox '" + text + "' after click", !expectedValue, jcbo.isSelected());
if (jcbo.isSelected()) {
// toggle back to not-selected state
jcbo.doClick();
assertFalse("Check Box '" + text + "' is not selected", jcbo.isSelected());
} else {
// toggle back to selected state
jcbo.doClick();
assertTrue("Check Box '" + text + "' is selected", jcbo.isSelected());
}
}
/*
* testDirectionRadioButtons(JFrameOperator) will toggle each position of
* the direction radio button panels
*/
private void testToggleButtons(JFrameOperator jfo) {
ComponentChooser directionPanelChooser = new ByClassChooser(DirectionPanel.class);
String text_Position = LayoutControlPanel.TEXT_POSITION;
ContainerOperator<?> textPositionContainer = getLabeledContainerOperator(jfo, text_Position);
ContainerOperator<?> directionPanelOperator = new ContainerOperator<>(textPositionContainer, directionPanelChooser);
testRadioButtons(directionPanelOperator, 9, (t, i) -> i == 5);
// Unfortunately, both directionPanels are in the same parent container
// so we have to use indexes here.
// There is no guarantee that if the UI changes, the code would be still
// valid in terms of which directionPanel is checked first. However, it
// does guarantee that two different directionPanels are checked.
String content_Alignment = LayoutControlPanel.CONTENT_ALIGNMENT;
ContainerOperator<?> contentAlignmentContainer = getLabeledContainerOperator(jfo, content_Alignment);
ContainerOperator<?> directionPanelOperator2 = new ContainerOperator<>(contentAlignmentContainer, directionPanelChooser,
contentAlignmentContainer.getSource() == textPositionContainer.getSource() ? 1 : 0);
testRadioButtons(directionPanelOperator2, 9, (t, i) -> i == 4);
}
}

View File

@ -0,0 +1,108 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.tree.TreeDemo;
import static com.sun.swingset3.demos.tree.TreeDemo.DEMO_TITLE;
import javax.swing.tree.TreePath;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JTreeOperator;
import static org.jemmy2ext.JemmyExt.captureDebugInfoOnFail;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 TreeDemo by expanding all collapsed nodes in the
* tree and then collapsing all the expanded nodes in the tree. It
* verifies the number of nodes expanded, number of nodes collapsed and
* number of rows in the tree in the begininng, after expanding and
* after collapsing the nodes. It also checks that the tree grows
* vertically (as ScrollPane allows it).
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.tree.TreeDemo
* @run testng TreeDemoTest
*/
public class TreeDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(TreeDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator(DEMO_TITLE);
JTreeOperator tree = new JTreeOperator(frame);
assertEquals("Initial number of rows in the tree", 4, tree.getRowCount());
int initialTreeHeight = tree.getHeight();
// expand all nodes
int expandsCount = 0;
for (int i = 0; i < tree.getRowCount(); i++) {
TreePath tp = tree.getPathForRow(i);
if (tree.getChildCount(tp) > 0 && !tree.isExpanded(tp)) {
tree.expandRow(i);
expandsCount++;
}
}
assertEquals("Number of rows expanded", 75, expandsCount);
assertEquals("Number of rows in the tree after expanding all of them",
616, tree.getRowCount());
int expandedTreeHeight = tree.getHeight();
assertTrue("Expanded tree height has increased, current "
+ expandedTreeHeight + " > initial " + initialTreeHeight,
expandedTreeHeight > initialTreeHeight);
// collapse all nodes
int collapsesCount = 0;
for (int i = tree.getRowCount() - 1; i >= 0; i--) {
TreePath tp = tree.getPathForRow(i);
if (tree.getChildCount(tp) > 0 && tree.isExpanded(tp)) {
tree.collapseRow(i);
collapsesCount++;
}
}
assertEquals("Number of rows collapsed", 76, collapsesCount);
assertEquals("Number of rows in the tree after collapsing all of them",
1, tree.getRowCount());
int collapsedTreeHeight = tree.getHeight();
assertTrue("Collpased tree height is not longer than initial, "
+ "current " + collapsedTreeHeight + " <= initial "
+ initialTreeHeight,
collapsedTreeHeight <= initialTreeHeight);
});
}
}

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.swingset3.demos.window.WindowDemo;
import static com.sun.swingset3.demos.window.WindowDemo.*;
import static org.jemmy2ext.JemmyExt.*;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.Test;
import org.netbeans.jemmy.ClassReference;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.WindowOperator;
/*
* @test
* @key headful
* @summary Verifies SwingSet3 WindowDemo by checking that separate JWindow is
* shown, it contains predefined label and no new windows are opened
* when the "Show JWindow..." button is clicked.
*
* @library /sanity/client/lib/jemmy/src
* @library /sanity/client/lib/Jemmy2Ext/src
* @library /sanity/client/lib/SwingSet3/src
* @build org.jemmy2ext.JemmyExt
* @build com.sun.swingset3.demos.window.WindowDemo
* @run testng WindowDemoTest
*/
public class WindowDemoTest {
@Test
public void test() throws Exception {
captureDebugInfoOnFail(() -> {
new ClassReference(WindowDemo.class.getCanonicalName()).startApplication();
JFrameOperator frame = new JFrameOperator();
assertEquals("Only one JWindow is shown", 1, getJWindowCount());
WindowOperator window = new WindowOperator(getJWindow());
assertTrue("JFrame is showing", frame.isShowing());
assertFalse("JFrame is not iconified", isIconified(frame));
assertTrue("JWindow is showing", window.isShowing());
final String labelText = I_HAVE_NO_SYSTEM_BORDER;
JLabelOperator jLabelOperator = new JLabelOperator(window, labelText);
assertEquals("JWindow contains the label with corresponding text", labelText, jLabelOperator.getText());
new JButtonOperator(frame, SHOW_J_WINDOW).push();
assertEquals("Only one JWindow is shown", 1, getJWindowCount());
});
}
}

View File

@ -0,0 +1,24 @@
# This file identifies the root of the test-suite hierarchy.
# It also contains test-suite configuration information.
# The list of keywords supported in the entire test suite. The
# "intermittent" keyword marks tests known to fail intermittently.
# The "randomness" keyword marks tests using randomness with test
# cases differing from run to run. (A test using a fixed random seed
# would not count as "randomness" by this definition.) Extra care
# should be taken to handle test failures of intermittent or
# randomness tests.
#
# A "headful" test requires a graphical environment to meaningfully
# run. Tests that are not headful are "headless."
keys=screenshots
# Tests that must run in othervm mode
othervm.dirs=sanity/client/SwingSet
# Tests that cannot run concurrently
exclusiveAccess.dirs=sanity/client/SwingSet
# Tests using jtreg 4.1 b13 features
requiredVersion=4.1 b13

View File

@ -0,0 +1,14 @@
# This file contains test-suite configuration information related to this portion
# of the test suite.
#
# A "screenshots" test requires a 100% headful graphical environment
# as they rely on Robot to take screenshots and move mouse.
# The list of keywords supported in this part of the test suite
keys=screenshots
# Tests that cannot run concurrently
exclusiveAccess.dirs=SwingSet
# Tests require jtreg 4.1 b13 features
#requiredVersion=4.1 b13

View File

@ -0,0 +1,614 @@
/*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.jemmy2ext;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.TitledBorder;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.DefaultCharBindingMap;
import org.netbeans.jemmy.QueueTool;
import org.netbeans.jemmy.TimeoutExpiredException;
import org.netbeans.jemmy.Waitable;
import org.netbeans.jemmy.Waiter;
import org.netbeans.jemmy.drivers.scrolling.JSpinnerDriver;
import org.netbeans.jemmy.image.StrictImageComparator;
import org.netbeans.jemmy.operators.ComponentOperator;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.FrameOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.Operator;
import org.netbeans.jemmy.util.Dumper;
import org.netbeans.jemmy.util.PNGEncoder;
import static org.testng.AssertJUnit.*;
/**
* This class solves two tasks: 1. It adds functionality that is missing in
* Jemmy 2. It references all the Jemmy API that is needed by tests so that they
* can just @build JemmyExt class and do not worry about Jemmy
*
* @author akouznet
*/
public class JemmyExt {
/**
* Statically referencing all the classes that are needed by tests so that
* they're compiled by jtreg
*/
static final Class<?>[] DEPENDENCIES = {
JSpinnerDriver.class,
DefaultCharBindingMap.class
};
public static void assertNotBlack(BufferedImage image) {
int w = image.getWidth();
int h = image.getHeight();
try {
assertFalse("All pixels are not black", IntStream.range(0, w).parallel().allMatch(x
-> IntStream.range(0, h).allMatch(y -> (image.getRGB(x, y) & 0xffffff) == 0)
));
} catch (Throwable t) {
save(image, "allPixelsAreBlack.png");
throw t;
}
}
public static void waitArmed(JButtonOperator button) {
button.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
return isArmed(button);
}
@Override
public String getDescription() {
return "Button is armed";
}
});
}
public static boolean isArmed(JButtonOperator button) {
return button.getQueueTool().invokeSmoothly(new QueueTool.QueueAction<Boolean>("getModel().isArmed()") {
@Override
public Boolean launch() throws Exception {
return ((JButton) button.getSource()).getModel().isArmed();
}
});
}
public static void waitPressed(JButtonOperator button) {
button.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
return isPressed(button);
}
@Override
public String getDescription() {
return "Button is pressed";
}
});
}
public static boolean isPressed(JButtonOperator button) {
return button.getQueueTool().invokeSmoothly(new QueueTool.QueueAction<Boolean>("getModel().isPressed()") {
@Override
public Boolean launch() throws Exception {
return ((JButton) button.getSource()).getModel().isPressed();
}
});
}
public static void assertEquals(String string, StrictImageComparator comparator, BufferedImage expected, BufferedImage actual) {
try {
assertTrue(string, comparator.compare(expected, actual));
} catch (Error err) {
save(expected, "expected.png");
save(actual, "actual.png");
throw err;
}
}
public static void assertNotEquals(String string, StrictImageComparator comparator, BufferedImage notExpected, BufferedImage actual) {
try {
assertFalse(string, comparator.compare(notExpected, actual));
} catch (Error err) {
save(notExpected, "notExpected.png");
save(actual, "actual.png");
throw err;
}
}
public static void save(BufferedImage image, String filename) {
String filepath = filename;
try {
filepath = new File(filename).getCanonicalPath();
System.out.println("Saving screenshot to " + filepath);
BufferedOutputStream file = new BufferedOutputStream(new FileOutputStream(filepath));
new PNGEncoder(file, PNGEncoder.COLOR_MODE).encode(image);
} catch (IOException ioe) {
throw new RuntimeException("Failed to save image to " + filepath, ioe);
}
}
public static void waitImageIsStill(Robot rob, ComponentOperator operator) {
operator.waitState(new ComponentChooser() {
private BufferedImage previousImage = null;
private int index = 0;
private final StrictImageComparator sComparator = new StrictImageComparator();
@Override
public boolean checkComponent(Component comp) {
BufferedImage currentImage = capture(rob, operator);
save(currentImage, "waitImageIsStill" + index + ".png");
index++;
boolean compareResult = previousImage == null ? false : sComparator.compare(currentImage, previousImage);
previousImage = currentImage;
return compareResult;
}
@Override
public String getDescription() {
return "Image of " + operator + " is still";
}
});
}
private static class ThrowableHolder {
volatile Throwable t;
}
public static void waitFor(String description, RunnableWithException r) throws Exception {
Waiter<Boolean, ThrowableHolder> waiter = new Waiter<>(new Waitable<Boolean, ThrowableHolder>() {
@Override
public Boolean actionProduced(ThrowableHolder obj) {
try {
r.run();
return true;
} catch (Throwable t) {
obj.t = t;
return null;
}
}
@Override
public String getDescription() {
return description;
}
});
ThrowableHolder th = new ThrowableHolder();
try {
waiter.waitAction(th);
} catch (TimeoutExpiredException tee) {
Throwable t = th.t;
if (t != null) {
t.addSuppressed(tee);
if (t instanceof Exception) {
throw (Exception) t;
} else if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new IllegalStateException("Unexpected exception type", t);
}
}
}
}
public static BufferedImage capture(Robot rob, ComponentOperator operator) {
Rectangle boundary = new Rectangle(operator.getLocationOnScreen(),
operator.getSize());
return rob.createScreenCapture(boundary);
}
/**
* Wraps the test code so that in case of any failure as much information as
* possible is captured
*
* @param r test code Runnable
* @throws Exception whatever exception the test may throw
*/
public static void captureDebugInfoOnFail(RunnableWithException r) throws Exception {
// TODO: Remove this once https://bugs.openjdk.java.net/browse/JDK-8151671 is fixed
try {
r.run();
System.out.println("TEST PASSED");
} catch (Throwable t) {
captureAll();
throw t;
}
}
/**
* This is a helper class which allows to catch throwables thrown in other
* threads and throw them in the main test thread
*/
public static class MultiThreadedTryCatch {
private final List<Throwable> throwables
= Collections.synchronizedList(new ArrayList<>());
/**
* Throws registered throwables. If the list of the registered
* throwables is not empty, it re-throws the first throwable in the list
* adding all others into its suppressed list. Can be used in any
* thread.
*
* @throws Exception
*/
public void throwRegistered() throws Exception {
Throwable root = null;
synchronized (throwables) {
if (!throwables.isEmpty()) {
root = throwables.remove(0);
while (!throwables.isEmpty()) {
root.addSuppressed(throwables.remove(0));
}
}
}
if (root != null) {
if (root instanceof Error) {
throw (Error) root;
} else if (root instanceof Exception) {
throw (Exception) root;
} else {
throw new AssertionError("Unexpected exception type: " + root.getClass() + " (" + root + ")");
}
}
}
/**
* Registers a throwable and adds it to the list of throwables. Can be
* used in any thread.
*
* @param t
*/
public void register(Throwable t) {
t.printStackTrace();
throwables.add(t);
}
/**
* Registers a throwable and adds it as the first item of the list of
* catched throwables.
*
* @param t
*/
public void registerRoot(Throwable t) {
t.printStackTrace();
throwables.add(0, t);
}
}
/**
* Trying to capture as much information as possible. Currently it includes
* full dump and a screenshot of the whole screen.
*/
public static void captureAll() {
PNGEncoder.captureScreen("failure.png", PNGEncoder.COLOR_MODE);
try {
Dumper.dumpAll("dumpAll.xml");
} catch (FileNotFoundException ex) {
Logger.getLogger(JemmyExt.class.getName()).log(Level.SEVERE, null, ex);
}
captureWindows();
}
/**
* Captures each showing window image using Window.paint() method.
*/
private static void captureWindows() {
try {
EventQueue.invokeAndWait(() -> {
Window[] windows = Window.getWindows();
int index = 0;
for (Window w : windows) {
if (!w.isShowing()) {
continue;
}
BufferedImage img = new BufferedImage(w.getWidth(), w.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
w.paint(g);
g.dispose();
try {
ImageIO.write(img, "png", new File("window" + index++ + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (InterruptedException | InvocationTargetException ex) {
Logger.getLogger(JemmyExt.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static interface RunnableWithException {
public void run() throws Exception;
}
public static void waitIsFocused(JFrameOperator jfo) {
jfo.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(Component comp) {
return jfo.isFocused();
}
@Override
public String getDescription() {
return "JFrame is focused";
}
});
}
public static int getJWindowCount() {
return new QueueTool().invokeAndWait(new QueueTool.QueueAction<Integer>(null) {
@Override
public Integer launch() throws Exception {
Window[] windows = Window.getWindows();
int windowCount = 0;
for (Window w : windows) {
if (w.getClass().equals(JWindow.class)) {
windowCount++;
}
}
return windowCount;
}
});
}
public static JWindow getJWindow() {
return getJWindow(0);
}
public static JWindow getJWindow(int index) {
return new QueueTool().invokeAndWait(new QueueTool.QueueAction<JWindow>(null) {
@Override
public JWindow launch() throws Exception {
Window[] windows = Window.getWindows();
int windowIndex = 0;
for (Window w : windows) {
if (w.getClass().equals(JWindow.class)) {
if (windowIndex == index) {
return (JWindow) w;
}
windowIndex++;
}
}
return null;
}
});
}
public static boolean isIconified(FrameOperator frameOperator) {
return frameOperator.getQueueTool().invokeAndWait(new QueueTool.QueueAction<Boolean>("Frame is iconified") {
@Override
public Boolean launch() throws Exception {
return (((Frame) frameOperator.getSource()).getState() & Frame.ICONIFIED) != 0;
}
});
}
public static final Operator.DefaultStringComparator EXACT_STRING_COMPARATOR
= new Operator.DefaultStringComparator(true, true);
/**
* Finds a label with the exact labelText and returns the operator for its
* parent container.
*
* @param container
* @param labelText
* @return
*/
public static ContainerOperator<?> getLabeledContainerOperator(ContainerOperator<?> container, String labelText) {
container.setComparator(EXACT_STRING_COMPARATOR);
JLabelOperator jLabelOperator = new JLabelOperator(container, labelText);
assert labelText.equals(jLabelOperator.getText());
return new ContainerOperator<>(jLabelOperator.getParent());
}
/**
* Finds a JPanel with exact title text.
*
* @param container
* @param titleText
* @return
*/
public static ContainerOperator<?> getBorderTitledJPanelOperator(ContainerOperator<?> container, String titleText) {
return new ContainerOperator<>(container, new JPanelByBorderTitleFinder(titleText, EXACT_STRING_COMPARATOR));
}
public static final QueueTool QUEUE_TOOL = new QueueTool();
/**
* Allows to find JPanel by the title text in its border.
*/
public static class JPanelByBorderTitleFinder implements ComponentChooser {
String titleText;
Operator.StringComparator comparator;
/**
* @param titleText title text pattern
* @param comparator specifies string comparison algorithm.
*/
public JPanelByBorderTitleFinder(String titleText, Operator.StringComparator comparator) {
this.titleText = titleText;
this.comparator = comparator;
}
/**
* @param titleText title text pattern
*/
public JPanelByBorderTitleFinder(String titleText) {
this(titleText, Operator.getDefaultStringComparator());
}
@Override
public boolean checkComponent(Component comp) {
assert EventQueue.isDispatchThread();
if (comp instanceof JPanel) {
return checkBorder(((JPanel) comp).getBorder());
}
return false;
}
public boolean checkBorder(Border border) {
if (border instanceof TitledBorder) {
String title = ((TitledBorder) border).getTitle();
return comparator.equals(title, titleText);
} else if (border instanceof CompoundBorder) {
CompoundBorder compoundBorder = (CompoundBorder) border;
return checkBorder(compoundBorder.getInsideBorder()) || checkBorder(compoundBorder.getOutsideBorder());
} else {
return false;
}
}
@Override
public String getDescription() {
return ("JPanel with border title text \"" + titleText + "\" with comparator " + comparator);
}
}
public static class ByClassSimpleNameChooser implements ComponentChooser {
private final String className;
public ByClassSimpleNameChooser(String className) {
this.className = className;
}
@Override
public boolean checkComponent(Component comp) {
return comp.getClass().getSimpleName().equals(className);
}
@Override
public String getDescription() {
return "Component with the simple class name of " + className;
}
}
public static class ByClassChooser implements ComponentChooser {
private final Class<?> clazz;
public ByClassChooser(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public boolean checkComponent(Component comp) {
return comp.getClass().equals(clazz);
}
@Override
public String getDescription() {
return "Component with the class of " + clazz;
}
}
public static class ByToolTipChooser implements ComponentChooser {
private final String tooltip;
public ByToolTipChooser(String tooltip) {
if (tooltip == null) {
throw new NullPointerException("Tooltip cannot be null");
}
this.tooltip = tooltip;
}
@Override
public boolean checkComponent(Component comp) {
return (comp instanceof JComponent)
? tooltip.equals(((JComponent) comp).getToolTipText())
: false;
}
@Override
public String getDescription() {
return "JComponent with the tooltip '" + tooltip + "'";
}
}
@SuppressWarnings(value = "unchecked")
public static <R, O extends Operator, S extends Component> R getUIValue(O operator, Function<S, R> getter) {
return operator.getQueueTool().invokeSmoothly(new QueueTool.QueueAction<R>("getting UI value through the queue using " + getter) {
@Override
public R launch() throws Exception {
return getter.apply((S) operator.getSource());
}
});
}
}

View File

@ -0,0 +1,4 @@
This content of this src folder was originally taken from SwingSet3 demo project: https://java.net/projects/swingset3/.
Then it was modified to increase testability and remove extra content and extra dependencies.
Do NOT modify files in it.

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Annotation type for specifying meta-data about Demo
*
* @author aim
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface DemoProperties {
String value(); // Name
String category();
String description();
String iconFile() default "";
String[] sourceFiles() default "";
}

View File

@ -0,0 +1,115 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos;
import java.awt.*;
import java.net.URI;
import java.io.IOException;
import javax.swing.*;
/**
* @author Pavel Porvatov
*/
public class DemoUtilities {
private DemoUtilities() {
// Hide constructor
}
public static void setToplevelLocation(Window toplevel, Component component,
int relativePosition) {
Rectangle compBounds = component.getBounds();
// Convert component location to screen coordinates
Point p = new Point();
SwingUtilities.convertPointToScreen(p, component);
int x;
int y;
// Set frame location to be centered on panel
switch (relativePosition) {
case SwingConstants.NORTH: {
x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
y = p.y - toplevel.getHeight();
break;
}
case SwingConstants.EAST: {
x = p.x + compBounds.width;
y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
break;
}
case SwingConstants.SOUTH: {
x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
y = p.y + compBounds.height;
break;
}
case SwingConstants.WEST: {
x = p.x - toplevel.getWidth();
y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
break;
}
case SwingConstants.NORTH_EAST: {
x = p.x + compBounds.width;
y = p.y - toplevel.getHeight();
break;
}
case SwingConstants.NORTH_WEST: {
x = p.x - toplevel.getWidth();
y = p.y - toplevel.getHeight();
break;
}
case SwingConstants.SOUTH_EAST: {
x = p.x + compBounds.width;
y = p.y + compBounds.height;
break;
}
case SwingConstants.SOUTH_WEST: {
x = p.x - toplevel.getWidth();
y = p.y + compBounds.height;
break;
}
default:
case SwingConstants.CENTER: {
x = (p.x + (compBounds.width / 2)) - (toplevel.getWidth() / 2);
y = (p.y + (compBounds.height / 2)) - (toplevel.getHeight() / 2);
}
}
toplevel.setLocation(x, y);
}
public static boolean browse(URI uri) throws IOException {
// Try using the Desktop api first
try {
Desktop desktop = Desktop.getDesktop();
desktop.browse(uri);
return true;
} catch (SecurityException e) {
e.printStackTrace();
}
return false;
}
}

View File

@ -0,0 +1,231 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos;
import java.awt.*;
import javax.swing.*;
/**
* JGridPanel
*
* @author Pavel Porvatov
*/
public class JGridPanel extends JPanel {
public static final int DEFAULT_GAP = 5;
public enum Layout {
FIRST,
CENTER,
LAST,
FILL
}
private enum ComponentType {
NO_RESIZABLE,
HORIZONTAL_FILL,
FULL
}
private final int cols;
private int bigCol = -1;
private int bigRow = -1;
private int vGap = -1;
private int hGap = -1;
public JGridPanel(int cols) {
this(cols, -1, -1);
}
public JGridPanel(int cols, int bigCol) {
this(cols, bigCol, -1);
}
public JGridPanel(int cols, int bigCol, int bigRow) {
super(new GridBagLayout());
assert cols > 0;
assert bigCol >= -1 && bigCol < cols;
assert bigRow >= -1;
this.cols = cols;
this.bigCol = bigCol;
this.bigRow = bigRow;
}
public void setVGap(int vGap) {
this.vGap = vGap;
}
public void setHGap(int hGap) {
this.hGap = hGap;
}
public JGridPanel cell() {
return cell(null, getHLayout(null), getVLayout(null), null);
}
public JGridPanel cell(Component component) {
return cell(component, getHLayout(component), getVLayout(component), null);
}
public JGridPanel cell(Component component, Layout hLayout) {
return cell(component, hLayout, getVLayout(component), null);
}
public JGridPanel cell(Component component, Layout hLayout, Layout vLayout) {
return cell(component, hLayout, vLayout, null);
}
public JGridPanel cell(Component component, Insets insets) {
assert insets != null;
return cell(component, getHLayout(component), getVLayout(component), insets);
}
private JGridPanel cell(Component component, Layout hLayout, Layout vLayout, Insets insets) {
int componentCount = getComponentCount();
int x = componentCount % cols;
int y = componentCount / cols;
int weightx = x == bigCol || (bigCol < 0 && hLayout == Layout.FILL) ? 1 : 0;
int weighty = y == bigRow || (bigRow < 0 && vLayout == Layout.FILL) ? 1 : 0;
if (insets == null) {
int topGap = y == 0 ? 0 : vGap;
int leftGap = x == 0 ? 0 : hGap;
insets = new Insets(topGap < 0 ? DEFAULT_GAP : topGap,
leftGap < 0 ? DEFAULT_GAP : leftGap, 0, 0);
}
add(component == null ? createSeparator() : component,
new GridBagConstraints(x, y,
1, 1,
weightx, weighty,
getAnchor(hLayout, vLayout), getFill(hLayout, vLayout),
insets, 0, 0));
return this;
}
public void setComponent(Component component, int col, int row) {
assert col >= 0 && col < cols;
assert row >= 0;
GridBagLayout layout = (GridBagLayout) getLayout();
for (int i = 0; i < getComponentCount(); i++) {
Component oldComponent = getComponent(i);
GridBagConstraints constraints = layout.getConstraints(oldComponent);
if (constraints.gridx == col && constraints.gridy == row) {
remove(i);
add(component == null ? createSeparator() : component, constraints);
validate();
repaint();
return;
}
}
// Cell not found
assert false;
}
private static JComponent createSeparator() {
return new JLabel();
}
private static int getFill(Layout hLayout, Layout vLayout) {
if (hLayout == Layout.FILL) {
return vLayout == Layout.FILL ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;
}
return vLayout == Layout.FILL ? GridBagConstraints.VERTICAL : GridBagConstraints.NONE;
}
private static ComponentType getComponentType(Component component) {
if (component == null
|| component instanceof JLabel
|| component instanceof JRadioButton
|| component instanceof JCheckBox
|| component instanceof JButton) {
return ComponentType.NO_RESIZABLE;
}
if (component instanceof JComboBox
|| component instanceof JTextField) {
return ComponentType.HORIZONTAL_FILL;
}
return ComponentType.FULL;
}
private static Layout getHLayout(Component component) {
if (getComponentType(component) == ComponentType.NO_RESIZABLE) {
return Layout.FIRST;
} else {
return Layout.FILL;
}
}
private static Layout getVLayout(Component component) {
if (getComponentType(component) == ComponentType.FULL) {
return Layout.FILL;
} else {
return Layout.CENTER;
}
}
private static final int[][] ANCHORS = new int[][]{
{GridBagConstraints.NORTHWEST, GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST},
{GridBagConstraints.WEST, GridBagConstraints.CENTER, GridBagConstraints.EAST},
{GridBagConstraints.SOUTHWEST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTHEAST}
};
private static int getAnchorIndex(Layout layout) {
if (layout == Layout.CENTER) {
return 1;
} else if (layout == Layout.LAST) {
return 2;
} else {
return 0;
}
}
private static int getAnchor(Layout hLayout, Layout vLayout) {
return ANCHORS[getAnchorIndex(vLayout)][getAnchorIndex(hLayout)];
}
public void setBorderEqual(int border) {
setBorder(BorderFactory.createEmptyBorder(border, border, border, border));
}
}

View File

@ -0,0 +1,237 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
*
* @author aim
*/
//<snip>Create HTML hyperlink
//<snip>Create HTML image hyperlink
public class JHyperlink extends JButton {
private static final BrowseAction defaultBrowseAction = new BrowseAction();
private URI targetURI;
private boolean visited;
private final transient Rectangle viewRect = new Rectangle();
private final transient Rectangle iconRect = new Rectangle();
private final transient Rectangle textRect = new Rectangle();
//remind(aim): lookup colors instead of hardcoding them
private Color normalForeground;
private Color activeForeground;
private Color visitedForeground;
private boolean drawUnderline = true;
static {
UIManager.put("Hyperlink.foreground", Color.blue);
UIManager.put("Hyperlink.activeForeground", Color.red);
UIManager.put("Hyperlink.visitedForeground", new Color(85, 145, 90));
}
/**
* Creates a new instance of JHyperlink
*/
public JHyperlink() {
super();
normalForeground = UIManager.getColor("Hyperlink.foreground");
activeForeground = UIManager.getColor("Hyperlink.activeForeground");
visitedForeground = UIManager.getColor("Hyperlink.visitedForeground");
setBorderPainted(false);
setContentAreaFilled(false);
setForeground(normalForeground);
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setMargin(new Insets(0, 0, 0, 0));
setAction(defaultBrowseAction);
}
/**
* Creates a new instance of JHyperlink
*/
public JHyperlink(String text) {
this();
setText(text); // override the inheritence of the action's name
}
public JHyperlink(String text, String targetURI) throws URISyntaxException {
this(text, new URI(targetURI));
}
public JHyperlink(String text, URI target) {
this(text);
setTarget(target);
}
public JHyperlink(String text, Action action) {
this(text);
setAction(action); // replaces default browse action
setText(text); // override the inheritence of the action's name
}
public JHyperlink(String text, Icon icon) {
this(text);
setIcon(icon);
}
public JHyperlink(Icon icon, String targetURI) throws URISyntaxException {
this(null, icon, targetURI);
}
public JHyperlink(String text, Icon icon, String targetURI) throws URISyntaxException {
this(text, new URI(targetURI));
setIcon(icon);
}
public JHyperlink(String text, Icon icon, URI target) {
this(text);
setIcon(icon);
setTarget(target);
}
public void setTarget(URI target) {
this.targetURI = target;
setToolTipText(target.toASCIIString());
}
public URI getTarget() {
return targetURI;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isVisited() {
return visited;
}
@Override
public void setForeground(Color foreground) {
normalForeground = foreground;
super.setForeground(foreground);
}
public void setVisitedForeground(Color visited) {
visitedForeground = visited;
}
public void setDrawUnderline(boolean drawUnderline) {
this.drawUnderline = drawUnderline;
}
public boolean getDrawUnderline() {
return drawUnderline;
}
@Override
protected void paintComponent(Graphics g) {
// Set the foreground on the fly to ensure the text is painted
// with the proper color in super.paintComponent
ButtonModel model = getModel();
if (model.isArmed()) {
super.setForeground(activeForeground);
} else if (visited) {
super.setForeground(visitedForeground);
} else {
super.setForeground(normalForeground);
}
super.paintComponent(g);
if (drawUnderline) {
Insets insets = getInsets();
viewRect.x = insets.left;
viewRect.y = insets.top;
viewRect.width = getWidth() - insets.left - insets.right;
viewRect.height = getHeight() - insets.top - insets.bottom;
int baseline = getBaseline(viewRect.width, viewRect.height);
iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;
textRect.x = textRect.y = textRect.width = textRect.height = 0;
SwingUtilities.layoutCompoundLabel(g.getFontMetrics(), getText(),
getIcon(), getVerticalAlignment(), getHorizontalAlignment(),
getVerticalTextPosition(), getHorizontalTextPosition(),
viewRect, iconRect, textRect, getIconTextGap());
// getBaseline not returning correct results, so workaround for now
if (UIManager.getLookAndFeel().getName().equals("Nimbus")) {
baseline += 7;
} else {
baseline += 3;
}
g.setColor(getForeground());
g.drawLine(textRect.x,
baseline,
textRect.x + textRect.width,
baseline);
}
}
// This action is stateless and hence can be shared across hyperlinks
private static class BrowseAction extends AbstractAction {
public BrowseAction() {
super();
}
@Override
public void actionPerformed(ActionEvent e) {
JHyperlink hyperlink = (JHyperlink) e.getSource();
URI targetURI = hyperlink.getTarget();
if (targetURI != null) {
try {
DemoUtilities.browse(targetURI);
hyperlink.setVisited(true);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex);
}
}
}
}
//</snip>
//</snip>
}

View File

@ -0,0 +1,77 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos;
import java.net.URL;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
* @author Pavel Porvatov
*/
public class ResourceManager {
private static final Logger logger = Logger.getLogger(ResourceManager.class.getName());
private final Class<?> demoClass;
// Resource bundle for internationalized and accessible text
private ResourceBundle bundle = null;
public ResourceManager(Class<?> demoClass) {
this.demoClass = demoClass;
String bundleName = demoClass.getPackage().getName() + ".resources." + demoClass.getSimpleName();
try {
bundle = ResourceBundle.getBundle(bundleName);
} catch (MissingResourceException e) {
logger.log(Level.SEVERE, "Couldn't load bundle: " + bundleName);
}
}
public String getString(String key) {
return bundle != null ? bundle.getString(key) : key;
}
public char getMnemonic(String key) {
return (getString(key)).charAt(0);
}
public ImageIcon createImageIcon(String filename, String description) {
String path = "resources/images/" + filename;
URL imageURL = demoClass.getResource(path);
if (imageURL == null) {
logger.log(Level.SEVERE, "unable to access image file: " + path);
return null;
} else {
return new ImageIcon(imageURL, description);
}
}
}

View File

@ -0,0 +1,224 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos.button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.net.URISyntaxException;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.JHyperlink;
/**
*
* @author aim
*/
@DemoProperties(
value = "JButton Demo",
category = "Controls",
description = "Demonstrates the many uses of JButton, Swing's push button component.",
sourceFiles = {
"com/sun/swingset3/demos/button/ButtonDemo.java",
"com/sun/swingset3/demos/JHyperlink.java",
"com/sun/swingset3/demos/button/resources/ButtonDemo.html",
"com/sun/swingset3/demos/button/resources/images/blogs.png",
"com/sun/swingset3/demos/button/resources/images/ButtonDemo.gif",
"com/sun/swingset3/demos/button/resources/images/document-print.png",
"com/sun/swingset3/demos/button/resources/images/earth_day.gif",
"com/sun/swingset3/demos/button/resources/images/earth_night.gif",
"com/sun/swingset3/demos/button/resources/images/edit-find.png",
"com/sun/swingset3/demos/button/resources/images/redbutton.png",
"com/sun/swingset3/demos/button/resources/images/redbutton_dark.png",
"com/sun/swingset3/demos/button/resources/images/redbutton_glow.png"
}
)
public final class ButtonDemo extends JPanel {
public static final String DEMO_TITLE = ButtonDemo.class.getAnnotation(DemoProperties.class).value();
public static final String DO_IT_AGAIN = "Do it again";
public static final String DO_IT = "Do it";
public static final String BUTTON_WITH_TEXT_AND_IMAGE = "button with text and image";
public static final String BUTTON_WITH_BACKGROUND_COLOR = "button with background color";
public static final String GO = "Go";
public static final String FIND = "Find";
public static final String IMAGE_BUTTON = "image button";
public static final String SIMPLE_BUTTON = "simple button";
public static final String GET_MORE_INFO = "Get More Info";
public static final String JAVA_BLOGS_URL = "https://blogs.oracle.com/java/";
public static final String JAVA_SE_URL = "http://www.oracle.com/technetwork/java/javase/overview/index.html";
public static final String BUTTON_WITH_ROLLOVER_IMAGE = "button with rollover image";
public static final String BUTTON_WITH_NO_BORDER = "button with no border";
public static final String CONNECT = "Connect";
public ButtonDemo() {
setToolTipText("Demonstrates JButton, Swing's push button component.");
initComponents();
setOpaque(false);
}
protected void initComponents() {
setLayout(new GridLayout(0, 1));
add(createSimpleButtonPanel());
add(createCreativeButtonPanel());
}
protected JPanel createSimpleButtonPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 8));
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
"Simple Buttons"));
//<snip>Create simple button
final JButton simpleButton = new JButton(DO_IT);
simpleButton.setToolTipText(SIMPLE_BUTTON);
//</snip>
//<snip>Add action listener using anonymous inner class
// This style is useful when the action code is tied to a
// single button instance and it's useful for simplicity
// sake to keep the action code located near the button.
// More global application actions should be implemented
// using Action classes instead.
simpleButton.addActionListener((ActionEvent event) -> {
simpleButton.setText(DO_IT_AGAIN);
// Need to force toplevel to relayout to accommodate new button size
SwingUtilities.getWindowAncestor(simpleButton).validate();
});
//</snip>
simpleButton.putClientProperty("snippetKey", "Create simple button");
panel.add(simpleButton);
//<snip>Create image button
// Image is from the Java Look and Feel Graphics Repository
JButton button = new JButton(new ImageIcon(getClass().
getResource("resources/images/document-print.png")));
button.setToolTipText(IMAGE_BUTTON);
//</snip>
button.putClientProperty("snippetKey", "Create image button");
panel.add(button);
//<snip>Create button with text and image
// Image is from the Java Look and Feel Graphics Repository
button = new JButton(FIND,
new ImageIcon(getClass().
getResource("resources/images/edit-find.png")));
button.setToolTipText(BUTTON_WITH_TEXT_AND_IMAGE);
button.setHorizontalTextPosition(JButton.LEADING);
button.setIconTextGap(6);
//</snip>
button.putClientProperty("snippetKey", "Create button with text and image");
panel.add(button);
//<snip>Create button with background color
button = new JButton(GO);
button.setBackground(Color.green);
button.setContentAreaFilled(true);
button.setOpaque(false);
button.setToolTipText(BUTTON_WITH_BACKGROUND_COLOR);
//</snip>
button.putClientProperty("snippetKey", "Create button with background color");
panel.add(button);
return panel;
}
protected JPanel createCreativeButtonPanel() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 16, 8));
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
"More Interesting Buttons"));
//<snip>Create button with no border
JButton button = new JButton();
button.setText(CONNECT);
button.setIcon(new ImageIcon(getClass().getResource("resources/images/earth_day.gif")));
button.setPressedIcon(new ImageIcon(getClass().getResource("resources/images/earth_night.gif")));
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setVerticalTextPosition(JButton.BOTTOM);
button.setHorizontalTextPosition(JButton.CENTER);
button.setIconTextGap(0);
button.setToolTipText(BUTTON_WITH_NO_BORDER);
//</snip>
button.putClientProperty("snippetKey", "Create button with no border");
panel.add(button);
//<snip>Create image button with rollover image
button = new JButton();
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setIcon(new ImageIcon(getClass().getResource("resources/images/redbutton.png")));
button.setRolloverEnabled(true);
button.setRolloverIcon(new ImageIcon(getClass().getResource("resources/images/redbutton_glow.png")));
button.setPressedIcon(new ImageIcon(getClass().getResource("resources/images/redbutton_dark.png")));
button.setToolTipText(BUTTON_WITH_ROLLOVER_IMAGE);
//</snip>
button.putClientProperty("snippetKey", "Create image button with rollover image");
panel.add(button);
//<snip>Create HTML hyperlink
JHyperlink hyperlink;
try {
hyperlink = new JHyperlink(GET_MORE_INFO, JAVA_SE_URL);
} catch (URISyntaxException use) {
use.printStackTrace();
hyperlink = new JHyperlink(GET_MORE_INFO);
}
//</snip>
hyperlink.putClientProperty("snippetKey", "Create HTML hyperlink");
panel.add(hyperlink);
//<snip>Create HTML image hyperlink
try {
hyperlink = new JHyperlink(
new ImageIcon(getClass().getResource("resources/images/blogs.png")), JAVA_BLOGS_URL);
} catch (URISyntaxException use) {
use.printStackTrace();
}
//</snip>
button.putClientProperty("snippetKey", "Create HTML image hyperlink");
panel.add(hyperlink);
return panel;
}
public static void main(String args[]) {
final ButtonDemo buttonDemo = new ButtonDemo();
javax.swing.SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame(DEMO_TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(buttonDemo);
frame.pack();
frame.setVisible(true);
});
}
}

View File

@ -0,0 +1,36 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
or visit www.oracle.com if you need additional information or have any
questions.
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<body>
<p> Today's modern GUIs often use buttons which don't look like the traditional &quot;push&quot; button. Swing's button component, <a href="http://docs.oracle.com/javase/8/docs/api/javax/swing/JButton.html">javax.swing.JButton</a>,
can be used to create both ordinary and more creative button visuals. In the end, they all perform an action when clicked.
</p>
<p>
To highlight the source code used to create a particular button, popup the context menu over that button.
</p>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

View File

@ -0,0 +1,445 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos.combobox;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.accessibility.AccessibleRelation;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import com.sun.swingset3.demos.ResourceManager;
import com.sun.swingset3.DemoProperties;
/**
* JComboBox Demo
*
* @author Jeff Dinkins
* @version 1.13 11/17/05
*/
@DemoProperties(
value = "JComboBox Demo",
category = "Controls",
description = "Demonstrates JComboBox, a control which allows the user to make a selection from a popup list",
sourceFiles = {
"com/sun/swingset3/demos/combobox/ComboBoxDemo.java",
"com/sun/swingset3/demos/ResourceManager.java",
"com/sun/swingset3/demos/combobox/resources/ComboBoxDemo.properties",
"com/sun/swingset3/demos/combobox/resources/images/brenteyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/brenthair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/brentmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/ComboBoxDemo.gif",
"com/sun/swingset3/demos/combobox/resources/images/georgeseyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/georgeshair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/georgesmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/hanseyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/hanshair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/hansmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/howardeyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/howardhair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/howardmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jameseyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jameshair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jamesmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jeffeyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jeffhair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jeffmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/joneyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jonhair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/jonmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/laraeyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/larahair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/laramouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/larryeyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/larryhair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/larrymouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/lisaeyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/lisahair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/lisamouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/michaeleyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/michaelhair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/michaelmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/philipeyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/philiphair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/philipmouth.jpg",
"com/sun/swingset3/demos/combobox/resources/images/scotteyes.jpg",
"com/sun/swingset3/demos/combobox/resources/images/scotthair.jpg",
"com/sun/swingset3/demos/combobox/resources/images/scottmouth.jpg"
}
)
public class ComboBoxDemo extends JPanel implements ActionListener {
private static final Dimension VGAP15 = new Dimension(1, 15);
private static final Dimension HGAP20 = new Dimension(20, 1);
private static final Dimension VGAP20 = new Dimension(1, 20);
private static final Dimension HGAP30 = new Dimension(30, 1);
private static final Dimension VGAP30 = new Dimension(1, 30);
private final ResourceManager resourceManager = new ResourceManager(this.getClass());
public static final String DEMO_TITLE = ComboBoxDemo.class.getAnnotation(DemoProperties.class).value();
private Face face;
private JLabel faceLabel;
private JComboBox<String> hairCB;
private JComboBox<String> eyesCB;
private JComboBox<String> mouthCB;
private JComboBox<String> presetCB;
private final Map<String, Object> parts = new HashMap<>();
/**
* main method allows us to run as a standalone demo.
*
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame(DEMO_TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ComboBoxDemo());
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* ComboBoxDemo Constructor
*/
public ComboBoxDemo() {
createComboBoxDemo();
}
private void createComboBoxDemo() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS));
add(Box.createRigidArea(VGAP20));
add(innerPanel);
add(Box.createRigidArea(VGAP20));
innerPanel.add(Box.createRigidArea(HGAP20));
// Create a panel to hold buttons
JPanel comboBoxPanel = new JPanel() {
@Override
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(resourceManager.getString("ComboBoxDemo.presets")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
comboBoxPanel.add(presetCB = createPresetComboBox());
presetCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(presetCB);
comboBoxPanel.add(Box.createRigidArea(VGAP30));
l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.hair_description")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
comboBoxPanel.add(hairCB = createHairComboBox());
hairCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(hairCB);
comboBoxPanel.add(Box.createRigidArea(VGAP15));
l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.eyes_description")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
comboBoxPanel.add(eyesCB = createEyesComboBox());
eyesCB.setAlignmentX(JComboBox.LEFT_ALIGNMENT);
l.setLabelFor(eyesCB);
comboBoxPanel.add(Box.createRigidArea(VGAP15));
l = (JLabel) comboBoxPanel.add(new JLabel(resourceManager.getString("ComboBoxDemo.mouth_description")));
l.setAlignmentX(JLabel.LEFT_ALIGNMENT);
comboBoxPanel.add(mouthCB = 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", resourceManager.getString("ComboBoxDemo.brent"));
addFace("georges", resourceManager.getString("ComboBoxDemo.georges"));
addFace("hans", resourceManager.getString("ComboBoxDemo.hans"));
addFace("howard", resourceManager.getString("ComboBoxDemo.howard"));
addFace("james", resourceManager.getString("ComboBoxDemo.james"));
addFace("jeff", resourceManager.getString("ComboBoxDemo.jeff"));
addFace("jon", resourceManager.getString("ComboBoxDemo.jon"));
addFace("lara", resourceManager.getString("ComboBoxDemo.lara"));
addFace("larry", resourceManager.getString("ComboBoxDemo.larry"));
addFace("lisa", resourceManager.getString("ComboBoxDemo.lisa"));
addFace("michael", resourceManager.getString("ComboBoxDemo.michael"));
addFace("philip", resourceManager.getString("ComboBoxDemo.philip"));
addFace("scott", resourceManager.getString("ComboBoxDemo.scott"));
// set the default face
presetCB.setSelectedIndex(0);
}
private void addFace(String name, String i18n_name) {
ImageIcon i;
String i18n_hair = resourceManager.getString("ComboBoxDemo.hair");
String i18n_eyes = resourceManager.getString("ComboBoxDemo.eyes");
String i18n_mouth = resourceManager.getString("ComboBoxDemo.mouth");
parts.put(i18n_name, name); // i18n name lookup
parts.put(name, i18n_name); // reverse name lookup
i = resourceManager.createImageIcon(name + "hair.jpg", i18n_name + i18n_hair);
parts.put(name + "hair", i);
i = resourceManager.createImageIcon(name + "eyes.jpg", i18n_name + i18n_eyes);
parts.put(name + "eyes", i);
i = resourceManager.createImageIcon(name + "mouth.jpg", i18n_name + i18n_mouth);
parts.put(name + "mouth", i);
}
private JComboBox<String> createHairComboBox() {
JComboBox<String> cb = new JComboBox<>();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
private JComboBox<String> createEyesComboBox() {
JComboBox<String> cb = new JComboBox<>();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
private JComboBox<String> createMouthComboBox() {
JComboBox<String> cb = new JComboBox<>();
fillComboBox(cb);
cb.addActionListener(this);
return cb;
}
private JComboBox<String> createPresetComboBox() {
JComboBox<String> cb = new JComboBox<>();
cb.addItem(resourceManager.getString("ComboBoxDemo.preset1"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset2"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset3"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset4"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset5"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset6"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset7"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset8"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset9"));
cb.addItem(resourceManager.getString("ComboBoxDemo.preset10"));
cb.addActionListener(this);
return cb;
}
private void fillComboBox(JComboBox<String> cb) {
cb.addItem(resourceManager.getString("ComboBoxDemo.brent"));
cb.addItem(resourceManager.getString("ComboBoxDemo.georges"));
cb.addItem(resourceManager.getString("ComboBoxDemo.hans"));
cb.addItem(resourceManager.getString("ComboBoxDemo.howard"));
cb.addItem(resourceManager.getString("ComboBoxDemo.james"));
cb.addItem(resourceManager.getString("ComboBoxDemo.jeff"));
cb.addItem(resourceManager.getString("ComboBoxDemo.jon"));
cb.addItem(resourceManager.getString("ComboBoxDemo.lara"));
cb.addItem(resourceManager.getString("ComboBoxDemo.larry"));
cb.addItem(resourceManager.getString("ComboBoxDemo.lisa"));
cb.addItem(resourceManager.getString("ComboBoxDemo.michael"));
cb.addItem(resourceManager.getString("ComboBoxDemo.philip"));
cb.addItem(resourceManager.getString("ComboBoxDemo.scott"));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == hairCB) {
String name = (String) parts.get(hairCB.getSelectedItem());
face.setHair((ImageIcon) parts.get(name + "hair"));
faceLabel.repaint();
} else if (e.getSource() == eyesCB) {
String name = (String) parts.get(eyesCB.getSelectedItem());
face.setEyes((ImageIcon) parts.get(name + "eyes"));
faceLabel.repaint();
} else if (e.getSource() == mouthCB) {
String name = (String) parts.get(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();
}
}
}
private static class Face implements Icon {
private ImageIcon hair;
private ImageIcon eyes;
private ImageIcon mouth;
void setHair(ImageIcon i) {
hair = i;
}
void setEyes(ImageIcon i) {
eyes = i;
}
void setMouth(ImageIcon i) {
mouth = i;
}
@Override
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);
}
}
@Override
public int getIconWidth() {
return 344;
}
@Override
public int getIconHeight() {
return 455;
}
}
}

View File

@ -0,0 +1,42 @@
### ComboBox Demo ###
ComboBoxDemo.accessible_description=This demo shows an example of using the JComboBox component.
ComboBoxDemo.tooltip=JComboBox demo
ComboBoxDemo.name=ComboBox Demo
ComboBoxDemo.hair=hair
ComboBoxDemo.eyes=eyes
ComboBoxDemo.mouth=mouth
ComboBoxDemo.presets=Presets:
ComboBoxDemo.preset1=Philip, Howard, Jeff
ComboBoxDemo.preset2=Jeff, Larry, Philip
ComboBoxDemo.preset3=Howard, Scott, Hans
ComboBoxDemo.preset4=Philip, Jeff, Hans
ComboBoxDemo.preset5=Brent, Jon, Scott
ComboBoxDemo.preset6=Lara, Larry, Lisa
ComboBoxDemo.preset7=James, Philip, Michael
ComboBoxDemo.preset8=Philip, Lisa, Brent
ComboBoxDemo.preset9=James, Philip, Jon
ComboBoxDemo.preset10=Lara, Jon, Scott
ComboBoxDemo.hair_description=Hair:
ComboBoxDemo.eyes_description=Eyes & Nose:
ComboBoxDemo.mouth_description=Mouth:
ComboBoxDemo.amy=Amy
ComboBoxDemo.brent=Brent
ComboBoxDemo.georges=Georges
ComboBoxDemo.hans=Hans
ComboBoxDemo.howard=Howard
ComboBoxDemo.james=James
ComboBoxDemo.jeff=Jeff
ComboBoxDemo.jon=Jon
ComboBoxDemo.lara=Lara
ComboBoxDemo.larry=Larry
ComboBoxDemo.lisa=Lisa
ComboBoxDemo.michael=Michael
ComboBoxDemo.philip=Philip
ComboBoxDemo.scott=Scott

Binary file not shown.

After

Width:  |  Height:  |  Size: 672 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -0,0 +1,404 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos.list;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Vector;
import javax.swing.*;
import com.sun.swingset3.DemoProperties;
import com.sun.swingset3.demos.ResourceManager;
/**
* 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.17 11/17/05
* @author Jeff Dinkins
*/
@DemoProperties(
value = "JList Demo",
category = "Data",
description = "Demonstrates JList, a component which supports display/editing of a data list",
sourceFiles = {
"com/sun/swingset3/demos/list/ListDemo.java",
"com/sun/swingset3/demos/list/Permuter.java",
"com/sun/swingset3/demos/ResourceManager.java",
"com/sun/swingset3/demos/list/resources/ListDemo.properties",
"com/sun/swingset3/demos/list/resources/images/blue.gif",
"com/sun/swingset3/demos/list/resources/images/cyan.gif",
"com/sun/swingset3/demos/list/resources/images/gray.gif",
"com/sun/swingset3/demos/list/resources/images/green.gif",
"com/sun/swingset3/demos/list/resources/images/ListDemo.gif",
"com/sun/swingset3/demos/list/resources/images/magenta.gif",
"com/sun/swingset3/demos/list/resources/images/red.gif",
"com/sun/swingset3/demos/list/resources/images/yellow.gif"
}
)
public final class ListDemo extends JPanel {
private static final Dimension HGAP10 = new Dimension(10, 1);
private static final Dimension VGAP10 = new Dimension(1, 10);
private static final Dimension HGAP15 = new Dimension(15, 1);
private static final Dimension HGAP30 = new Dimension(30, 1);
private final ResourceManager resourceManager = new ResourceManager(this.getClass());
public static final String DEMO_TITLE = ListDemo.class.getAnnotation(DemoProperties.class).value();
private final JList<String> list;
private JPanel prefixList;
private JPanel suffixList;
private Action prefixAction;
private Action suffixAction;
private final GeneratedListModel listModel;
/**
* main method allows us to run as a standalone demo.
*
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame(DEMO_TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ListDemo());
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* ListDemo Constructor
*/
public ListDemo() {
setLayout(new BorderLayout());
loadImages();
JLabel description = new JLabel(resourceManager.getString("ListDemo.description"));
add(description, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
centerPanel.add(Box.createRigidArea(HGAP10));
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();
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)
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);
}
private JPanel createControlPanel() {
JPanel controlPanel = new JPanel() {
private final Insets insets = new Insets(0, 4, 10, 10);
@Override
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(resourceManager.getString("ListDemo.prefixes")));
JPanel suffixPanel = new JPanel();
suffixPanel.setLayout(new BoxLayout(suffixPanel, BoxLayout.Y_AXIS));
suffixPanel.add(new JLabel(resourceManager.getString("ListDemo.suffixes")));
prefixList = new JPanel() {
private final Insets insets = new Insets(0, 4, 0, 0);
@Override
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() {
private final Insets insets = new Insets(0, 4, 0, 0);
@Override
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;
}
private final FocusListener listFocusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
JComponent c = (JComponent) e.getComponent();
c.scrollRectToVisible(new Rectangle(0, 0, c.getWidth(), c.getHeight()));
}
};
private void addPrefix(String prefix, boolean selected) {
if (prefixAction == null) {
prefixAction = new UpdatePrefixListAction(listModel);
}
final JCheckBox cb = (JCheckBox) prefixList.add(new JCheckBox(prefix));
cb.setSelected(selected);
cb.addActionListener(prefixAction);
if (selected) {
listModel.addPrefix(prefix);
}
cb.addFocusListener(listFocusListener);
}
private void addSuffix(String suffix, boolean selected) {
if (suffixAction == null) {
suffixAction = new UpdateSuffixListAction(listModel);
}
final JCheckBox cb = (JCheckBox) suffixList.add(new JCheckBox(suffix));
cb.setSelected(selected);
cb.addActionListener(suffixAction);
if (selected) {
listModel.addSuffix(suffix);
}
cb.addFocusListener(listFocusListener);
}
private static class UpdatePrefixListAction extends AbstractAction {
private final GeneratedListModel listModel;
protected UpdatePrefixListAction(GeneratedListModel listModel) {
this.listModel = listModel;
}
@Override
public void actionPerformed(ActionEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
if (cb.isSelected()) {
listModel.addPrefix(cb.getText());
} else {
listModel.removePrefix(cb.getText());
}
}
}
private static class UpdateSuffixListAction extends AbstractAction {
private final GeneratedListModel listModel;
protected UpdateSuffixListAction(GeneratedListModel listModel) {
this.listModel = listModel;
}
@Override
public void actionPerformed(ActionEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
if (cb.isSelected()) {
listModel.addSuffix(cb.getText());
} else {
listModel.removeSuffix(cb.getText());
}
}
}
private static class GeneratedListModel extends AbstractListModel<String> {
private Permuter permuter;
private final Vector<String> prefix = new Vector<>();
private final Vector<String> suffix = new Vector<>();
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();
}
@Override
public int getSize() {
return prefix.size() * suffix.size();
}
@Override
public String 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 prefix.elementAt(j % ps) + suffix.elementAt((j / ps) % ss);
}
}
private final ImageIcon[] images = new ImageIcon[7];
void loadImages() {
images[0] = resourceManager.createImageIcon("red.gif", resourceManager.getString("ListDemo.red"));
images[1] = resourceManager.createImageIcon("blue.gif", resourceManager.getString("ListDemo.blue"));
images[2] = resourceManager.createImageIcon("yellow.gif", resourceManager.getString("ListDemo.yellow"));
images[3] = resourceManager.createImageIcon("green.gif", resourceManager.getString("ListDemo.green"));
images[4] = resourceManager.createImageIcon("gray.gif", resourceManager.getString("ListDemo.gray"));
images[5] = resourceManager.createImageIcon("cyan.gif", resourceManager.getString("ListDemo.cyan"));
images[6] = resourceManager.createImageIcon("magenta.gif", resourceManager.getString("ListDemo.magenta"));
}
private class CompanyLogoListCellRenderer extends DefaultListCellRenderer {
@Override
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;
}
}
}

View File

@ -0,0 +1,100 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos.list;
/**
* 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.9 11/17/05
* @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 static final 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();
}
}

View File

@ -0,0 +1,18 @@
### List Demo ###
ListDemo.accessible_description=JList Demo
ListDemo.name=List Demo
ListDemo.tooltip=JList demo
ListDemo.prefixes=Prefixes
ListDemo.suffixes=Suffixes
ListDemo.count_label=Number of generated list entries:
ListDemo.all=All
ListDemo.none=None
ListDemo.red=Red Company Logo Image
ListDemo.yellow=Red Company Logo Image
ListDemo.blue=Blue Company Logo Image
ListDemo.gray=Gray Company Logo Image
ListDemo.green=Green Company Logo Image
ListDemo.magenta=Magenta Company Logo Image
ListDemo.cyan=Cyan Company Logo Image
ListDemo.description=<html><P STYLE="margin-left: .25in; margin-right: .25in">This demo shows how to present lists of data in two different ways. On the left is a <b>JList</b> component whose list items consist of the permutations of the checked prefixes and suffixes. The prefix and suffix checkbox columns on the right are created by using a <b>JPanel</b> with a Y Axis <b>BoxLayout</b> inside a <b>JScrollPane</b>.</P></html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 287 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

View File

@ -0,0 +1,270 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.swingset3.demos.optionpane;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.swing.*;
import com.sun.swingset3.demos.ResourceManager;
import com.sun.swingset3.DemoProperties;
/**
* JOptionPaneDemo
*
* @author Jeff Dinkins
* @version 1.11 11/17/05
*/
@DemoProperties(
value = "JOptionPane Demo",
category = "Choosers",
description = "Demonstrates JOptionPane, a component which displays standard message dialogs (question, warning, error, etc).",
sourceFiles = {
"com/sun/swingset3/demos/optionpane/OptionPaneDemo.java",
"com/sun/swingset3/demos/ResourceManager.java",
"com/sun/swingset3/demos/optionpane/resources/OptionPaneDemo.properties",
"com/sun/swingset3/demos/optionpane/resources/images/bottle.gif",
"com/sun/swingset3/demos/optionpane/resources/images/OptionPaneDemo.gif"
}
)
public class OptionPaneDemo extends JPanel {
private static final Dimension VGAP15 = new Dimension(1, 15);
private static final Dimension VGAP30 = new Dimension(1, 30);
private static final ResourceManager resourceManager = new ResourceManager(OptionPaneDemo.class);
public static final String WARNING_TITLE = resourceManager.getString("OptionPaneDemo.warningtitle");
public static final String WARNING_TEXT = resourceManager.getString("OptionPaneDemo.warningtext");
public static final String WARNING_BUTTON = resourceManager.getString("OptionPaneDemo.warningbutton");
public static final String CONFIRM_NO = resourceManager.getString("OptionPaneDemo.confirmno");
public static final String CONFIRM_YES = resourceManager.getString("OptionPaneDemo.confirmyes");
public static final String CONFIRM_QUESTION = resourceManager.getString("OptionPaneDemo.confirmquestion");
public static final String CONFIRM_BUTTON = resourceManager.getString("OptionPaneDemo.confirmbutton");
public static final String MESSAGE_TEXT = resourceManager.getString("OptionPaneDemo.messagetext");
public static final String MESSAGE_BUTTON = resourceManager.getString("OptionPaneDemo.messagebutton");
public static final String INPUT_QUESTION = resourceManager.getString("OptionPaneDemo.inputquestion");
public static final String INPUT_RESPONSE = ": " + resourceManager.getString("OptionPaneDemo.inputresponse");
public static final String INPUT_BUTTON = resourceManager.getString("OptionPaneDemo.inputbutton");
public static final String COMPONENT_R4 = resourceManager.getString("OptionPaneDemo.component_r4");
public static final String COMPONENT_R3 = resourceManager.getString("OptionPaneDemo.component_r3");
public static final String COMPONENT_R2 = resourceManager.getString("OptionPaneDemo.component_r2");
public static final String COMPONENT_R1 = resourceManager.getString("OptionPaneDemo.component_r1");
public static final String COMPONENT_TITLE = resourceManager.getString("OptionPaneDemo.componenttitle");
public static final String COMPONENT_OP5 = resourceManager.getString("OptionPaneDemo.component_op5");
public static final String COMPONENT_OP4 = resourceManager.getString("OptionPaneDemo.component_op4");
public static final String COMPONENT_OP3 = resourceManager.getString("OptionPaneDemo.component_op3");
public static final String COMPONENT_OP2 = resourceManager.getString("OptionPaneDemo.component_op2");
public static final String COMPONENT_OP1 = resourceManager.getString("OptionPaneDemo.component_op1");
public static final String COMPONENT_MESSAGE_2 = resourceManager.getString("OptionPaneDemo.componentmessage2");
public static final String COMPONENT_CB3 = resourceManager.getString("OptionPaneDemo.component_cb3");
public static final String COMPONENT_CB2 = resourceManager.getString("OptionPaneDemo.component_cb2");
public static final String COMPONENT_CB1 = resourceManager.getString("OptionPaneDemo.component_cb1");
public static final String COMPONENT_BUTTON = resourceManager.getString("OptionPaneDemo.componentbutton");
public static final String COMPONENT_TEXT_FIELD = resourceManager.getString("OptionPaneDemo.componenttextfield");
public static final String COMPONENT_MESSAGE = resourceManager.getString("OptionPaneDemo.componentmessage");
public static final String DEMO_TITLE = OptionPaneDemo.class.getAnnotation(DemoProperties.class).value();
/**
* main method allows us to run as a standalone demo.
*
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame(DEMO_TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new OptionPaneDemo());
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* OptionPaneDemo Constructor
*/
public OptionPaneDemo() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
JPanel bp = new JPanel() {
@Override
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());
add(Box.createHorizontalGlue());
add(bp);
add(Box.createHorizontalGlue());
}
private JButton createWarningDialogButton() {
Action a = new AbstractAction(WARNING_BUTTON) {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(OptionPaneDemo.this,
WARNING_TEXT,
WARNING_TITLE,
JOptionPane.WARNING_MESSAGE
);
}
};
return createButton(a);
}
private JButton createMessageDialogButton() {
Action a = new AbstractAction(MESSAGE_BUTTON) {
final URL img = getClass().getResource("resources/images/bottle.gif");
final String imagesrc = "<img src=\"" + img + "\" width=\"284\" height=\"100\">";
final String message = MESSAGE_TEXT;
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
OptionPaneDemo.this,
"<html>" + imagesrc + "<br><center>" + message + "</center><br></html>"
);
}
};
return createButton(a);
}
private JButton createConfirmDialogButton() {
Action a = new AbstractAction(CONFIRM_BUTTON) {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(OptionPaneDemo.this, CONFIRM_QUESTION);
if (result == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(OptionPaneDemo.this, CONFIRM_YES);
} else if (result == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(OptionPaneDemo.this, CONFIRM_NO);
}
}
};
return createButton(a);
}
private JButton createInputDialogButton() {
Action a = new AbstractAction(INPUT_BUTTON) {
@Override
public void actionPerformed(ActionEvent e) {
String result = JOptionPane.showInputDialog(OptionPaneDemo.this, INPUT_QUESTION);
if ((result != null) && (result.length() > 0)) {
JOptionPane.showMessageDialog(OptionPaneDemo.this,
result + INPUT_RESPONSE);
}
}
};
return createButton(a);
}
private JButton createComponentDialogButton() {
Action a = new AbstractAction(COMPONENT_BUTTON) {
@Override
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] = COMPONENT_MESSAGE;
message[1] = new JTextField(COMPONENT_TEXT_FIELD);
JComboBox<String> cb = new JComboBox<>();
cb.addItem(COMPONENT_CB1);
cb.addItem(COMPONENT_CB2);
cb.addItem(COMPONENT_CB3);
message[2] = cb;
message[3] = COMPONENT_MESSAGE_2;
// Options
String[] options = {
COMPONENT_OP1, COMPONENT_OP2, COMPONENT_OP3, COMPONENT_OP4, COMPONENT_OP5};
int result = JOptionPane.showOptionDialog(
OptionPaneDemo.this, // the parent that the dialog blocks
message, // the dialog message array
COMPONENT_TITLE, // 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(OptionPaneDemo.this, COMPONENT_R1);
break;
case 1: // no
JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R2);
break;
case 2: // maybe
JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R3);
break;
case 3: // probably
JOptionPane.showMessageDialog(OptionPaneDemo.this, COMPONENT_R4);
break;
default:
break;
}
}
};
return createButton(a);
}
private JButton createButton(Action a) {
JButton b = new JButton() {
@Override
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;
}
}

View File

@ -0,0 +1,42 @@
### OptionPane Demo ###
OptionPaneDemo.accessible_description=The OptionPane Demo shows examples of using JOptionPane to generate different common option dialog boxes
OptionPaneDemo.tooltip=JOptionPane Demo
OptionPaneDemo.name=Option Pane Demo
OptionPaneDemo.warningbutton=Show Warning Dialog
OptionPaneDemo.componentbutton=Show Component Dialog
OptionPaneDemo.inputbutton=Show Input Dialog
OptionPaneDemo.confirmbutton=Show Confirmation Dialog
OptionPaneDemo.messagebutton=Show Message Dialog
OptionPaneDemo.warningtitle=Warning Dialog Example
OptionPaneDemo.warningtext=<html><P><font color=black>This is a test of the <font color=red><b>Emergency Broadcast System</b></font>. <i><b>This is <br> only a test</b></i>. The webmaster of your local intranet, in voluntary <br> cooperation with the <font color=blue><b>Federal</b></font> and <font color=blue><b>State</b></font> authorities, have <br> developed this system to keep you informed in the event of an <br> emergency. If this had been an actual emergency, the signal you <br> just heard would have been followed by official information, news <br> or instructions. This concludes this test of the <font color=red><b>Emergency <br> Broadcast System</b></font>.</font></P><P><br>Developer Note: This dialog demo used HTML for text formatting.</P></html>
OptionPaneDemo.messagetext=Message in a Bottle (yeah)
OptionPaneDemo.confirmquestion=Is the sun shining outside today?
OptionPaneDemo.confirmyes=<html>Well what are you doing playing on the computer?<br> Get outside! Take a trip to the beach! Get a little sun!</html>
OptionPaneDemo.confirmno=Well good thing you're inside protected from the elements!
OptionPaneDemo.inputquestion=What is your favorite movie?
OptionPaneDemo.inputresponse=That was a pretty good movie!
OptionPaneDemo.componenttitle=Component Dialog Example
OptionPaneDemo.componentmessage=<html>JOptionPane can contain as many components <br> as you want, such as a text field:</html>
OptionPaneDemo.componenttextfield=or a combobox:
OptionPaneDemo.component_cb1=item 1
OptionPaneDemo.component_cb2=item 2
OptionPaneDemo.component_cb3=item 3
OptionPaneDemo.componentmessage2=<html>JOptionPane can also show as many options <br> as you want:</html>
OptionPaneDemo.component_op1=Yes
OptionPaneDemo.component_op2=No
OptionPaneDemo.component_op3=Maybe
OptionPaneDemo.component_op4=Probably
OptionPaneDemo.component_op5=Cancel
OptionPaneDemo.component_r1=Upbeat and positive! I like that! Good choice.
OptionPaneDemo.component_r2=Definitely not, I wouldn't do it either.
OptionPaneDemo.component_r3=<html><font color=black> Mmmm.. yes, the situation is unclear at this <br> time. Check back when you know for sure.</font></html>
OptionPaneDemo.component_r4=<html><font color=black>You know you want to. I think you should <br> have gone for broke and pressed "Yes".</font></html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 881 B

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