undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 4513402
@summary AWTEventMulticaster.getListeners throws unexpected ArrayStoreException
*/
import java.awt.AWTEventMulticaster;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentListener;
import java.awt.event.FocusListener;
public class ArrayStoreException {
public static void main(String[] args) throws Exception {
ComponentListener mc =
AWTEventMulticaster.add(
new ComponentAdapter() {},
new ComponentAdapter() {});
if (AWTEventMulticaster.getListeners(mc, FocusListener.class).length == 0) {
System.out.println("OKAY");
} else {
System.out.println("empty array expected");
throw new RuntimeException("Test failed");
}
}
}

View file

@ -0,0 +1,323 @@
/*
* Copyright (c) 2003, 2023, 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.
*/
/*
@test
@bug 4370733
@summary AWTKeyStroke's getAWTKeyStroke(String) and toString() method aren't symmetric
*/
import java.awt.AWTKeyStroke;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.KeyStroke;
public class ToStringTest {
/* Note this test is deliberately testing the deprecated constants
* as well as their replacements.
*/
@SuppressWarnings("deprecation")
public static final int[] modifiers = {
0,
InputEvent.SHIFT_MASK,
InputEvent.CTRL_MASK,
InputEvent.META_MASK,
InputEvent.ALT_MASK,
InputEvent.ALT_GRAPH_MASK,
InputEvent.BUTTON1_MASK,
InputEvent.BUTTON2_MASK,
InputEvent.BUTTON3_MASK,
InputEvent.SHIFT_DOWN_MASK,
InputEvent.CTRL_DOWN_MASK,
InputEvent.META_DOWN_MASK,
InputEvent.ALT_DOWN_MASK,
InputEvent.BUTTON1_DOWN_MASK,
InputEvent.BUTTON2_DOWN_MASK,
InputEvent.BUTTON3_DOWN_MASK,
InputEvent.ALT_GRAPH_DOWN_MASK
};
public static final int[] keys = {
KeyEvent.VK_A,
KeyEvent.VK_B,
KeyEvent.VK_C,
KeyEvent.VK_D,
KeyEvent.VK_E,
KeyEvent.VK_F,
KeyEvent.VK_G,
KeyEvent.VK_H,
KeyEvent.VK_I,
KeyEvent.VK_J,
KeyEvent.VK_K,
KeyEvent.VK_L,
KeyEvent.VK_M,
KeyEvent.VK_N,
KeyEvent.VK_O,
KeyEvent.VK_P,
KeyEvent.VK_Q,
KeyEvent.VK_R,
KeyEvent.VK_S,
KeyEvent.VK_T,
KeyEvent.VK_U,
KeyEvent.VK_V,
KeyEvent.VK_W,
KeyEvent.VK_X,
KeyEvent.VK_Y,
KeyEvent.VK_Z,
KeyEvent.VK_0,
KeyEvent.VK_1,
KeyEvent.VK_2,
KeyEvent.VK_3,
KeyEvent.VK_4,
KeyEvent.VK_5,
KeyEvent.VK_6,
KeyEvent.VK_7,
KeyEvent.VK_8,
KeyEvent.VK_9,
KeyEvent.VK_COMMA,
KeyEvent.VK_PERIOD,
KeyEvent.VK_SLASH,
KeyEvent.VK_SEMICOLON,
KeyEvent.VK_EQUALS,
KeyEvent.VK_OPEN_BRACKET,
KeyEvent.VK_BACK_SLASH,
KeyEvent.VK_CLOSE_BRACKET,
KeyEvent.VK_ENTER,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_TAB,
KeyEvent.VK_CANCEL,
KeyEvent.VK_CLEAR,
KeyEvent.VK_SHIFT,
KeyEvent.VK_CONTROL,
KeyEvent.VK_ALT,
KeyEvent.VK_PAUSE,
KeyEvent.VK_CAPS_LOCK,
KeyEvent.VK_ESCAPE,
KeyEvent.VK_SPACE,
KeyEvent.VK_PAGE_UP,
KeyEvent.VK_PAGE_DOWN,
KeyEvent.VK_END,
KeyEvent.VK_HOME,
KeyEvent.VK_LEFT,
KeyEvent.VK_UP,
KeyEvent.VK_RIGHT,
KeyEvent.VK_DOWN,
KeyEvent.VK_ADD,
KeyEvent.VK_SEPARATOR,
KeyEvent.VK_SUBTRACT,
KeyEvent.VK_DECIMAL,
KeyEvent.VK_DIVIDE,
KeyEvent.VK_DELETE,
KeyEvent.VK_NUM_LOCK,
KeyEvent.VK_SCROLL_LOCK,
KeyEvent.VK_WINDOWS,
KeyEvent.VK_CONTEXT_MENU,
KeyEvent.VK_F1,
KeyEvent.VK_F2,
KeyEvent.VK_F3,
KeyEvent.VK_F4,
KeyEvent.VK_F5,
KeyEvent.VK_F6,
KeyEvent.VK_F7,
KeyEvent.VK_F8,
KeyEvent.VK_F9,
KeyEvent.VK_F10,
KeyEvent.VK_F11,
KeyEvent.VK_F12,
KeyEvent.VK_F13,
KeyEvent.VK_F14,
KeyEvent.VK_F15,
KeyEvent.VK_F16,
KeyEvent.VK_F17,
KeyEvent.VK_F18,
KeyEvent.VK_F19,
KeyEvent.VK_F20,
KeyEvent.VK_F21,
KeyEvent.VK_F22,
KeyEvent.VK_F23,
KeyEvent.VK_F24,
KeyEvent.VK_PRINTSCREEN,
KeyEvent.VK_INSERT,
KeyEvent.VK_HELP,
KeyEvent.VK_META,
KeyEvent.VK_BACK_QUOTE,
KeyEvent.VK_QUOTE,
KeyEvent.VK_KP_UP,
KeyEvent.VK_KP_DOWN,
KeyEvent.VK_KP_LEFT,
KeyEvent.VK_KP_RIGHT,
KeyEvent.VK_DEAD_GRAVE,
KeyEvent.VK_DEAD_ACUTE,
KeyEvent.VK_DEAD_CIRCUMFLEX,
KeyEvent.VK_DEAD_TILDE,
KeyEvent.VK_DEAD_MACRON,
KeyEvent.VK_DEAD_BREVE,
KeyEvent.VK_DEAD_ABOVEDOT,
KeyEvent.VK_DEAD_DIAERESIS,
KeyEvent.VK_DEAD_ABOVERING,
KeyEvent.VK_DEAD_DOUBLEACUTE,
KeyEvent.VK_DEAD_CARON,
KeyEvent.VK_DEAD_CEDILLA,
KeyEvent.VK_DEAD_OGONEK,
KeyEvent.VK_DEAD_IOTA,
KeyEvent.VK_DEAD_VOICED_SOUND,
KeyEvent.VK_DEAD_SEMIVOICED_SOUND,
KeyEvent.VK_AMPERSAND,
KeyEvent.VK_ASTERISK,
KeyEvent.VK_QUOTEDBL,
KeyEvent.VK_LESS,
KeyEvent.VK_GREATER,
KeyEvent.VK_BRACELEFT,
KeyEvent.VK_BRACERIGHT,
KeyEvent.VK_AT,
KeyEvent.VK_COLON,
KeyEvent.VK_CIRCUMFLEX,
KeyEvent.VK_DOLLAR,
KeyEvent.VK_EURO_SIGN,
KeyEvent.VK_EXCLAMATION_MARK,
KeyEvent.VK_INVERTED_EXCLAMATION_MARK,
KeyEvent.VK_LEFT_PARENTHESIS,
KeyEvent.VK_NUMBER_SIGN,
KeyEvent.VK_MINUS,
KeyEvent.VK_PLUS,
KeyEvent.VK_RIGHT_PARENTHESIS,
KeyEvent.VK_UNDERSCORE,
KeyEvent.VK_FINAL,
KeyEvent.VK_CONVERT,
KeyEvent.VK_NONCONVERT,
KeyEvent.VK_ACCEPT,
KeyEvent.VK_MODECHANGE,
KeyEvent.VK_KANA,
KeyEvent.VK_KANJI,
KeyEvent.VK_ALPHANUMERIC,
KeyEvent.VK_KATAKANA,
KeyEvent.VK_HIRAGANA,
KeyEvent.VK_FULL_WIDTH,
KeyEvent.VK_HALF_WIDTH,
KeyEvent.VK_ROMAN_CHARACTERS,
KeyEvent.VK_ALL_CANDIDATES,
KeyEvent.VK_PREVIOUS_CANDIDATE,
KeyEvent.VK_CODE_INPUT,
KeyEvent.VK_JAPANESE_KATAKANA,
KeyEvent.VK_JAPANESE_HIRAGANA,
KeyEvent.VK_JAPANESE_ROMAN,
KeyEvent.VK_KANA_LOCK,
KeyEvent.VK_INPUT_METHOD_ON_OFF,
KeyEvent.VK_AGAIN,
KeyEvent.VK_UNDO,
KeyEvent.VK_COPY,
KeyEvent.VK_PASTE,
KeyEvent.VK_CUT,
KeyEvent.VK_FIND,
KeyEvent.VK_PROPS,
KeyEvent.VK_STOP,
KeyEvent.VK_COMPOSE,
KeyEvent.VK_ALT_GRAPH,
KeyEvent.VK_BEGIN,
KeyEvent.VK_NUMPAD0,
KeyEvent.VK_NUMPAD1,
KeyEvent.VK_NUMPAD2,
KeyEvent.VK_NUMPAD3,
KeyEvent.VK_NUMPAD4,
KeyEvent.VK_NUMPAD5,
KeyEvent.VK_NUMPAD6,
KeyEvent.VK_NUMPAD7,
KeyEvent.VK_NUMPAD8,
KeyEvent.VK_NUMPAD9
};
public static void main(String[] args) throws Exception {
System.err.println("**** Testing AWTKeyStrokes");
for (int n_key=0; n_key < keys.length; n_key++) {
for (int n_mod=0; n_mod < modifiers.length; n_mod++) {
checkStroke(AWTKeyStroke.getAWTKeyStroke(keys[n_key],
modifiers[n_mod],
true));
checkStroke(AWTKeyStroke.getAWTKeyStroke(keys[n_key],
modifiers[n_mod],
false));
}
}
System.err.println("**** Testing Swing KeyStrokes");
for (int n_key=0; n_key < keys.length; n_key++) {
for (int n_mod=0; n_mod < modifiers.length; n_mod++) {
checkStroke(KeyStroke.getKeyStroke(keys[n_key],
modifiers[n_mod],
true));
checkStroke(KeyStroke.getKeyStroke(keys[n_key],
modifiers[n_mod],
false));
}
}
Character a = Character.valueOf('a');
System.err.println("**** Testing KEY_TYPED AWTKeyStrokes");
for (int n_mod = 0; n_mod < modifiers.length; n_mod++) {
checkStroke(AWTKeyStroke.getAWTKeyStroke(a, modifiers[n_mod]));
}
System.err.println("**** Testing KEY_TYPED Swing KeyStrokes");
for (int n_mod = 0; n_mod < modifiers.length; n_mod++) {
checkStroke(KeyStroke.getKeyStroke(a, modifiers[n_mod]));
}
System.out.println("Test passed.");
}
public static void checkStroke(AWTKeyStroke original) {
System.err.println("AWT Original >> " + original);
AWTKeyStroke copy = AWTKeyStroke.getAWTKeyStroke(original.toString());
// System.err.println("AWT Copy >> " + copy);
if (!original.equals(copy)) {
System.out.println("AWT bad copy for VK= 0x" +
Integer.toString(original.getKeyCode(), 16));
throw new RuntimeException("Test Failed: for " + original);
}
}
public static void checkStroke(KeyStroke original) {
System.err.println("Swing Original >> " + original);
KeyStroke copy = KeyStroke.getKeyStroke(original.toString());
// System.err.println("Swing Copy >> " + copy);
if (!original.equals(copy)) {
System.out.println("Swing bad copy for VK= 0x" +
Integer.toString(original.getKeyCode(), 16));
throw new RuntimeException("Test Failed: for " + original);
}
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2007, 2014, 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.*;
import java.awt.image.ColorModel;
/*
* @test
* @summary Check no exception occurrence when running AlphaComposite getInstance(),
* createContext(), getAlpha(), getRule(), hashCode() methods in headless mode
* @run main/othervm -Djava.awt.headless=true HeadlessAlphaComposite
*/
public class HeadlessAlphaComposite {
public static void main(String args[]) {
AlphaComposite ac;
ac = AlphaComposite.getInstance(AlphaComposite.CLEAR);
ac = AlphaComposite.getInstance(AlphaComposite.DST_IN);
ac = AlphaComposite.getInstance(AlphaComposite.DST_OUT);
ac = AlphaComposite.getInstance(AlphaComposite.DST_OVER);
ac = AlphaComposite.getInstance(AlphaComposite.SRC);
ac = AlphaComposite.getInstance(AlphaComposite.SRC_IN);
ac = AlphaComposite.getInstance(AlphaComposite.SRC_OUT);
ac = AlphaComposite.getInstance(AlphaComposite.DST_IN);
ac = AlphaComposite.getInstance(AlphaComposite.SRC, (float) 0.5);
ac = AlphaComposite.getInstance(AlphaComposite.SRC, (float) 0.5);
CompositeContext cc = ac.createContext(ColorModel.getRGBdefault(),
ColorModel.getRGBdefault(),
new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
ac = AlphaComposite.getInstance(AlphaComposite.SRC, (float) 0.5);
float alpha = ac.getAlpha();
ac = AlphaComposite.getInstance(AlphaComposite.SRC, (float) 0.5);
int rule = ac.getRule();
ac = AlphaComposite.getInstance(AlphaComposite.SRC, (float) 0.5);
int hc = ac.hashCode();
}
}

View file

@ -0,0 +1,45 @@
/*
* Copyright (c) 2010, 2013, 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.
*/
/*
* @test
* @bug 6918065
* @summary Test for passing NaN as alpha
* should throw IllegalArgumentException
*/
import java.awt.*;
public class TestAlphaCompositeForNaN {
public static void main(String[] args) {
try {
AlphaComposite a = AlphaComposite.getInstance(AlphaComposite.DST, Float.NaN);
System.out.println("Failed");
throw new RuntimeException(a + " failed to throw IllegalArgumentException for alpha = " + Float.NaN);
}
catch (IllegalArgumentException ie) {
System.out.println("Passed");
System.out.println("Caught " + ie);
}
}
}

View file

@ -0,0 +1,238 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, JetBrains s.r.o.. 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.
*/
/**
* @test
* @key headful
* @bug 8266079 8298887
* @summary [macosx] window rendering alpha composite test
* @author Alexey Ushakov
* @run main WindowAlphaCompositeTest
* @requires (os.family == "mac")
*/
import java.awt.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
public class WindowAlphaCompositeTest
{
interface Validate {
boolean validate(int x, int y, Color c);
}
static Color RED128 = new Color(128, 0, 0);
static Color BLUE128 = new Color(0, 0, 128);
static Color PURPLE128 = new Color(128, 0, 128);
static Color RED_BLUE24 = new Color(230, 0, 24);
static Validate redBlackCheck = (int x, int y, Color c) -> {
Color expColor = Color.RED;
if (x > 24 && x < 75) {
expColor = Color.BLACK;
}
return validateColor(c, expColor);
};
static Validate redBlueCheck = (int x, int y, Color c) -> {
Color expColor = Color.RED;
if (x > 24 && x < 75) {
expColor = Color.BLUE;
}
return validateColor(c, expColor);
};
static Validate redCheck = (int x, int y, Color c) -> {
Color expColor = Color.RED;
return validateColor(c, expColor);
};
static Validate redRed128Check = (int x, int y, Color c) -> {
Color expColor = Color.RED;
if (x > 24 && x < 75) {
expColor = RED128;
}
return validateColor(c, expColor);
};
static Validate redBlue128Check = (int x, int y, Color c) -> {
Color expColor = Color.RED;
if (x > 24 && x < 75) {
expColor = BLUE128;
}
return validateColor(c, expColor);
};
static Validate purple128Check = (int x, int y, Color c) -> {
Color expColor = Color.RED;
if (x > 24 && x < 75) {
expColor = PURPLE128;
}
return validateColor(c, expColor);
};
static Validate redBlue24Check = (int x, int y, Color c) -> {
Color expColor = Color.RED;
if (x > 24 && x < 75) {
expColor = RED_BLUE24;
}
return validateColor(c, expColor);
};
static Object[][] alphaComposites = {
{AlphaComposite.Clear, redBlackCheck},
{AlphaComposite.Dst, redCheck},
{AlphaComposite.DstAtop, redCheck},
{AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0f), redCheck},
{AlphaComposite.getInstance(AlphaComposite.DST_IN, 0.5f), redRed128Check},
{AlphaComposite.getInstance(AlphaComposite.DST_OUT, 1.0f), redBlackCheck},
{AlphaComposite.getInstance(AlphaComposite.DST_OUT, 0.5f), redRed128Check},
{AlphaComposite.DstOver, redCheck},
{AlphaComposite.Src, redBlueCheck},
{AlphaComposite.SrcAtop, redBlueCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_IN, 1.0f), redBlueCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.5f), redBlue128Check},
{AlphaComposite.SrcOut, redBlackCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f), redBlueCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f), purple128Check},
//Uncomment after resolving issues with Xor mode on Metal
//{AlphaComposite.Xor, redBlackCheck},
{AlphaComposite.getInstance(AlphaComposite.DST_OUT, 0.0f), redCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.0f), redBlackCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.01f), redCheck},
{AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.099f), redBlue24Check}
};
private static final int TD = 10;
static WindowAlphaCompositeTest theTest;
private final Robot robot;
private JFrame frame;
private final static int DELAY = 1000;
public WindowAlphaCompositeTest() {
try {
robot = new Robot();
} catch (AWTException ex) {
throw new RuntimeException(ex);
}
}
public void performTest(final AlphaComposite ac, Validate validate) {
runSwing(() -> {
frame = new JFrame();
frame.setBounds(100, 100, 100, 150);
JComponent contentPane = (JComponent) frame.getContentPane();
JPanel comp = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
renderComposite((Graphics2D) g, ac, 100, 100);
}
};
contentPane.add(comp);
comp.setBackground(Color.BLACK);
frame.setVisible(true);
});
robot.delay(DELAY);
for (int px = 10; px <= 90; px += 20) {
Color c = getTestPixel(px, 90);
if (!validate.validate(px, 90, c)) {
throw new RuntimeException("Test failed. Incorrect color " + c +
" at (" + px + "," + 90 + ") with composite rule=" + ac.getRule() +
" alpha=" + ac.getAlpha());
}
}
runSwing(() -> frame.dispose());
frame = null;
}
public void renderComposite(Graphics2D g, AlphaComposite ac,
int w, int h)
{
// draw stage
// outer rect
g.setComposite(AlphaComposite.SrcOver); // as default
g.setPaint(Color.red);
g.fillRect(0, 0, w, h);
// inner rect
g.setComposite(ac);
g.setPaint(Color.blue);
g.fillRect(w/4, h/4, w/2, h/2);
}
private Color getTestPixel(int x, int y) {
Rectangle bounds = frame.getBounds();
BufferedImage screenImage = robot.createScreenCapture(bounds);
int rgb = screenImage.getRGB(x, y);
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
return new Color(red, green, blue);
}
private static boolean validateColor(Color c, Color expected) {
return Math.abs(c.getRed() - expected.getRed()) <= TD &&
Math.abs(c.getGreen() - expected.getGreen()) <= TD &&
Math.abs(c.getBlue() - expected.getBlue()) <= TD;
}
public void dispose() {
if (frame != null) {
frame.dispose();
frame = null;
}
}
private static void runSwing(Runnable r) {
try {
SwingUtilities.invokeAndWait(r);
} catch (InterruptedException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
if (!System.getProperty("os.name").contains("OS X")) {
System.out.println("This test is for MacOS only. Automatically passed on other platforms.");
return;
}
try {
for (Object[] alphaComposite : alphaComposites) {
if (alphaComposite[1] == null) continue;
runSwing(() -> theTest = new WindowAlphaCompositeTest());
theTest.performTest((AlphaComposite) alphaComposite[0], (Validate) alphaComposite[1]);
}
} finally {
if (theTest != null) {
runSwing(() -> theTest.dispose());
}
}
}
}

View file

@ -0,0 +1,241 @@
/*
* Copyright (c) 2001, 2019, 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.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.VolatileImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import static java.awt.image.BufferedImage.TYPE_INT_RGB;
/*
* @test
* @bug 4469881 8217263 8218682
* @key headful
* @summary Verifies that dashed rectangles drawn to the screen line
* up with their undashed counterparts
* @author flar
* @run main/othervm -Dsun.java2d.uiScale=1 DashOffset
*/
public class DashOffset {
private static final BasicStroke dash =
new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f,
new float[] {2.0f, 2.0f}, 0.0f);
private static final Color COLOR1 = Color.BLUE;
private static final Color COLOR2 = Color.GREEN;
private static final Color BACKGROUND = Color.WHITE;
private static final int WIDTH = 20;
private static final int HEIGHT = 20;
private static final int OFFSET = 2;
private static final int MAX_DASH_LENGTH = 3;
public static void main(String[] argv) throws Exception {
final boolean saveImage = argv.length > 0 && "-save".equals(argv[0]);
final BufferedImage img = new BufferedImage(WIDTH, HEIGHT,
TYPE_INT_RGB);
try {
draw(img);
validate(img);
} finally {
if (saveImage) {
save(img, "bufferedImage.png");
}
}
BufferedImage snapshot = null;
try {
final GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
if (gc.getColorModel() instanceof IndexColorModel) {
System.err.println("Skipping VolatileImage because of IndexColorModel");
return;
}
VolatileImage vi = gc.createCompatibleVolatileImage(WIDTH, HEIGHT);
int attempt = 0;
do {
vi.validate(gc);
draw(vi);
snapshot = vi.getSnapshot();
} while (vi.contentsLost() && ++attempt <= 10);
if (attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
validate(snapshot);
} finally {
if (saveImage && snapshot != null) {
save(snapshot, "volatileImage.png");
}
}
}
private static void draw(final Image img) {
Graphics g = img.getGraphics();
g.setColor(BACKGROUND);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(COLOR1);
g.drawRect(OFFSET, OFFSET, WIDTH - OFFSET * 2, HEIGHT - OFFSET * 2);
g.setColor(COLOR2);
g.clipRect(OFFSET, OFFSET, WIDTH - OFFSET * 2 + 1, HEIGHT - OFFSET * 2 + 1);
((Graphics2D) g).setStroke(dash);
g.drawRect(OFFSET, OFFSET, WIDTH - OFFSET * 2, HEIGHT - OFFSET * 2);
g.dispose();
}
private static void validate(final BufferedImage img) {
checkHorizontalLine(img, OFFSET);
checkHorizontalLine(img, HEIGHT - OFFSET);
checkVerticalLine(img, OFFSET);
checkVerticalLine(img, WIDTH - OFFSET);
checkCorners(img);
}
private static void checkHorizontalLine(final BufferedImage img,
final int y) {
int prev = img.getRGB(OFFSET, y);
int curr;
int count = 1;
checkColor(OFFSET, y, prev, COLOR1, COLOR2);
for (int x = OFFSET + 1; x <= WIDTH - OFFSET; x++) {
curr = img.getRGB(x, y);
if (curr != prev) {
checkColor(x, y, curr, COLOR1, COLOR2);
checkCount(x, y, count);
prev = curr;
count = 1;
} else {
count++;
}
if (x < WIDTH - OFFSET) {
checkColor(x, y - 1, img.getRGB(x, y - 1), BACKGROUND);
checkColor(x, y + 1, img.getRGB(x, y + 1), BACKGROUND);
}
}
checkCount(WIDTH - OFFSET, y, count);
}
private static void checkVerticalLine(final BufferedImage img,
final int x) {
int prev = img.getRGB(x, OFFSET);
checkColor(x, OFFSET, prev, COLOR1, COLOR2);
int count = 1;
for (int y = OFFSET + 1; y <= HEIGHT - OFFSET; y++) {
int curr = img.getRGB(x, y);
if (curr != prev) {
checkColor(x, y, curr, COLOR1, COLOR2);
checkCount(x, y, count);
prev = curr;
count = 1;
} else {
count++;
}
if (y < HEIGHT - OFFSET) {
checkColor(x - 1, y, img.getRGB(x - 1, y), BACKGROUND);
checkColor(x + 1, y, img.getRGB(x + 1, y), BACKGROUND);
}
}
checkCount(x, HEIGHT - OFFSET, count);
}
private static void checkCorners(final BufferedImage img) {
int[][] corners = {
{OFFSET - 1, OFFSET - 1},
{OFFSET, OFFSET - 1},
{OFFSET - 1, OFFSET + 1},
{OFFSET - 1, HEIGHT - OFFSET},
{OFFSET - 1, HEIGHT - OFFSET + 1},
{OFFSET, HEIGHT - OFFSET + 1},
{WIDTH - OFFSET, OFFSET - 1},
{WIDTH - OFFSET + 1, OFFSET - 1},
{WIDTH - OFFSET + 1, OFFSET},
{WIDTH - OFFSET + 1, HEIGHT - OFFSET},
{WIDTH - OFFSET + 1, HEIGHT - OFFSET + 1},
{WIDTH - OFFSET, HEIGHT - OFFSET + 1},
};
for (int[] corner : corners) {
int color = img.getRGB(corner[0], corner[1]);
checkColor(corner[0], corner[1], color, BACKGROUND);
}
}
private static void checkColor(final int x, final int y,
final int color,
final Color... validColors) {
checkColor(x, y, color, Arrays.stream(validColors)
.mapToInt(Color::getRGB)
.toArray());
}
private static void checkColor(final int x, final int y,
final int color,
final int... validColors) {
for (int valid : validColors) {
if (color == valid) {
return;
}
}
throw new RuntimeException("Unexpected color at " + x + ", " + y
+ ": " + Integer.toHexString(color) + "; expected: "
+ Arrays.stream(validColors)
.mapToObj(Integer::toHexString)
.collect(Collectors.joining(", ")));
}
private static void checkCount(final int x, final int y, final int count) {
if (count > MAX_DASH_LENGTH) {
throw new RuntimeException("Dash is longer than " + MAX_DASH_LENGTH
+ " at " + x + ", " + y);
}
}
private static void save(final BufferedImage img,
final String fileName) throws IOException {
ImageIO.write(img, "png", new File(fileName));
}
}

View file

@ -0,0 +1,102 @@
/*
* Copyright (c) 2003, 2019, 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.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.VolatileImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
/**
* @test
* @bug 4917097 8019816 8198411
* @key headful
* @summary 1.4.1 REGRESSION: BasicStroke Dashes don't show when scale * line width = 1.0
* @run main/othervm -Dsun.java2d.uiScale=1 DashScaleMinWidth
*/
public final class DashScaleMinWidth {
public static void main(final String[] args) {
BufferedImage img = new BufferedImage(200, 40, TYPE_INT_ARGB);
draw(img);
validate(img);
GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
if (gc.getColorModel() instanceof IndexColorModel) {
System.err.println("Skipping VolatileImage because of IndexColorModel");
return;
}
VolatileImage vi = gc.createCompatibleVolatileImage(200, 40);
BufferedImage snapshot;
int attempt = 0;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
draw(vi);
snapshot = vi.getSnapshot();
if (!vi.contentsLost()) {
break;
}
}
validate(snapshot);
}
private static void draw(final Image img) {
float[] dashes = {200.0f, 200.0f};
BasicStroke bs = new BasicStroke(20.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
1.0f,
dashes,
0.0f);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 200, 40);
Line2D line = new Line2D.Double(400, 400, 3600, 400);
g.setColor(Color.BLACK);
g.scale(0.05, 0.05);
g.setStroke(bs);
g.draw(line);
g.dispose();
}
private static void validate(final BufferedImage img) {
int white = Color.white.getRGB();
int point = img.getRGB(35, 20); // point in the gap
if (point != white) {
throw new RuntimeException("Line should be dashed");
}
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2015, 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.
*
* @test
* @bug 8075942 8080932
* @summary test there is no exception rendering a dashed stroke
* @run main DashStrokeTest
*/
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
public class DashStrokeTest {
public static void main(String[] args) {
GeneralPath shape = new GeneralPath();
int[] pointTypes = {0, 0, 1, 1, 0, 1, 1, 0};
double[] xpoints = {428, 420, 400, 400, 400, 400, 420, 733};
double[] ypoints = {180, 180, 180, 160, 30, 10, 10, 10};
shape.moveTo(xpoints[0], ypoints[0]);
for (int i = 1; i < pointTypes.length; i++) {
if (pointTypes[i] == 1 && i < pointTypes.length - 1) {
shape.quadTo(xpoints[i], ypoints[i],
xpoints[i + 1], ypoints[i + 1]);
} else {
shape.lineTo(xpoints[i], ypoints[i]);
}
}
BufferedImage image = new
BufferedImage(1000, 1000, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
Color color = new Color(124, 0, 124, 255);
g2.setColor(color);
Stroke stroke = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL,
10.0f, new float[] {9, 6}, 0.0f);
g2.setStroke(stroke);
g2.draw(shape);
}
}

View file

@ -0,0 +1,100 @@
/*
* Copyright (c) 2003, 2019, 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.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.VolatileImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
/**
* @test
* @bug 4779211 8019816 8198411
* @key headful
* @summary REGRESSION: 1.4 Dashed lines disappear if BasicStroke width=0.0
* @run main/othervm -Dsun.java2d.uiScale=1 DashZeroWidth
*/
public final class DashZeroWidth {
public static void main(final String[] args) {
BufferedImage img = new BufferedImage(200, 40, TYPE_INT_ARGB);
draw(img);
validate(img);
GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
if (gc.getColorModel() instanceof IndexColorModel) {
System.err.println("Skipping VolatileImage because of IndexColorModel");
return;
}
VolatileImage vi = gc.createCompatibleVolatileImage(200, 40);
BufferedImage snapshot;
int attempt = 0;
while (true) {
if (++attempt > 10) {
throw new RuntimeException("Too many attempts: " + attempt);
}
vi.validate(gc);
draw(vi);
snapshot = vi.getSnapshot();
if (!vi.contentsLost()) {
break;
}
}
validate(snapshot);
}
private static void draw(final Image img) {
float[] dashes = {10.0f, 10.0f};
BasicStroke bs = new BasicStroke(0.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL, 10.0f, dashes,
0.0f);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 200, 40);
Line2D line = new Line2D.Double(20, 20, 180, 20);
g.setColor(Color.BLACK);
g.setStroke(bs);
g.draw(line);
g.dispose();
}
private static void validate(final BufferedImage img) {
int black = Color.black.getRGB();
int white = Color.white.getRGB();
int pointB = img.getRGB(25, 20); // point on the dash
int pointW = img.getRGB(35, 20); // point in the gap
if (pointB != black || pointW != white) {
throw new RuntimeException("Line should be visible and dashed");
}
}
}

View file

@ -0,0 +1,44 @@
/*
* Copyright (c) 2021, 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.
*/
/**
* @test
* @bug 6211257
* @summary Verifies NPE is thrown for BasicStroke.createStrokedShape(null).
*/
import java.awt.BasicStroke;
import java.awt.Shape;
public class TestNullShape {
public static void main(String[] args) {
BasicStroke bs = new BasicStroke();
try {
Shape s = bs.createStrokedShape(null);
System.out.println("result: false");
throw new RuntimeException("NPE is expected");
} catch (NullPointerException ne) {
System.out.println("result (npe): true");
}
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6242148
@summary API method java.awt.BorderLayout.getConstraints(null) should return null
*/
import java.awt.BorderLayout;
public class NullConstraintsReturns {
public static void main(String[] args) {
BorderLayout bl = new BorderLayout();
Object constraints = bl.getConstraints(null);
if (constraints != null) {
throw new RuntimeException("Test failed. Constraints is not null: " + constraints);
}
System.out.println("Test Passed.");
}
}

View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 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.
*/
/*
* @test
* @bug 6191390
* @summary Verify that ActionEvent is received with correct modifiers set.
* @run main/manual ActionEventTest
*/
import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Button;
import java.awt.TextArea;
import java.awt.Robot;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class ActionEventTest extends Frame {
Button button;
Robot robot;
TextArea instructions;
public static boolean isProgInterruption = false;
static Thread mainThread = null;
static int sleepTime = 300000;
public ActionEventTest() {
try {
robot = new Robot();
} catch(AWTException e) {
throw new RuntimeException(e.getMessage());
}
button = new Button("ClickMe");
button.setEnabled(true);
instructions = new TextArea(10, 50);
instructions.setText(
" This is a manual test\n" +
" Keep the Alt, Shift & Ctrl Keys pressed &\n" +
" Click 'ClickMe' button with left mouse button\n" +
" Test exits automatically after mouse click.");
add(button);
add(instructions);
setSize(400,400);
setLayout(new FlowLayout());
pack();
setVisible(true);
robot.waitForIdle();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int md = ae.getModifiers();
int expectedMask = ActionEvent.ALT_MASK | ActionEvent.CTRL_MASK
| ActionEvent.SHIFT_MASK;
isProgInterruption = true;
mainThread.interrupt();
if ((md & expectedMask) != expectedMask) {
throw new RuntimeException("Action Event modifiers"
+ " are not set correctly.");
}
}
});
}
public static void main(String args[]) throws Exception {
mainThread = Thread.currentThread();
ActionEventTest test = new ActionEventTest();
try {
mainThread.sleep(sleepTime);
} catch (InterruptedException e) {
if (!isProgInterruption) {
throw e;
}
}
test.dispose();
if (!isProgInterruption) {
throw new RuntimeException("Timed out after " + sleepTime / 1000
+ " seconds");
}
}
}

View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 2001, 2024, 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.
*/
/*
* @test
* @bug 4530087
* @summary Test if double-clicking causes ActionEvent on underlying button
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual BadActionEventTest
*/
import java.awt.Button;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BadActionEventTest implements ActionListener {
private static Button showBtn;
private static Button listBtn;
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
1) Click on 'Show File Dialog' to bring up the FileDialog window.
(If necessary, change to a directory with files (not just directories) in it.)
2) Move the FileDialog so that one of the file names (again, a file, NOT a directory) in the list is
directly over the 'ActionListener' button.
3) Double-click on the file name over the button. The FileDialog will disappear.
4) If the 'ActionListener' button receives an ActionEvent, the test fails and a
message to that effect will be printed.
Otherwise, the test passes.
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(BadActionEventTest::createUI)
.logArea(2)
.build()
.awaitAndCheck();
}
private static Frame createUI() {
Frame frame = new Frame("BadActionEventTest");
frame.setLayout(new GridLayout(1, 2));
frame.setSize(400, 200);
showBtn = new Button("Show File Dialog");
listBtn = new Button("ActionListener");
showBtn.setSize(200, 200);
listBtn.setSize(200, 200);
showBtn.addActionListener(new BadActionEventTest());
listBtn.addActionListener(new BadActionEventTest());
frame.add(showBtn);
frame.add(listBtn);
return frame;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showBtn) {
FileDialog fd = new FileDialog(new Frame());
fd.setVisible(true);
} else if (e.getSource() == listBtn) {
listBtn.setBackground(Color.red);
listBtn.setLabel("TEST FAILS!");
PassFailJFrame.log("*TEST FAILS!* ActionListener got ActionEvent! *TEST FAILS!*");
}
}
}

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 1999, 2023, 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.
*/
/*
@test
@bug 4245382
@summary Tests that Button.setLabel(null) does not cause NPE in Java code or VM crash
@key headful
*/
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.Frame;
public class ButtonNullLabelTest {
public static void main(String args[]) throws Exception {
EventQueue.invokeAndWait(() -> runTest());
}
static void runTest() {
// Native code test
Frame frame = new Frame("Test null in native");
Button button = new Button();
try {
button.setLabel(null);
System.out.println("Set to null - test native");
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println("Test null in native **successful**");
} catch (NullPointerException npe) {
System.out.println("Test failed - test native");
throw new RuntimeException("Test failed - test native");
} finally {
frame.dispose();
}
// Peer code test
frame = new Frame("Test null in peer before show");
button = new Button();
try {
System.out.println("Set to null - test native before show");
frame.add(button);
frame.pack();
button.setLabel(null);
frame.setVisible(true);
System.out.println("Set null in peer before show **successful**");
} catch (NullPointerException npe) {
System.out.println("Test failed - test peer before show");
throw new RuntimeException("Test failed - test peer before show");
} finally {
frame.dispose();
}
// Peer code test
frame = new Frame("Test null in peer after show");
button = new Button();
try {
System.out.println("Set to null - test peer after show");
frame.add(button);
frame.pack();
frame.setVisible(true);
button.setLabel(null);
System.out.println("Test null in peer after show **successful**");
} catch (NullPointerException npe) {
System.out.println("Test failed - peer after show");
throw new RuntimeException("Test failed - peer after show");
} finally {
frame.dispose();
}
}
}

View file

@ -0,0 +1,117 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 5044469
@summary REG: Disabled component gains focus and receives keyevents on win32
@key headful
*/
import java.awt.AWTException;
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
public class DisabledButtonPress implements ActionListener, FocusListener {
public static void main(String[] args) throws Exception {
try {
DisabledButtonPress test = new DisabledButtonPress();
EventQueue.invokeAndWait(() -> test.createUI());
runTest();
} finally {
if (f != null) {
f.dispose();
}
}
if (!testPassed) {
throw new RuntimeException("Test Failed.");
}
}
final static Object FOCUS_LOCK = new Object();
final static Object ACTION_LOCK = new Object();
static volatile Frame f;
static volatile Button b2;
static volatile boolean testPassed = true;
public void createUI() {
f = new Frame("DisabledButtonPress");
b2 = new Button("Click Me");
b2.addActionListener(this);
b2.addFocusListener(this);
f.add(b2);
f.pack();
f.setVisible(true);
}
static void runTest() throws Exception {
Robot robot = new Robot();
robot.delay(500);
System.out.println("Requesting focus");
System.out.println(" b2.requestFocusInWindow()="+ b2.requestFocusInWindow());
b2.setEnabled(false);
synchronized(FOCUS_LOCK) {
FOCUS_LOCK.wait(3000);
}
if (!b2.isFocusOwner()) {
throw new RuntimeException("Test failed. Button doesn't have a focus.");
}
System.out.println("Button disabling");
robot.delay(1000);
robot.keyPress(KeyEvent.VK_SPACE);
robot.delay(10);
robot.keyRelease(KeyEvent.VK_SPACE);
synchronized(ACTION_LOCK) {
ACTION_LOCK.wait(2000); //give time to handle
// ACTION_PERFORMED event from the Button if it was generated
}
}
public void focusGained(FocusEvent ae) {
System.out.println("Button got focus");
synchronized(FOCUS_LOCK) {
FOCUS_LOCK.notify();
}
}
public void focusLost(FocusEvent ae) {}
public void actionPerformed(ActionEvent evt) {
System.out.println("Button: " + evt.getActionCommand() + " Clicked. Event is " +evt);
if (evt.getSource() == b2) {
testPassed = false;
synchronized(ACTION_LOCK) {
ACTION_LOCK.notify();
}
}
}
}

View file

@ -0,0 +1,112 @@
/*
* Copyright (c) 2002, 2023, 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.
*/
/*
@test
@bug 4531849
@summary Test that double action event no longer sent
@key headful
*/
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class DoubleActionEventTest implements ActionListener, WindowListener {
static class Lock {
boolean go = false;
public synchronized boolean getGo() {return go;}
public synchronized void setGo(boolean newGo) {go = newGo;}
}
static volatile Frame f;
static volatile int numActionEvents = 0;
static volatile Lock lock = new Lock();
public static void main(String[] args) throws Exception {
try {
DoubleActionEventTest test = new DoubleActionEventTest();
EventQueue.invokeAndWait(() -> test.createUI());
runTest();
} finally {
if (f != null) {
f.dispose();
}
}
}
public void createUI() {
f = new Frame("DoubleActionEventTest");
f.setLayout (new BorderLayout());
f.addWindowListener(this);
Button b = new Button("Action Listening Button");
b.addActionListener(this);
f.add(b);
f.setBounds(100, 100, 200, 200);
f.setVisible(true);
}
static void runTest() throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(250);
robot.setAutoWaitForIdle(true);
robot.mouseMove(200, 200);
while (!lock.getGo()) {}
robot.mousePress(InputEvent.BUTTON3_DOWN_MASK);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
if (numActionEvents != 1) {
System.out.println("Wrong number of ActionEvents. Test FAILS.");
throw new RuntimeException("TEST FAILS");
}
}
public void actionPerformed(ActionEvent e) {
numActionEvents++;
System.out.println("Number of ActionEvents: " + numActionEvents);
}
public void windowActivated(WindowEvent e) {
lock.setGo(true);
}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2001, 2023, 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.
*/
/*
* @test
* @bug 4429261
* @summary Checks AWTKeyStroke is cached
* @run main CacheTest
*/
import java.awt.AWTKeyStroke;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
public class CacheTest {
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> {
if (AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_X,
InputEvent.ALT_DOWN_MASK) !=
AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_X,
InputEvent.ALT_DOWN_MASK)) {
throw new RuntimeException("KeyStroke is not cached");
}
});
}
}// class CacheTest

View file

@ -0,0 +1,422 @@
/*
* Copyright (c) 1999, 2024, 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.
*/
/*
* @test
* @bug 6616089
* @summary Displays a dithered Canvas on all available GraphicsConfigurations
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MultiDitherTest
*/
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Label;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;
import java.util.List;
public class MultiDitherTest extends Panel implements Runnable {
final static int NOOP = 0;
final static int RED = 1;
final static int GREEN = 2;
final static int BLUE = 3;
final static int ALPHA = 4;
final static int SATURATION = 5;
final static String calcString = "Calculating...";
static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER, 10, 5);
Thread runner;
DitherControls XControls;
DitherControls YControls;
DitherCanvas canvas;
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
Depending on the GraphicsConfiguration, the dithering may be in
color or in grayscale and/or display at a lower bitdepth.
The number of GraphicsConfigurations will be printed in the
TextArea below as the test is starting up.
Ensure that there are as many Frames created as there are
available GraphicsConfigurations.
Examine each Frame to ensure it displays the dither pattern.
If all Canvases display correctly, the test PASSES.
Otherwise, the test FAILS.
The GC button runs the garbage collector.
This button can be ignored for now.
""";
PassFailJFrame passFailJFrame = PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(35)
.build();
EventQueue.invokeAndWait(() -> {
for (Frame frame : MultiDitherTest.initialize()) {
PassFailJFrame.addTestWindow(frame);
frame.setVisible(true);
}
});
passFailJFrame.awaitAndCheck();
}
public MultiDitherTest(GraphicsConfiguration gc) {
String xSpec, ySpec;
int[] xValues = new int[2];
int[] yValues = new int[2];
xSpec = "red";
ySpec = "blue";
int xMethod = colorMethod(xSpec, xValues);
int yMethod = colorMethod(ySpec, yValues);
setLayout(new BorderLayout());
XControls = new DitherControls(this, xValues[0], xValues[1],
xMethod, false);
YControls = new DitherControls(this, yValues[0], yValues[1],
yMethod, true);
YControls.addRenderButton();
YControls.addGCButton();
add("North", XControls);
add("South", YControls);
add("Center", canvas = new DitherCanvas(gc));
}
private static List<Frame> initialize() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
Frame[] frames = new Frame[0];
System.out.println(gds.length + " screens detected");
for (int j = 0; j < gds.length; j++) {
GraphicsDevice gd = gds[j];
GraphicsConfiguration[] gcs = gd.getConfigurations();
frames = new Frame[gcs.length];
System.out.println(gcs.length + " GraphicsConfigurations available on screen " + j);
for (int i = 0; i < gcs.length; i++) {
Frame f = new Frame("MultiDitherTest " + (i + 1), gcs[i]);
f.setLayout(new BorderLayout());
f.setLocation(gcs[i].getBounds().x + 100 + (i * 10),
gcs[i].getBounds().y + 100 + (i * 10));
MultiDitherTest ditherTest = new MultiDitherTest(gcs[i]);
f.add("Center", ditherTest);
f.pack();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
ev.getWindow().dispose();
}
});
f.setVisible(true);
ditherTest.start();
frames[i] = f;
}
}
return List.of(frames);
}
int colorMethod(String s, int[] values) {
int method = NOOP;
if (s == null) {
s = "";
}
String lower = s.toLowerCase();
if (lower.startsWith("red")) {
method = RED;
lower = lower.substring(3);
} else if (lower.startsWith("green")) {
method = GREEN;
lower = lower.substring(5);
} else if (lower.startsWith("blue")) {
method = BLUE;
lower = lower.substring(4);
} else if (lower.startsWith("alpha")) {
method = ALPHA;
lower = lower.substring(4);
} else if (lower.startsWith("saturation")) {
method = SATURATION;
lower = lower.substring(10);
}
if (method == NOOP) {
values[0] = 0;
values[1] = 0;
return method;
}
int begval = 0;
int endval = 255;
try {
int dash = lower.indexOf('-');
if (dash < 0) {
begval = endval = Integer.parseInt(lower);
} else {
begval = Integer.parseInt(lower.substring(0, dash));
endval = Integer.parseInt(lower.substring(dash + 1));
}
} catch (Exception e) {
}
if (begval < 0) {
begval = 0;
}
if (endval < 0) {
endval = 0;
}
if (begval > 255) {
begval = 255;
}
if (endval > 255) {
endval = 255;
}
values[0] = begval;
values[1] = endval;
return method;
}
public void start() {
runner = new Thread(this);
runner.start();
}
public void stop() {
runner = null;
}
public void destroy() {
remove(XControls);
remove(YControls);
remove(canvas);
}
void applyMethod(int[] c, int method, int step, int total, int[] values) {
if (method == NOOP) {
return;
}
int val = ((total < 2)
? values[0]
: values[0] + ((values[1] - values[0]) * step / (total - 1)));
switch (method) {
case RED:
c[0] = val;
break;
case GREEN:
c[1] = val;
break;
case BLUE:
c[2] = val;
break;
case ALPHA:
c[3] = val;
break;
case SATURATION:
int max = Math.max(Math.max(c[0], c[1]), c[2]);
int min = max * (255 - val) / 255;
if (c[0] == 0) c[0] = min;
if (c[1] == 0) c[1] = min;
if (c[2] == 0) c[2] = min;
break;
}
}
public void run() {
canvas.setImage(null);
Image img = calculateImage();
synchronized (this) {
if (img != null && runner == Thread.currentThread()) {
canvas.setImage(img);
}
}
}
/**
* Calculates and returns the image. Halts the calculation and returns
* null if the Application is stopped during the calculation.
*/
Image calculateImage() {
Thread me = Thread.currentThread();
int width = canvas.getSize().width;
int height = canvas.getSize().height;
int[] xValues = new int[2];
int[] yValues = new int[2];
int xMethod = XControls.getParams(xValues);
int yMethod = YControls.getParams(yValues);
int[] pixels = new int[width * height];
int[] c = new int[4];
int index = 0;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
c[0] = c[1] = c[2] = 0;
c[3] = 255;
if (xMethod < yMethod) {
applyMethod(c, xMethod, i, width, xValues);
applyMethod(c, yMethod, j, height, yValues);
} else {
applyMethod(c, yMethod, j, height, yValues);
applyMethod(c, xMethod, i, width, xValues);
}
pixels[index++] = ((c[3] << 24) |
(c[0] << 16) |
(c[1] << 8) |
(c[2] << 0));
}
// Poll once per row to see if we've been told to stop.
if (runner != me) {
return null;
}
}
return createImage(new MemoryImageSource(width, height,
ColorModel.getRGBdefault(), pixels, 0, width));
}
static class DitherCanvas extends Canvas {
Image img;
GraphicsConfiguration mGC;
public DitherCanvas(GraphicsConfiguration gc) {
super(gc);
mGC = gc;
}
public GraphicsConfiguration getGraphicsConfig() {
return mGC;
}
public void paint(Graphics g) {
int w = getSize().width;
int h = getSize().height;
if (img == null) {
super.paint(g);
g.setColor(Color.black);
FontMetrics fm = g.getFontMetrics();
int x = (w - fm.stringWidth(calcString)) / 2;
int y = h / 2;
g.drawString(calcString, x, y);
} else {
g.drawImage(img, 0, 0, w, h, this);
}
}
public void update(Graphics g) {
paint(g);
}
public Dimension getMinimumSize() {
return new Dimension(20, 20);
}
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public Image getImage() {
return img;
}
public void setImage(Image img) {
this.img = img;
paint(getGraphics());
}
}
static class DitherControls extends Panel implements ActionListener {
TextField start;
TextField end;
Button button;
Choice choice;
MultiDitherTest panel;
Button gc;
public DitherControls(MultiDitherTest app, int s, int e, int type,
boolean vertical) {
panel = app;
setLayout(dcLayout);
add(new Label(vertical ? "Vertical" : "Horizontal"));
add(choice = new Choice());
choice.addItem("Noop");
choice.addItem("Red");
choice.addItem("Green");
choice.addItem("Blue");
choice.addItem("Alpha");
choice.addItem("Saturation");
choice.select(type);
add(start = new TextField(Integer.toString(s), 4));
add(end = new TextField(Integer.toString(e), 4));
}
public void addRenderButton() {
add(button = new Button("New Image"));
button.addActionListener(this);
}
public void addGCButton() {
add(gc = new Button("GC"));
gc.addActionListener(this);
}
public int getParams(int[] values) {
values[0] = Integer.parseInt(start.getText());
values[1] = Integer.parseInt(end.getText());
return choice.getSelectedIndex();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
panel.start();
} else if (e.getSource() == gc) {
System.gc();
}
}
}
}

View file

@ -0,0 +1,139 @@
/*
* Copyright (c) 1999, 2024, 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.
*/
/*
* @test
* @bug 6616089
* @summary Display an image in all available GraphicsConfigurations
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MultiGraphicsTest
*/
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.List;
public class MultiGraphicsTest extends Canvas {
final static String IMAGEFILE = "duke_404.gif";
static Image jim;
MediaTracker tracker;
int w, h;
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
This test displays several Windows containing an image,
one Window for each available GraphicsConfiguration.
Depending on the GraphicsConfiguration, images may be
displayed in color or in grayscale and/or displayed at a
lower bitdepth.
The number of GraphicsConfigurations will be printed below
as the test is starting up.
Ensure that there are as many Windows created as there are
available GraphicsConfigurations.
Examine each Window to ensure it displays Duke_404.
If all Canvases display correctly, the test PASSES.
Otherwise, the test FAILS."
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(35)
.testUI(initialize())
.build()
.awaitAndCheck();
}
public MultiGraphicsTest(GraphicsConfiguration gc) {
super(gc);
tracker = new MediaTracker(this);
tracker.addImage(jim, 0);
try {
tracker.waitForAll();
} catch (java.lang.InterruptedException e) {
System.err.println(e);
}
w = jim.getWidth(this);
h = jim.getHeight(this);
}
private static List<Frame> initialize() {
URL imgURL;
imgURL = MultiGraphicsTest.class.getResource(IMAGEFILE);
if (imgURL == null) {
System.err.println("Unable to locate " + IMAGEFILE);
return null;
}
jim = Toolkit.getDefaultToolkit().getImage(imgURL);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration[] gc = gd.getConfigurations();
Frame[] frames = new Frame[gc.length];
System.out.println(gc.length + " available GraphicsConfigurations");
for (int i = 0; i < gc.length; i++) {
Frame f = new Frame("GraphicsTest " + (i + 1));
f.setLayout(new BorderLayout());
f.setLocation(100 + (i * 10), 100 + (i * 10));
MultiGraphicsTest gcTest = new MultiGraphicsTest(gc[i]);
f.add("Center", gcTest);
f.pack();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
ev.getWindow().setVisible(false);
}
});
frames[i] = f;
}
return List.of(frames);
}
public void paint(Graphics g) {
g.drawImage(jim, 0, 0, w, h, this);
}
public void update(Graphics g) {
paint(g);
}
public Dimension getMinimumSize() {
return new Dimension(w, h);
}
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 1999, 2024, 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.
*/
/*
* @test
* @bug 4250354
* @key headful
* @summary tests that JNI global refs are cleaned up correctly
* @run main/timeout=600 NoEventsLeakTest
*/
import java.awt.Canvas;
import java.awt.EventQueue;
import java.awt.Frame;
public class NoEventsLeakTest extends Frame {
static final int nLoopCount = 1000;
private static void initialize() {
NoEventsLeakTest app = new NoEventsLeakTest();
boolean result = app.run();
if (result) {
throw new RuntimeException("Memory leak in Component");
}
System.out.println("Test Passed");
}
public boolean run() {
setSize(10, 10);
addNotify();
for (int i = 0; i < nLoopCount; i++) {
Canvas panel = new TestCanvas();
add(panel, 0);
remove(0);
panel = null;
System.gc();
}
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
System.gc();
System.out.println("Checking");
return ((TestCanvas.created - TestCanvas.finalized) > 800);
}
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(NoEventsLeakTest::initialize);
}
}
class TestCanvas extends Canvas {
static int finalized = 0;
static int created = 0;
static final int nLoopPrint = 100;
public TestCanvas() {
if (created % nLoopPrint == 0) {
System.out.println("Created " + getClass() + " " + created);
}
created++;
}
@SuppressWarnings("removal")
protected void finalize() {
try {
super.finalize();
if (finalized % nLoopPrint == 0) {
System.out.println("Finalized " + getClass() + " " + finalized);
}
finalized++;
} catch (Throwable t) {
System.out.println("Exception in " + getClass() + ": " + t);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2002, 2023, 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.
*/
/*
@test
@bug 4689398
@summary Inserting items in a Container with CardLayout does not work since Merlin
*/
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
public class CardsOrderTest {
public static void main(String[] args) throws Exception {
CardLayout layout = new CardLayout();
Container cont = new Container();
Component comp1 = new Component() {};
Component comp2 = new Component() {};
Component comp3 = new Component() {};
cont.setLayout(layout);
cont.add(comp1, "1", 0);
cont.add(comp2, "2", 0);
cont.add(comp3, "3", 0);
// Testing visibility "state" - not actually if its visible on screen
// since this test does not require a UI.
System.out.println("comp1.isVisible() = " + comp1.isVisible());
System.out.println("comp2.isVisible() = " + comp2.isVisible());
System.out.println("comp3.isVisible() = " + comp3.isVisible());
if (!comp1.isVisible() || comp2.isVisible() || comp3.isVisible()) {
throw new RuntimeException("first added component must be visible");
}
System.out.println("CardLayout.next()");
layout.next(cont);
System.out.println("comp1.isVisible() = " + comp1.isVisible());
System.out.println("comp2.isVisible() = " + comp2.isVisible());
System.out.println("comp3.isVisible() = " + comp3.isVisible());
if (!comp3.isVisible() ||comp1.isVisible() || comp2.isVisible()) {
throw new RuntimeException("the wrong component is visible after CardLayout.next() (must be comp3)");
}
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2002, 2023, 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.
*/
/*
@test
@bug 4690266
@summary REGRESSION: Wizard Page does not move to the next page
*/
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
public class ObedienceTest {
public static void main(String[] args) {
Container cont = new Container();
Component comp1 = new Component() {};
Component comp2 = new Component() {};
CardLayout layout = new CardLayout();
cont.setLayout(layout);
cont.add(comp1, "first");
cont.add(comp2, "second");
if (!comp1.isVisible()) {
throw new RuntimeException("first component must be visible");
}
comp1.setVisible(false);
comp2.setVisible(true);
layout.layoutContainer(cont);
if (!comp2.isVisible() || comp1.isVisible()) {
System.out.println("comp1.isVisible() = " + comp1.isVisible());
System.out.println("comp2.isVisible() = " + comp2.isVisible());
throw new RuntimeException("manually shown component must be visible after layoutContainer()");
}
}
}

View file

@ -0,0 +1,166 @@
/*
* Copyright (c) 2002, 2024, 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.
*/
/*
* @test
* @bug 4546123
* @summary CardLayout becomes unusable after deleting an element
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual RemoveComponentTest
*/
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class RemoveComponentTest {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
You should see a frame titled "Test Frame For
RemoveComponentTest". Try to select a few different panels from
the second menu. Make sure your last choice is the red panel.
Then click close (in first menu). After that you should be able
to select any panels except red one.
If that is the case, the test passes. Otherwise, the test failed.
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.columns(35)
.testUI(RemoveComponentTest::createUI)
.logArea(5)
.build()
.awaitAndCheck();
}
public static Frame createUI() {
TestFrame frame = new TestFrame();
frame.setSize(200, 200);
return frame;
}
}
class TestFrame extends Frame implements ActionListener {
public Panel aPanel;
public TestPanel pageRed;
public TestPanel pageGreen;
public TestPanel pageBlue;
public String currentSelection = "";
public MenuItem mi;
public CardLayout theCardLayout;
public TestFrame() {
super("Test Frame For RemoveComponentTest");
setBackground(Color.black);
setLayout(new BorderLayout(5, 5));
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
Menu pageMenu = new Menu("Pages");
mi = new MenuItem("Close");
mi.addActionListener(this);
fileMenu.add(mi);
mi = new MenuItem("Red");
mi.addActionListener(this);
pageMenu.add(mi);
mi = new MenuItem("Green");
mi.addActionListener(this);
pageMenu.add(mi);
mi = new MenuItem("Blue");
mi.addActionListener(this);
pageMenu.add(mi);
mb.add(fileMenu);
mb.add(pageMenu);
setMenuBar(mb);
aPanel = new Panel();
theCardLayout = new CardLayout();
aPanel.setLayout(theCardLayout);
pageRed = new TestPanel("PageRed", Color.red);
pageGreen = new TestPanel("PageGreen", Color.green);
pageBlue = new TestPanel("PageBlue", Color.blue);
aPanel.add("PageRed", pageRed);
aPanel.add("PageGreen", pageGreen);
aPanel.add("PageBlue", pageBlue);
add("Center", aPanel);
setSize(getPreferredSize());
}
public Insets getInsets() {
return new Insets(47, 9, 9, 9);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Red")) {
theCardLayout.show(aPanel, "PageRed");
currentSelection = "PageRed";
} else if (e.getActionCommand().equals("Green")) {
theCardLayout.show(aPanel, "PageGreen");
} else if (e.getActionCommand().equals("Blue")) {
theCardLayout.show(aPanel, "PageBlue");
} else if (e.getActionCommand().equals("Close")) {
PassFailJFrame.log("Closing");
if (currentSelection.equals("PageRed")) {
PassFailJFrame.log("Remove page red");
theCardLayout.removeLayoutComponent(pageRed);
}
}
}
}
class TestPanel extends JPanel {
private String pageName;
TestPanel(String pageName, Color color) {
setBackground(color);
add(new JLabel(pageName));
}
}

View file

@ -0,0 +1,84 @@
/*
* Copyright (c) 2006, 2024, 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.Button;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
* @test
* @bug 6401956
* @summary The right mark of the CheckboxMenu item is broken
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual AppearanceIfLargeFont
*/
public class AppearanceIfLargeFont extends Frame {
private static final String INSTRUCTIONS = """
1) Make sure that font-size is large.
You could change this using 'Appearance' dialog.
2) Press button 'Press'
You will see a menu item with check-mark.
3) If check-mark is correctly painted then the test passed.
Otherwise, test failed.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("AppearanceIfLargeFont")
.instructions(INSTRUCTIONS)
.columns(35)
.testUI(AppearanceIfLargeFont::new)
.build()
.awaitAndCheck();
}
public AppearanceIfLargeFont() {
createComponents();
setSize(200, 200);
validate();
}
void createComponents() {
final Button press = new Button("Press");
final PopupMenu popup = new PopupMenu();
press.add(popup);
add(press);
CheckboxMenuItem item = new CheckboxMenuItem("CheckboxMenuItem", true);
popup.add(item);
press.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
popup.show(press, press.getSize().width, 0);
}
}
);
}
}

View file

@ -0,0 +1,71 @@
/*
* Copyright (c) 2001, 2024, 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.Checkbox;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Panel;
/*
* @test
* @bug 4410522
* @requires (os.family == "windows")
* @summary The box size of the Checkbox control should be the same as
* in Windows native applications.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual CheckboxBoxSizeTest
*/
public class CheckboxBoxSizeTest {
private static final String INSTRUCTIONS = """
This test must be run at UI Scale of 100% AND
150% or greater.
Compare the size of box to any of native apps on Windows
(Eg. Font Dialog Settings on Word).
They should be the same.
If the sizes are same Press PASS, else Press FAIL.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("CheckboxBoxSizeTest Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(35)
.testUI(CheckboxBoxSizeTest::createTestUI)
.build()
.awaitAndCheck();
}
private static Frame createTestUI() {
Frame frame = new Frame("CheckboxBoxSizeTest");
Panel panel = new Panel(new FlowLayout());
Checkbox checkbox = new Checkbox("Compare the box size");
panel.add(checkbox);
frame.add(panel);
frame.pack();
return frame;
}
}

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2024, 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.Checkbox;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/*
* @test
* @key headful
* @bug 8233068
* @summary Tests checkbox checker on scaling
* @requires (os.family == "linux")
* @run main CheckboxCheckerScalingTest
*/
public class CheckboxCheckerScalingTest {
private static Frame frame;
private static Checkbox checkbox;
private static volatile Point point;
private static boolean checkmarkFound = false;
private static final int TOLERANCE = 5;
private static final int COLOR_CHECK_THRESHOLD = 8;
private static int colorCounter = 0;
public static void main(String[] args) throws Exception {
System.setProperty("sun.java2d.uiScale", "2");
Robot robot = new Robot();
try {
EventQueue.invokeAndWait(() -> {
frame = new Frame("CheckBox checker scaling test");
checkbox = new Checkbox("one");
checkbox.setState(true);
frame.add(checkbox);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
});
robot.waitForIdle();
robot.delay(100);
EventQueue.invokeAndWait(() -> point = checkbox.getLocationOnScreen());
Rectangle rect = new Rectangle(point.x + 5, point.y + 7, 8, 8);
BufferedImage imageAfterChecked = robot.createScreenCapture(rect);
check:
{
for (int i = 0; i < imageAfterChecked.getHeight(); i++) {
for (int j = 0; j < imageAfterChecked.getWidth(); j++) {
Color pixelColor = new Color(imageAfterChecked.getRGB(i, j));
if (compareColor(pixelColor)) {
if (++colorCounter >= COLOR_CHECK_THRESHOLD) {
checkmarkFound = true;
break check;
}
}
}
}
}
if (!checkmarkFound) {
try {
ImageIO.write(imageAfterChecked, "png",
new File("imageAfterChecked.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
throw new RuntimeException("Checkmark not scaled");
}
System.out.println("Test Passed");
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
private static boolean compareColor(Color c) {
return Math.abs(Color.black.getRed() - c.getRed()) < TOLERANCE &&
Math.abs(Color.black.getGreen() - c.getGreen()) < TOLERANCE &&
Math.abs(Color.black.getBlue() - c.getBlue()) < TOLERANCE;
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright (c) 2000, 2023, 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.
*/
/*
@test
@bug 4378378
@summary Tests that checkbox.setLabel(null) doesn't crash the VM.
@key headful
*/
import java.awt.Checkbox;
import java.awt.EventQueue;
import java.awt.Frame;
public class CheckboxCrashTest {
static Frame f;
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> runTest());
Thread.sleep(1000);
} finally {
f.dispose();
}
}
static void runTest() {
f = new Frame("CheckboxCrashTest");
Checkbox cb = new Checkbox();
f.add(cb);
f.pack();
cb.setLabel(null);
f.setVisible(true);
}
}

View file

@ -0,0 +1,168 @@
/*
* Copyright (c) 1999, 2024, 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.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
* @test
* @bug 4090493
* @summary Test for Checkbox indicator size
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual CheckboxIndicatorSizeTest
*/
public class CheckboxIndicatorSizeTest implements ActionListener {
private static final String INSTRUCTIONS = """
Indicator size of Checkbox depends
on the platform font used to render the label.
In the frame you can see a group of checkboxes
and radio buttons.
Verify that all checkboxes and radio buttons have
indicators of the same size and proportional to
the uiScale and/or font-size.
Use menu to change the font size and the indicators
should scale proportionally.
If there is a bug, the checkbox/radiobutton with
dingbats label will have a smaller indicator.
Press PASS if the above conditions are true else Press FAIL.
""";
private static Frame frame;
private static Panel testPanel;
public static void main(String[] args) throws Exception {
CheckboxIndicatorSizeTest obj = new CheckboxIndicatorSizeTest();
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 3)
.columns(60)
.testUI(obj::createAndShowUI)
.build()
.awaitAndCheck();
}
private Frame createAndShowUI() {
frame = new Frame("CheckboxIndicatorSizeTest");
testPanel = new Panel(new GridLayout(0, 1));
testPanel.setFont(new Font("Dialog", Font.PLAIN, 12));
frame.add(testPanel);
MenuBar menuBar = new MenuBar();
Menu fontSizeMenu = new Menu("FontSize");
MenuItem size10 = new MenuItem("10");
size10.addActionListener(this);
fontSizeMenu.add(size10);
MenuItem size12 = new MenuItem("12");
size12.addActionListener(this);
fontSizeMenu.add(size12);
MenuItem size14 = new MenuItem("14");
size14.addActionListener(this);
fontSizeMenu.add(size14);
MenuItem size18 = new MenuItem("18");
size18.addActionListener(this);
fontSizeMenu.add(size18);
MenuItem size24 = new MenuItem("24");
size24.addActionListener(this);
fontSizeMenu.add(size24);
MenuItem size36 = new MenuItem("36");
size36.addActionListener(this);
fontSizeMenu.add(size36);
menuBar.add(fontSizeMenu);
frame.setMenuBar(menuBar);
Checkbox cbEnglishOnly
= new Checkbox("Toggle", true);
Checkbox cbDingbatsOnly
= new Checkbox("\u274a\u274b\u274c\u274d", true);
Checkbox cbEnglishDingbats
= new Checkbox("Toggle \u274a\u274d", true);
Checkbox cbDingbatsEnglish
= new Checkbox("\u274a\u274d toggle", true);
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox rbEnglishOnly
= new Checkbox("Radio", true, radioGroup);
Checkbox rbDingbatsOnly
= new Checkbox("\u274a\u274b\u274c\u274d", false, radioGroup);
Checkbox rbEnglishDingbats
= new Checkbox("Radio \u274a\u274d", false, radioGroup);
Checkbox rbDingbatsEnglish
= new Checkbox("\u274a\u274d radio", false, radioGroup);
Label cbLabel = new Label("Checkboxes");
cbLabel.setBackground(Color.YELLOW);
testPanel.add(cbLabel);
testPanel.add(cbEnglishOnly);
testPanel.add(cbDingbatsOnly);
testPanel.add(cbEnglishDingbats);
testPanel.add(cbDingbatsEnglish);
Label rbLabel = new Label("Radio buttons");
rbLabel.setBackground(Color.YELLOW);
testPanel.add(rbLabel);
testPanel.add(rbEnglishOnly);
testPanel.add(rbDingbatsOnly);
testPanel.add(rbEnglishDingbats);
testPanel.add(rbDingbatsEnglish);
frame.pack();
return frame;
}
@Override
public void actionPerformed(ActionEvent e) {
String sizeStr = e.getActionCommand();
int size = Integer.parseInt(sizeStr);
Font oldFont = testPanel.getFont();
Font newFont = new Font(oldFont.getName(), oldFont.getStyle(), size);
testPanel.setFont(newFont);
frame.pack();
frame.setVisible(true);
}
}

View file

@ -0,0 +1,120 @@
/*
* Copyright (c) 2003, 2024, 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.BorderLayout;
import java.awt.Button;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.PopupMenu;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/*
* @test
* @bug 4814163 5005195
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @summary Tests events fired by CheckboxMenuItem
* @run main/manual CheckboxMenuItemEventsTest
*/
public class CheckboxMenuItemEventsTest extends Frame implements ActionListener {
Button trigger;
PopupMenu popup;
TextArea ta;
class Listener implements ItemListener, ActionListener {
public void itemStateChanged(ItemEvent e) {
ta.append("CORRECT: ItemEvent fired\n");
}
public void actionPerformed(ActionEvent e) {
ta.append("ERROR: ActionEvent fired\n");
}
}
Listener listener = new Listener();
private static final String INSTRUCTIONS = """
Press button to invoke popup menu
When you press checkbox menu item
Item state should toggle (on/off).
ItemEvent should be displayed in log below.
And ActionEvent should not be displayed
Press PASS if ItemEvents are generated
and ActionEvents are not, FAIL Otherwise.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("CheckboxMenuItemEventsTest")
.instructions(INSTRUCTIONS)
.columns(35)
.testUI(CheckboxMenuItemEventsTest::new)
.build()
.awaitAndCheck();
}
public CheckboxMenuItemEventsTest() {
CheckboxMenuItem i1 = new CheckboxMenuItem("CheckBoxMenuItem 1");
CheckboxMenuItem i2 = new CheckboxMenuItem("CheckBoxMenuItem 2");
Panel p1 = new Panel();
Panel p2 = new Panel();
setLayout(new BorderLayout());
ta = new TextArea();
p2.add(ta);
trigger = new Button("menu");
trigger.addActionListener(this);
popup = new PopupMenu();
i1.addItemListener(listener);
i1.addActionListener(listener);
popup.add(i1);
i2.addItemListener(listener);
i2.addActionListener(listener);
popup.add(i2);
trigger.add(popup);
p1.add(trigger);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.SOUTH);
pack();
validate();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == (Object) trigger) {
popup.show(trigger, trigger.getSize().width, 0);
}
}
}

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 2012, 2024, 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.BorderLayout;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
/*
* @test
* @bug 4383735
* @summary Checkbox buttons are too small with java 1.3 and 1.4
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual CheckboxNullLabelTest
*/
public class CheckboxNullLabelTest {
private static final String INSTRUCTIONS = """
Please look at the frame titled 'CheckboxNullLabelTest'.
Check if all the check boxes in each group
(of 3 check boxes) have the same size.
If the size of labeled check box is NOT the same as
the size of non-labeled Press FAIL otherwise Press PASS.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 1)
.columns(35)
.testUI(CheckboxNullLabelTest::createAndShowUI)
.build()
.awaitAndCheck();
}
private static Frame createAndShowUI() {
Frame f = new Frame("CheckboxNullLabelTest");
f.setLayout(new BorderLayout());
f.add(new CheckboxTest(Color.gray, new Font(null, 0, 12)), "North");
f.add(new CheckboxTest(Color.green, new Font(null, 0, 18)), "South");
f.add(new CheckboxTest(Color.red, new Font(null, 0, 24)), "East");
f.add(new CheckboxTest(Color.white, new Font(null, 0, 30)), "West");
f.add(new CheckboxTest(f.getBackground(), new Font(null, 0, 36)), "Center");
f.setSize(600, 450);
return f;
}
private static class CheckboxTest extends Panel {
Checkbox cb1, cb2, cb3;
CheckboxTest(Color background, Font font) {
setBackground(background);
CheckboxGroup cbg = new CheckboxGroup();
cb1 = new Checkbox(null, cbg, true);
cb1.setFont(font);
cb2 = new Checkbox("", cbg, true);
cb2.setFont(font);
cb3 = new Checkbox("Label", cbg, false);
cb3.setFont(font);
add(cb1);
add(cb2);
add(cb3);
}
}
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2000, 2024, 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.Checkbox;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
/*
* @test
* @bug 4304049
* @summary tests that Checkbox fits into its preferred size entirely
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual CheckboxPreferredSizeTest
*/
public class CheckboxPreferredSizeTest {
private static final String INSTRUCTIONS = """
As the test starts, ensure that the
whole checkbox with all its text is visible.
If the checkbox is entirely visible, press PASS else,
press FAIL.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 1)
.columns(35)
.testUI(CheckboxPreferredSizeTest::createAndShowUI)
.build()
.awaitAndCheck();
}
private static Frame createAndShowUI() {
Frame frame = new Frame("Checkbox Preferred Size Test");
frame.setBackground(Color.BLUE);
Checkbox box = new Checkbox("Checkbox_With_Some_Size");
box.setFont(new Font("Helvetica", Font.PLAIN, 36));
box.setBackground(Color.RED);
frame.add(box);
frame.pack();
return frame;
}
}

View file

@ -0,0 +1,72 @@
/*
* Copyright (c) 2005, 2024, 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.
*/
/*
* @test
* @bug 6225679
* @summary Tests that checkbox changes into radiobutton dynamically
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual DynamicChangeTest
*/
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Frame;
import java.awt.GridLayout;
public class DynamicChangeTest {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
This test is primarily for Windows platform, but should pass
on other platforms as well. Ensure that 'This is checkbox' is
checkbox, and 'This is radiobutton' is radiobutton.
If it is so, press pass else fail.
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(35)
.testUI(DynamicChangeTest::createUI)
.build()
.awaitAndCheck();
}
public static Frame createUI() {
Frame f = new Frame("Dynamic Change Checkbox Test");
f.setSize(200, 200);
f.setLayout(new GridLayout(2, 1));
Checkbox ch1 = new Checkbox("This is checkbox",
new CheckboxGroup(), true);
f.add(ch1);
Checkbox ch2 = new Checkbox("This is radiobutton", null, true);
f.add(ch2);
ch1.setCheckboxGroup(null);
ch2.setCheckboxGroup(new CheckboxGroup());
return f;
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2002, 2023, 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.
*/
/*
@test
@bug 4136496
@key headful
@summary Checkbox.setCheckboxGroup(CheckboxGroup) works wrong on some Checkbox states
*/
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
public class MultiCheckedCheckboxGroupTest {
public static void main(String[] args) throws Exception {
CheckboxGroup gr = new CheckboxGroup();
Checkbox chb1 = new Checkbox("Box 1", true, gr);
Checkbox chb2 = new Checkbox("Box 2", true, null);
chb2.setCheckboxGroup(gr);
System.out.println("chb1="+chb1);
System.out.println("chb2="+chb2);
System.out.println("gr.getSelectedCheckbox="+gr.getSelectedCheckbox());
if(chb1.getState()
&& !chb2.getState()
&& chb1.getCheckboxGroup() == gr
&& chb2.getCheckboxGroup() == gr
&& gr.getSelectedCheckbox() == chb1) {
System.out.println("PASSED");
} else {
System.out.println("FAILED");
throw new RuntimeException("Test FAILED");
}
}
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2002, 2023, 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.
*/
/*
@test
@bug 4114268
@key headful
@summary Checkbox.setCheckboxGroup(null) alters selection for CB's previous CBGroup
*/
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
public class NullCheckboxGroupTest {
public static void main(String[] args) {
CheckboxGroup cbg = new CheckboxGroup();
Checkbox chbox1 = new Checkbox("First", cbg, true);
Checkbox chbox2 = new Checkbox("Second", cbg, false);
chbox2.setCheckboxGroup(null);
System.out.println("chbox1="+chbox1);
System.out.println("chbox2="+chbox2);
System.out.println("cbg="+cbg);
if (cbg.getSelectedCheckbox() != chbox1) {
System.out.println("FAILED");
throw new RuntimeException("Test FAILED");
} else {
System.out.println("PASSED");
}
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2002, 2023, 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.
*/
/*
@test
@bug 4726853
@key headful
@summary Checkbox is changing it's state after removing from CheckboxGroup
*/
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
public class SetCheckboxGroupNull {
public static void main(String[] args) {
boolean passed = true;
// 1 step
{
CheckboxGroup g = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Label", true, g);
System.out.println("1. (should be true) "+cb1.getState());
passed = passed && (cb1.getState() == true);
cb1.setCheckboxGroup(null);
System.out.println("2. (should be true) "+cb1.getState());
passed = passed && (cb1.getState() == true);
}
// 2 step
{
CheckboxGroup g = new CheckboxGroup();
Checkbox cb1 = new Checkbox("CB1", true, g);
System.out.println("3. (should be true) " + cb1.getState());
passed = passed && (cb1.getState() == true);
g.setSelectedCheckbox(null);
System.out.println("4. (should be false) " + cb1.getState());
passed = passed && (cb1.getState() == false);
}
if (!passed) {
throw new RuntimeException("SetCheckboxGroupNull FAILED");
}
System.out.println("SetCheckboxGroupNull PASSED");
}
}

View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 2015, 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.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.Robot;
/**
* @test
* @key headful
* @bug 8074500
* @summary Checkbox.setState() call should not post ItemEvent
* @author Sergey Bylokhov
*/
public final class SetStateExcessEvent {
private static boolean failed;
public static void main(final String[] args) throws Exception {
final Robot robot = new Robot();
final CheckboxGroup group = new CheckboxGroup();
final Checkbox[] cbs = {new Checkbox("checkbox1", true, group),
new Checkbox("checkbox2", false, group),
new Checkbox("checkbox3", true, group),
new Checkbox("checkbox4", true),
new Checkbox("checkbox5", false),
new Checkbox("checkbox6", true)};
final Frame frame = new Frame();
frame.setLayout(new GridBagLayout());
try {
for (final Checkbox cb : cbs) {
cb.addItemListener(e -> {
failed = true;
});
}
for (final Checkbox cb : cbs) {
frame.add(cb);
}
frame.pack();
for (final Checkbox cb : cbs) {
cb.setState(!cb.getState());
}
for (final Checkbox cb : cbs) {
group.setSelectedCheckbox(cb);
}
robot.waitForIdle();
} finally {
frame.dispose();
}
if (failed) {
throw new RuntimeException("Listener should not be called");
}
System.out.println("Test passed");
}
}

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 1999, 2024, 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.BorderLayout;
import java.awt.Choice;
import java.awt.Frame;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/*
* @test
* @bug 4151949
* @summary Verifies that Components are reshaped to their preferred size
* when their Container is packed.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual CheckChoiceTest
*/
public class CheckChoiceTest {
private static JComponent componentToFocus;
private static final String INSTRUCTIONS = """
Verify that the widths of the Choice components are all the same
and that none is the minimum possible size.
(The Choices should be at least as wide as the Frame.)
""";
public static void main(String[] args) throws Exception {
PassFailJFrame passFailJFrame = PassFailJFrame.builder()
.title("CheckChoiceTest Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 3)
.columns(45)
.testUI(CheckChoiceTest::createAndShowUI)
.splitUIBottom(CheckChoiceTest::createComponentToFocus)
.build();
// focus away from the window with choices
Thread.sleep(300);
SwingUtilities.invokeAndWait(() -> componentToFocus.requestFocus());
passFailJFrame.awaitAndCheck();
}
private static JComponent createComponentToFocus() {
componentToFocus = new JPanel();
return componentToFocus;
}
private static Frame createAndShowUI() {
Frame f = new Frame("Check Choice");
f.setLayout(new BorderLayout());
Choice choice1 = new Choice();
Choice choice2 = new Choice();
Choice choice3 = new Choice();
f.add(choice1, BorderLayout.NORTH);
f.add(choice3, BorderLayout.CENTER);
f.add(choice2, BorderLayout.SOUTH);
f.pack();
choice1.add("I am Choice, yes I am : 0");
choice2.add("I am the same, yes I am : 0");
choice3.add("I am the same, yes I am : 0");
return f;
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2001, 2024, 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.Choice;
import java.awt.Frame;
import java.awt.FlowLayout;
import java.awt.Window;
/*
* @test
* @bug 4288285
* @summary Verifies choice works with many items
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ChoiceBigTest
*/
public class ChoiceBigTest {
private static final String INSTRUCTIONS = """
Click the Choice button, press Pass if:
- all looks good.
- if you can select the item 1000
Otherwise press Fail.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("ChoiceBigTest Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 3)
.columns(45)
.testUI(ChoiceBigTest::createAndShowUI)
.build()
.awaitAndCheck();
}
private static Window createAndShowUI() {
Frame frame = new Frame("Check Choice");
frame.setLayout(new FlowLayout());
Choice choice = new Choice();
frame.setSize(400, 200);
for (int i = 1; i < 1001; ++i) {
choice.add("I am Choice, yes I am : " + i);
}
frame.add(choice);
return frame;
}
}

View file

@ -0,0 +1,125 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6251988
@summary PIT: Choice consumes MouseReleased, MouseClicked events when clicking it with left button,
@key headful
*/
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ChoiceConsumeMouseEvents {
static volatile Frame frame;
static volatile Robot robot;
static volatile Choice choice1 = new Choice();
static volatile boolean mousePressed = false;
static volatile boolean mouseReleased = false;
static volatile boolean mouseClicked = false;
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
for (int i = 1; i<10; i++){
choice1.add("item-0"+i);
}
choice1.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
mousePressed = true;
System.out.println(me);
}
public void mouseReleased(MouseEvent me) {
mouseReleased = true;
System.out.println(me);
}
public void mouseClicked(MouseEvent me) {
mouseClicked = true;
System.out.println(me);
}
});
frame = new Frame("ChoiceConsumeMouseEvents");
frame.add(choice1);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.validate();
}
static void runTest() {
try {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(100);
testMouseClick(InputEvent.BUTTON1_DOWN_MASK, 0);
robot.delay(100);
testMouseClick(InputEvent.BUTTON1_DOWN_MASK, 100);
} catch (Throwable e) {
throw new RuntimeException("Test failed. Exception thrown: "+e);
}
}
static void testMouseClick(int button, int delay) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(button);
robot.delay(delay);
robot.mouseRelease(button);
robot.delay(200);
if (!(mousePressed &&
mouseReleased &&
mouseClicked))
{
throw new RuntimeException("Test failed. Choice should generate PRESSED, RELEASED, CLICKED events");
} else {
System.out.println("Test passed. Choice generated MouseDragged PRESSED, RELEASED, CLICKED events");
}
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
mousePressed = false;
mouseReleased = false;
mouseClicked = false;
}
}

View file

@ -0,0 +1,210 @@
/*
* Copyright (c) 2000, 2024, 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.
*/
/*
* @test
* @bug 6251983 6722236
* @summary MouseDragged events not triggered for Choice when dragging it with left mouse button
* @key headful
* @run main ChoiceDragEventsInside
*/
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.lang.reflect.InvocationTargetException;
public class ChoiceDragEventsInside extends Frame {
Robot robot;
Choice choice1;
Point pt;
Dimension size;
volatile boolean mouseDragged = false;
volatile boolean mouseDraggedOutside = false;
public void setupUI() {
setTitle("Choce Drag Events Inside");
choice1 = new Choice();
for (int i = 1; i < 50; i++) {
choice1.add("item-0" + i);
}
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
choice1.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent me) {
System.out.println(me);
}
public void mouseDragged(MouseEvent me) {
System.out.println(me);
mouseDragged = true;
if (me.getY() < 0) {
mouseDraggedOutside = true;
}
}
}
);
add(choice1);
setLayout(new FlowLayout());
setSize(200, 200);
setLocationRelativeTo(null);
setVisible(true);
validate();
}
public void start() {
try {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(100);
EventQueue.invokeAndWait(() -> {
pt = choice1.getLocationOnScreen();
size = choice1.getSize();
});
testDragInsideChoice(InputEvent.BUTTON1_MASK);
testDragInsideChoiceList(InputEvent.BUTTON1_MASK);
testDragOutsideChoice(InputEvent.BUTTON1_MASK);
} catch (Throwable e) {
throw new RuntimeException("Test failed. Exception thrown: " + e);
}
}
public void testDragInsideChoice(int button) {
robot.mouseMove(pt.x + size.width / 2, pt.y + size.height / 2);
robot.delay(100);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
robot.mouseMove(pt.x + size.width / 4, pt.y + size.height / 2);
robot.mousePress(button);
dragMouse(pt.x + size.width / 4, pt.y + size.height / 2,
pt.x + size.width * 3 / 4, pt.y + size.height / 2);
robot.mouseRelease(button);
robot.delay(200);
if (!mouseDragged) {
throw new RuntimeException("Test failed. Choice should generate MouseDragged events inside Choice itself");
} else {
System.out.println("Stage 1 passed. Choice generates MouseDragged events inside Choice itself");
}
mouseDragged = false;
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
public void testDragInsideChoiceList(int button) {
robot.mouseMove(pt.x + size.width / 2, pt.y + size.height / 2);
robot.delay(100);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
robot.mouseMove(pt.x + size.width / 2, pt.y + 5 * size.height);
robot.delay(200);
robot.mousePress(button);
dragMouse(pt.x + size.width / 2, pt.y + 5 * size.height,
pt.x + size.width / 2, pt.y + 8 * size.height);
robot.mouseRelease(button);
robot.delay(200);
if (mouseDragged) {
throw new RuntimeException("Test failed. Choice shouldn't generate MouseDragged events inside Choice's list");
} else {
System.out.println("Stage 2 passed. Choice doesn't generate MouseDragged events inside Choice's list");
}
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
mouseDragged = false;
}
public void testDragOutsideChoice(int button) {
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + size.width / 2, pt.y + size.height / 2);
robot.delay(100);
robot.mousePress(button);
//drag mouse outside of Choice
dragMouse(pt.x + size.width / 2, pt.y + size.height / 2,
pt.x + size.width / 2, pt.y - 3 * size.height);
robot.mouseRelease(button);
robot.delay(200);
if (!mouseDragged || !mouseDraggedOutside) {
throw new RuntimeException("Test failed. Choice should generate MouseDragged events outside Choice");
} else {
System.out.println("Stage 3 passed. Choice generates MouseDragged events outside Choice");
}
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
mouseDragged = false;
}
public void dragMouse(int x0, int y0, int x1, int y1) {
int curX = x0;
int curY = y0;
int dx = x0 < x1 ? 1 : -1;
int dy = y0 < y1 ? 1 : -1;
while (curX != x1) {
curX += dx;
robot.mouseMove(curX, curY);
}
while (curY != y1) {
curY += dy;
robot.mouseMove(curX, curY);
}
}
public static void main(final String[] args) throws InterruptedException,
InvocationTargetException {
ChoiceDragEventsInside app = new ChoiceDragEventsInside();
try {
EventQueue.invokeAndWait(app::setupUI);
app.start();
} finally {
EventQueue.invokeAndWait(app::dispose);
}
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright (c) 2000, 2023, 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.
*/
/*
@test
@bug 4338368
@summary Tests that choice doesn't throw spurious mouse events when losing focus
@key headful
*/
import java.awt.Button;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Robot;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ChoiceFocusLostTest {
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> createUI());
Robot robot = new Robot();
robot.waitForIdle();
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_TAB);
robot.waitForIdle();
robot.delay(1000);
if (!client.isPassed()) {
throw new RuntimeException("Test failed: choice fires spurious events");
} else {
System.out.println("Test passed.");
}
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static volatile Frame frame;
static volatile ChoiceBug client;
static void createUI() {
frame = new Frame("ChoiceFocusLostTest");
client = new ChoiceBug();
frame.add(client);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ChoiceBug extends Panel {
volatile boolean passed = true;
public ChoiceBug() {
Choice choice = new Choice();
choice.add("item-1");
choice.add("item-2");
Button button = new Button("Button");
add(choice);
add(button);
choice.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
passed = false;
}
public void mouseClicked(MouseEvent me) {
passed = false;
}
});
choice.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fe) {
System.out.println("Focus Gained");
System.out.println(fe);
}
public void focusLost(FocusEvent fe) {
System.out.println("Got expected FocusLost event.");
System.out.println(fe);
}
});
setSize(400, 400);
choice.requestFocus();
}
public boolean isPassed() {
return passed;
}
}

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2003, 2024, 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.Button;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Window;
/*
* @test
* @bug 4927930
* @summary Verify that the focus is set to the selected item after calling the java.awt.Choice.select() method
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ChoiceFocusTest
*/
public class ChoiceFocusTest {
private static final String INSTRUCTIONS = """
1. Use the mouse to select Item 5 in the Choice list.
2. Click on the Choice. Item5 is now selected and highlighted. This is the correct behavior.
3. Select Item 1 in the Choice list.
4. Click the "choice.select(5)" button. This causes a call to Choice.select(5). Item 5 is now selected.
5. Click on the Choice.
6. If the cursor and focus are on item 5, the test passes. Otherwise, it fails.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("ChoiceFocusTest Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 3)
.columns(50)
.testUI(ChoiceFocusTest::createAndShowUI)
.build()
.awaitAndCheck();
}
private static Window createAndShowUI() {
Panel panel = new Panel();
Choice choice = new Choice();
Button button = new Button("choice.select(5);");
for (int i = 0; i < 10; i++) {
choice.add(String.valueOf(i));
}
button.addActionListener(e -> choice.select(5));
panel.add(button);
panel.add(choice);
Frame frame = new Frame("ChoiceFocusTest");
frame.add(panel);
frame.pack();
return frame;
}
}

View file

@ -0,0 +1,132 @@
/*
* Copyright (c) 2000, 2023, 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.
*/
/*
@test
@bug 4303064
@summary Tests that choice doesn't freeze display when its container is
disabled and enabled after.
@key headful
*/
import java.awt.Button;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ChoiceFreezeTest {
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static volatile Frame frame;
static volatile ChoiceFreezeBug client;
static void createUI() {
frame = new Frame("ChoiceFreezeTest");
client = new ChoiceFreezeBug();
frame.add(client);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
client.init();
}
static void runTest() throws Exception {
Robot robot = new Robot();
robot.waitForIdle();
robot.delay(2000);
robot.mouseMove(client.choice.getLocationOnScreen().x + 1, client.choice.getLocationOnScreen().y + 1);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
robot.mouseMove(client.button.getLocationOnScreen().x + 3, client.button.getLocationOnScreen().y + 3);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(6000);
if (!client.isPassed()) {
throw new RuntimeException("Test failed: display is frozen.");
}
}
}
class ChoiceFreezeBug extends Panel {
volatile Button button;
volatile Choice choice;
volatile ChoiceMouseListener listener = new ChoiceMouseListener();
public ChoiceFreezeBug() {
choice = new Choice();
choice.addItem("Item 1");
choice.addItem("Item 2");
button = new Button("Button");
add(choice);
add(button);
button.addMouseListener(listener);
setEnabled(false);
}
void init() {
setEnabled(true);
choice.requestFocus();
}
public boolean isPassed() {
return listener.isPassed();
}
}
class ChoiceMouseListener extends MouseAdapter {
volatile boolean passed = false;
public void mouseReleased(MouseEvent e) {
passed = true;
}
public void mousePressed(MouseEvent e) {
passed = true;
}
public boolean isPassed() {
return passed;
}
}

View file

@ -0,0 +1,83 @@
/*
* Copyright (c) 2019, 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.
*/
/**
* @test
* @key headful
* @bug 8234386
* @requires (os.family == "mac")
* @summary [macos] NPE was thrown at expanding Choice from maximized frame
* @run main ChoiceFromMaximizedFrame
*/
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class ChoiceFromMaximizedFrame
{
static public void main(String args[]) throws Exception
{
Frame f = new Frame("ChoiceTest");
try {
Panel p =new Panel(new BorderLayout());
Choice choice = new Choice();
choice.addItem("aaa");
choice.addItem("bbb");
p.add("North",choice);
p.add("Center",new Canvas());
f.add(p);
GraphicsConfiguration gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
Rectangle bounds = gc.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
int x = bounds.x + insets.left;
int y = bounds.y + insets.top;
int width = bounds.width - insets.left - insets.right;
int height = bounds.height - insets.top - insets.bottom;
Rectangle rect = new Rectangle(x, y, width, height);
f.pack();
f.setBounds(rect);
f.setVisible(true);
Robot robot = new Robot();
robot.waitForIdle();
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
robot.delay(1000);
} finally {
f.dispose();
}
}
}

View file

@ -0,0 +1,129 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6239941
@summary Choice triggers ItemEvent when selecting an item with right mouse button, Xtoolkit
@key headful
@requires (os.family == "linux")
*/
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
public class ChoiceGeneratesItemEvents implements ItemListener {
public static void main(String[] args) throws Exception {
if (!System.getProperty("os.name").toLowerCase().startsWith("linux")) {
System.out.println("This test is for Linux only");
return;
}
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static volatile Frame frame;
static volatile Robot robot;
static volatile Choice choice1;
static volatile boolean passed = true;
static void createUI() {
choice1 = new Choice();
for (int i = 1; i<10; i++){
choice1.add("item-0"+i);
}
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
choice1.addItemListener(new ChoiceGeneratesItemEvents());
frame = new Frame("ChoiceGeneratesItemEvents");
frame.add(choice1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.validate();
frame.setVisible(true);
}
static void runTest() throws Exception {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(100);
testMousePressOnChoice(InputEvent.BUTTON2_DOWN_MASK);
testMousePressOnChoice(InputEvent.BUTTON3_DOWN_MASK);
if (!passed) {
throw new RuntimeException("Test failed.");
} else {
System.out.println("Test passed. ");
}
}
static void testMousePressOnChoice(int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(2000);
int px = pt.x + choice1.getWidth()/2;
int py = pt.y + 2 * choice1.getHeight();
Color color = robot.getPixelColor(px, py);
//we should take a color on the point on the choice's menu
System.out.println("Got color " + color + " at (" + px + "," + py + ")");
if (!color.equals(Color.red)) {
throw new RuntimeException("Test failed. Choice wasn't open with LEFTMOUSE button." +button);
}
robot.mouseMove(pt.x + choice1.getWidth()/2,
pt.y + 5*choice1.getHeight());
robot.delay(200);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
public void itemStateChanged(ItemEvent ie) {
System.err.println("Opened Choice generated ItemEvent on RIGHT/MIDDLE mouse press." +ie);
passed = false;
}
}

View file

@ -0,0 +1,206 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 5003166
@summary REG:Mouse button not validated before bringing up the drop-down menu for choice
@key headful
@requires (os.family == "linux" | os.family == "windows")
*/
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ChoiceHandleMouseEvent {
static Robot robot;
static volatile Choice choice1;
static volatile Frame frame;
public static void main(String[] args) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
if (!os.startsWith("windows") && !os.startsWith("linux")) {
System.out.println("This test is only for Windows and Linux");
return;
}
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
choice1 = new Choice();
choice1.add("item-01");
choice1.add("item-02");
choice1.add("item-03");
choice1.add("item-04");
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
frame = new Frame("ChoiceHandleMouseEvent");
frame.add(choice1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.validate();
frame.setVisible(true);
}
static void runTest() throws Exception {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
/*
* Stage 1: Choice should only opens with LEFTMOUSE click.
* Should only pass on Windows or XAWT.
* Choice on motif might be opened only by click on small box
* in the right side.
*/
testPressMouseButton(InputEvent.BUTTON2_DOWN_MASK);
testPressMouseButton(InputEvent.BUTTON3_DOWN_MASK);
System.out.println("Passed Stage 1: Choice should only opens with LEFT BUTTON.");
/*
* Stage 2: Choice should only change its value if pressed
* mouse button is LEFTMOUSE.
*/
// first parameter is for opening choice. The second is for
// selecting item inside the menu
testPressMouseButton_2(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK);
testPressMouseButton_2(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK);
System.out.println("Passed Stage 2: Choice should not change its value if pressed mouse buttonis not left.");
/*
* Stage 3: Choice should only react on drags with LEFTMOUSE button.
*/
// first parameter is for opening choice. The second is for
// selecting item inside the menu
testDragMouseButton(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK);
testDragMouseButton(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK);
System.out.println("Passed Stage 3: Choice should only react on drags with LEFTMOUSE button.");
}
static void testPressMouseButton(int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
int px = pt.x + choice1.getWidth()/2;
int py = pt.y + 3 * choice1.getHeight();
Color color = robot.getPixelColor(px, py);
//we should take a color on the point on the choice's menu
System.out.println("Got color " + color + " at (" + px + "," + py + ")");
System.out.println("RED="+Color.red);
if (color.equals(Color.red)) {
throw new RuntimeException("Test failed. Choice opens with "+button);
} else {
System.out.println("Stage 1 passed."+ button);
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
}
static void testPressMouseButton_2(int openButton, int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2,
pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(openButton);
robot.mouseRelease(openButton);
robot.delay(200);
robot.mouseMove(pt.x + choice1.getWidth()/2,
pt.y + 2 * choice1.getHeight());
robot.mousePress(button);
robot.mouseRelease(button);
System.out.println();
if (choice1.getSelectedIndex() == 0) {
System.out.println("Stage 2 passed." + openButton +":"+button);
} else {
throw new RuntimeException("Stage 2 failed." + openButton +":"+button);
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
}
static void testDragMouseButton(int openButton, int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(openButton);
robot.mouseRelease(openButton);
robot.delay(200);
robot.mousePress(button);
dragMouse(pt.x + choice1.getWidth()/2, pt.y +
choice1.getHeight()/2,
pt.x + choice1.getWidth()/2,
pt.y + 2 * choice1.getHeight());
robot.mouseRelease(button);
if (choice1.getSelectedIndex() == 0 ){
System.out.println("Stage 3 passed." + openButton +":"+button);
// System.out.println("choice1.getSelectedIndex()" + choice1.getSelectedIndex());
} else {
throw new RuntimeException("Stage 3 failed." + openButton +":"+button);
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
}
static void dragMouse(int x0, int y0, int x1, int y1) {
int curX = x0;
int curY = y0;
int dx = x0 < x1 ? 1 : -1;
int dy = y0 < y1 ? 1 : -1;
while (curX != x1){
curX += dx;
robot.mouseMove(curX, curY);
}
while (curY != y1 ){
curY += dy;
robot.mouseMove(curX, curY);
}
}
}

View file

@ -0,0 +1,340 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6239944
@summary PIT: Right clicking on the scrollbar of the choice's dropdown disposes the drop-down, on XToolkit
@key headful
@requires (os.family == "linux" | os.family == "windows")
*/
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ChoiceHandleMouseEvent_2 {
static Robot robot;
static volatile Choice choice1;
static volatile Frame frame;
static boolean isWindows;
public static void main(String[] args) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
if (!os.startsWith("windows") && !os.startsWith("linux")) {
System.out.println("This test is only for Windows and Linux");
return;
}
isWindows = os.startsWith("windows");
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
choice1 = new Choice();
for (int i = 1; i<50; i++) {
choice1.add("item-0"+i);
}
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
frame = new Frame("ChoiceHandleMouseEvent_2");
frame.setBackground(Color.green);
Panel panel = new Panel();
panel.setBackground(Color.green);
panel.add(choice1);
frame.add(panel);
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.validate();
frame.setVisible(true);
}
static void runTest() throws Exception {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(100);
/*
* Stage 1. Choice should be closed if user dragged mouse
* outside of Choice after opening it.
* Should only pass on Windows or XAWT.
* Choice on motif might be opened only by click on small box
* in the right side.
*/
testDragMouseButtonOut(InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Passed Stage 1: Choice should be closed if mouse dragged out.");
/*
* Stage 2: Choice should be closed if LeftMouse drag finished
* on Scrollbar. This involeves only one
* MousePress and one MouseRelease event
*/
// first parameter is for opening choice. The second is for
// selecting item inside the menu
testDragMouseButtonOnSB(InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Passed Stage 2: Choice should be closed if " +
"LeftMouse drag finished on Scrollbar.");
/*
* Stage 3: Pressing RIGHT/MIDDLE MouseButton on Scrollbar
* shouldn't close Choice's pop-down menu.
* Pressing LEFT MouseButton shouldn't close it too. It should
* scroll it.
* This is an unstable test because we doesn't have an API to
* get Scrollbar from Choice. There is a possibility not to
* hit the scrollbar that couldn't been predicted.
*/
// first parameter is for opening choice. The second is for
// selecting item inside the menu
testPressOnScrollbar(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON2_DOWN_MASK);
testPressOnScrollbar(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON3_DOWN_MASK);
System.out.println("Passed Stage 3: Choice correctly reacts on mouse click on its Scrollbar.");
/*
* Stage 4: Choice should close its popdown menu if user opened a Choice then
* releases Mouse and then presses Mouse again and dragged it on Choice's Scrollbar
* This involves only one MousePress and one MouseRelease
* event, so it differs from Stage 2.
*/
// first parameter is for opening choice. The second is for
// selecting item inside the menu or scrollbar
testDragMouseOnScrollbar(InputEvent.BUTTON1_DOWN_MASK, InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Passed Stage 4: Choice should close if user opened a " +
"Choice then releases Mouse and then presses Mouse again " +
"and drag it on Choice's Scrollbar .");
}
//Stage 4
static void testDragMouseOnScrollbar(int openButton, int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(openButton);
robot.mouseRelease(openButton);
robot.delay(200);
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.mousePress(button);
/*X-coordinate should be closer to right edge of Choice, so
divider 4 is used. */
dragMouse(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2,
pt.x + choice1.getWidth() - choice1.getHeight()/4, pt.y + 5*choice1.getHeight());
robot.mouseRelease(button);
robot.delay(200);
int px = pt.x + choice1.getWidth()/2;
int py = pt.y + 3 * choice1.getHeight();
Color color = robot.getPixelColor(px, py);
//should take a color on the point on the choice's menu
System.out.println("Got color " + color + " at (" + px + "," + py + ")");
if (color.equals(Color.red)) {
throw new RuntimeException(
"Test failed. Choice didn't close after drag without firstPress on ScrollBar " + button);
} else {
System.out.println("Stage 4 passed."+ button);
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
//stage 3
static void testPressOnScrollbar(int openButton, int button) {
if (!isWindows) {
return; // Windows-only tests.
}
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(openButton);
robot.mouseRelease(openButton);
robot.delay(200);
/*X-coordinate should be closer to right edge of Choice, so
divide by 4 is used. */
int px = pt.x + choice1.getWidth() - choice1.getHeight()/4;
int py = pt.y + 5*choice1.getHeight();
robot.mouseMove(px, py);
robot.delay(200);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
System.out.println("x= "+px);
System.out.println("y= "+py);
/*
This is for Windows only.
On XP theme choice become closed on RightMouseClick over a scrollbar.
A system menu is opened after that. On Classic theme Choice doesn't react on it at all.
*/
boolean isXPTheme = false;
Object themeObject = Toolkit.getDefaultToolkit().getDesktopProperty("win.xpstyle.themeActive");
// it returns null when Classic theme is active but we should
// check it's boolean value anyway if event it's not null.
if (themeObject != null) {
isXPTheme = ((Boolean)themeObject).booleanValue();
}
System.out.println("isXPTheme="+isXPTheme);
px = pt.x + choice1.getWidth()/2;
py = pt.y + 3 * choice1.getHeight();
Color color = robot.getPixelColor(px, py);
//we should take a color on the point on the choice's menu
System.out.println("Got color " + color + " at (" + px + "," + py + ")");
System.out.println("RED="+Color.red);
System.out.println("GREEN="+Color.green);
if (isXPTheme && button == InputEvent.BUTTON3_DOWN_MASK) {
if (!color.equals(Color.green)) {
throw new RuntimeException("Stage 3 failed(XP theme). " +
"Choice wasn't closed with pressing button on its Scrollbar" + openButton +":"+button);
} else {
System.out.println("Stage 3 passed(XP theme)." + openButton +":"+button);
}
} else {
if (!color.equals(Color.red)) {
throw new RuntimeException("Stage 3 failed(classic theme). " +
"Choice is being closed with pressing button on its Scrollbar" + openButton +":"+button);
} else {
System.out.println("Stage 3 passed(classic theme)." + openButton +":"+button);
}
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
// Stage 1
static void testDragMouseButtonOut(int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.mousePress(button);
dragMouse(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2,
pt.x + choice1.getWidth()*2, pt.y + choice1.getHeight()/2);
robot.mouseRelease(button);
robot.delay(200);
int px = pt.x + choice1.getWidth()/2;
int py = pt.y + 3 * choice1.getHeight();
Color color = robot.getPixelColor(px, py);
//should take a color on the point on the choice's menu
System.out.println("Got color " + color + " at (" + px + "," + py + ")");
System.out.println("RED="+Color.red);
// fix 6268989: On Windows Choice shouldn't been closed if
// Mouse dragged outside of Choice after one mouse press.
if (isWindows) {
if (color.equals(Color.red)) {
System.out.println("Stage 1 passed. On Windows Choice shouldn't be " +
"closed if Mouse dragged outside of Choice after one mouse press "+button);
} else {
throw new RuntimeException("Test failed. Choice on Windows shouldn't be " +
"closed after drag outside of Choice after one mouse press "+button);
}
} else {
if (color.equals(Color.red)) {
throw new RuntimeException("Test failed. Choice didn't close " +
"after drag outside of Choice "+button);
} else {
System.out.println("Stage 1 passed."+ button);
}
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
//stage 2
static void testDragMouseButtonOnSB(int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.mousePress(button);
/*X-coordinate should be closer to right edge of Choice, so
divider 4 is used. */
dragMouse(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2,
pt.x + choice1.getWidth() - choice1.getHeight()/4, pt.y + 5*choice1.getHeight());
robot.mouseRelease(button);
robot.delay(200);
int px = pt.x + choice1.getWidth()/2;
int py = pt.y + 3 * choice1.getHeight();
Color color = robot.getPixelColor(px, py);
//should take a color on the point on the choice's menu
System.out.println("Got color " + color + " at (" + px + "," + py + ")");
if (isWindows) {
if (color.equals(Color.red)) {
System.out.println("Stage 2 passed. On Windows Choice shouldn't be " +
" closed if Mouse dragged on its scrollbar "+button);
} else {
throw new RuntimeException("Test failed. On Windows Choice shouldn't be " +
" closed if Mouse dragged on its scrollbar "+button);
}
} else {
if (color.equals(Color.red)) {
throw new RuntimeException("Test failed. Choice didn't close after drag on ScrollBar "+button);
} else {
System.out.println("Stage 2 passed."+ button);
}
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
static void dragMouse(int x0, int y0, int x1, int y1) {
int curX = x0;
int curY = y0;
int dx = x0 < x1 ? 1 : -1;
int dy = y0 < y1 ? 1 : -1;
while (curX != x1) {
curX += dx;
robot.mouseMove(curX, curY);
}
while (curY != y1) {
curY += dy;
robot.mouseMove(curX, curY);
}
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2016, 2017, 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.
*/
/**
* @test
* @key headful
* @bug 8144594
* @summary HiDPI: awt.Choice looks improperly (Win 8)
* @run main ChoiceTest
*/
import java.awt.Frame;
import java.awt.Choice;
import java.awt.Font;
import java.util.stream.Stream;
public class ChoiceTest {
private static void UI() {
Frame frame = new Frame("Test frame");
Choice choice = new Choice();
Stream.of(new String[]{"item 1", "item 2", "item 3"}).forEach(choice::add);
frame.add(choice);
frame.setBounds(100, 100, 400, 200);
frame.setVisible(true);
Font font = choice.getFont();
int size = font.getSize();
int height = choice.getBounds().height;
try {
if (height < size) {
throw new RuntimeException("Test failed");
}
} finally {
frame.dispose();
}
}
public static void main(String[] args) throws Exception {
ChoiceTest.UI();
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 1998, 2024, 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.
*/
/*
* @test
* @bug 4130788
* @summary Choice components move unexpectedly when in lightweight containers
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ChoiceInLWTest
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
public class ChoiceInLWTest extends Frame implements Runnable {
private final Choice choices;
static final String INSTRUCTIONS = """
After test starts wait for two seconds and open a choice.
If choice's popup obscures the label above it press Fail.
Otherwise press Pass.
""";
public ChoiceInLWTest() {
setLayout(new BorderLayout());
Container lwCont = new Container();
lwCont.setLayout(new FlowLayout());
choices = new Choice();
choices.add("This is just a token item to get a nice width.");
lwCont.add(choices);
add("Center", lwCont);
Label label = new Label("You should see an unobscured Choice below.");
label.setAlignment(Label.CENTER);
add("North", label);
addChoiceItem();
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
super.windowOpened(e);
new Thread(ChoiceInLWTest.this).start();
}
});
pack();
}
private void addChoiceItem() {
choices.add("Adding an item used to move the Choice!");
}
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
addChoiceItem();
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("Choice in LW Container Test")
.testUI(ChoiceInLWTest::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,89 @@
/*
* Copyright (c) 1998, 2024, 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.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Robot;
/*
* @test
* @bug 4082078
* @summary Test for bug(s): 4082078, Multiple calls to Choice.insert cause core dump
* @key headful
* @run main ChoiceInsertTest
*/
public class ChoiceInsertTest extends Frame {
Choice c;
Label l;
private static ChoiceInsertTest choiceInsertTest;
public ChoiceInsertTest() {
c = new Choice();
l = new Label("If you see this, the choice insert bug is fixed!");
c.add("Initial choice");
add(c);
}
public void testInsertion() {
// inserting 30 or so items aborts Solaris VM
// in JDK's before 1.1.5
for (int nchoice = 0; nchoice < 30; nchoice++) {
c.insert("new choice", 0);
}
// if you made it to here the bug is not there anymore...
remove(l);
add(l);
validate();
}
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
try {
EventQueue.invokeAndWait(() ->{
choiceInsertTest = new ChoiceInsertTest();
choiceInsertTest.setTitle("ChoiceInsertTest");
choiceInsertTest.setLocationRelativeTo(null);
choiceInsertTest.setSize(500, 300);
choiceInsertTest.setLayout(new GridLayout());
choiceInsertTest.setVisible(true);
});
robot.waitForIdle();
robot.delay(500);
EventQueue.invokeAndWait(choiceInsertTest::testInsertion);
robot.delay(1000);
} finally {
EventQueue.invokeAndWait(() -> {
if (choiceInsertTest != null) {
choiceInsertTest.dispose();
}
});
}
System.err.println("ChoiceInsertTest: Didn't abort VM inserting 30 items, so we passed!");
}
}

View file

@ -0,0 +1,147 @@
/*
* Copyright (c) 2005, 2022, 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.
*/
/*
* @test
* @bug 6252982
* @key headful
* @summary PIT: Keyboard FocusTraversal not working when choice's drop-down is visible, on XToolkit
* @author andrei.dmitriev : area=awt.choice
* @run main ChoiceKeyEventReaction
*/
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class ChoiceKeyEventReaction
{
private static Robot robot;
private static Choice choice1 = new Choice();
private static Point pt;
private static TextField tf = new TextField("Hi");
private static boolean keyTypedOnTextField = false;
private static boolean itemChanged = false;
private static Frame frame;
private static String toolkit;
public static void main(String[] args) {
createAndShowGUI();
try {
robot = new Robot();
robot.setAutoDelay(100);
robot.waitForIdle();
moveFocusToTextField();
testKeyOnChoice(InputEvent.BUTTON1_MASK, KeyEvent.VK_UP);
} catch (Exception e) {
throw new RuntimeException("Test failed. Exception thrown: "+e);
} finally {
if (frame != null) {
frame.dispose();
}
}
}
private static void createAndShowGUI() {
frame = new Frame();
toolkit = Toolkit.getDefaultToolkit().getClass().getName();
System.out.println("Current toolkit is :" +toolkit);
for (int i = 1; i<20; i++){
choice1.add("item-0"+i);
}
tf.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent ke) {
keyTypedOnTextField = true;
System.out.println(ke);
}
});
choice1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
itemChanged = true;
System.out.println(e);
}
});
choice1.setFocusable(false);
frame.add(tf);
frame.add(choice1);
frame.setLayout (new FlowLayout());
frame.setSize (200,200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void testKeyOnChoice(int button, int key) {
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.mousePress(button);
robot.mouseRelease(button);
robot.waitForIdle();
robot.keyPress(key);
robot.keyRelease(key);
robot.waitForIdle();
System.out.println("keyTypedOnTextField = "+keyTypedOnTextField +": itemChanged = " + itemChanged);
if (itemChanged) {
throw new RuntimeException("Test failed. ItemChanged event occur on Choice.");
}
// We may just write
// if (toolkit.equals("sun.awt.windows.WToolkit") == keyTypedOnTextField) {fail;}
// but must report differently in these cases so put two separate if statements for simplicity.
if (!toolkit.equals("sun.awt.X11.XToolkit") &&
!keyTypedOnTextField) {
throw new RuntimeException("Test failed. (Win32/MacOS) KeyEvent wasn't addressed to TextField. ");
}
if (toolkit.equals("sun.awt.X11.XToolkit") &&
keyTypedOnTextField) {
throw new RuntimeException("Test failed. (XToolkit). KeyEvent was addressed to TextField.");
}
System.out.println("Test passed. Unfocusable Choice doesn't react on keys.");
}
public static void moveFocusToTextField() {
pt = tf.getLocationOnScreen();
robot.mouseMove(pt.x + tf.getWidth()/2, pt.y + tf.getHeight()/2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 2013, 2025, 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.
*/
/*
* @test
* @key headful
* @bug 7159566
* @summary The choice positioned in the top of window when clicking the choice.
* @author Petr Pchelko
* @library ../../regtesthelpers
* @build Util
* @run main ChoiceLocationTest
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.util.stream.Stream;
import test.java.awt.regtesthelpers.Util;
public class ChoiceLocationTest {
private static final int FRAME_LOCATION = 100;
private static final int FRAME_SIZE = 400;
private static final int CLICK_STEP = 5;
private static String[] choiceItems = new String[] {
"test item 1",
"test item 2",
"test item 3"
};
private static volatile Frame frame;
private static volatile Choice choice;
public static void main(String[] args) throws Exception {
try {
SwingUtilities.invokeAndWait(ChoiceLocationTest::initAndShowUI);
Robot r = new Robot();
r.waitForIdle();
r.delay(100);
Util.clickOnComp(choice, r);
choice.addItemListener(event -> {throw new RuntimeException("Failed: the choice popup is in the wrong place");});
// Test: click in several places on the top of the frame an ensure there' no choice there
Point locOnScreen = frame.getLocationOnScreen();
int x = locOnScreen.x + FRAME_SIZE / 2;
for (int y = locOnScreen.y + frame.getInsets().top + 10; y < locOnScreen.y + FRAME_SIZE / 3 ; y += CLICK_STEP) {
r.mouseMove(x, y);
r.waitForIdle();
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
r.waitForIdle();
r.delay(100);
}
} finally {
if (frame != null) {
frame.dispose();
}
}
}
private static void initAndShowUI() {
frame = new Frame("Test frame");
choice = new Choice();
Stream.of(choiceItems).forEach(choice::add);
frame.add(choice);
frame.setBounds(FRAME_LOCATION, FRAME_LOCATION, FRAME_SIZE, FRAME_SIZE);
frame.setVisible(true);
}
}

View file

@ -0,0 +1,138 @@
/*
* Copyright (c) 2000, 2024, 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.BorderLayout;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/*
* @test
* @bug 4328557
* @summary Tests that MouseDragged and MouseReleased are triggered on choice
* @library /lib/client
* @build ExtendedRobot
* @key headful
* @run main ChoiceMouseDragTest
*/
public class ChoiceMouseDragTest extends Frame {
private static final Choice choice = new Choice();
private static ExtendedRobot robot;
private volatile boolean isDragged;
private volatile boolean isReleased;
private static volatile ChoiceMouseDragTest choiceMouseDragTest;
public ChoiceMouseDragTest() {
super("ChoiceMouseDragTest");
this.setLayout(new BorderLayout());
choice.add("item-1");
choice.add("item-2");
choice.add("item-3");
choice.add("item-4");
add("Center", choice);
choice.addMouseListener(new MouseEventHandler());
choice.addMouseMotionListener(new MouseMotionEventHandler());
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() ->
choiceMouseDragTest = new ChoiceMouseDragTest());
robot = new ExtendedRobot();
robot.waitForIdle();
robot.delay(500);
Point pointToDrag = choice.getLocationOnScreen();
pointToDrag.x += choice.getWidth() - 10;
pointToDrag.y += choice.getHeight() / 2 ;
choiceMouseDragTest.test(InputEvent.BUTTON3_DOWN_MASK, pointToDrag);
choiceMouseDragTest.test(InputEvent.BUTTON1_DOWN_MASK, pointToDrag);
} finally {
EventQueue.invokeAndWait(() -> {
if (choiceMouseDragTest != null) {
choiceMouseDragTest.dispose();
}
});
}
}
void test(int buttonToTest, Point pointToDrag) {
isDragged = false;
isReleased = false;
robot.mouseMove(pointToDrag.x, pointToDrag.y);
robot.waitForIdle();
robot.mousePress(buttonToTest);
robot.glide(pointToDrag.x + 100, pointToDrag.y);
robot.waitForIdle();
robot.mouseRelease(buttonToTest);
robot.waitForIdle();
if (!isReleased || !isDragged) {
throw new RuntimeException(("Test failed: button %d dragged(received %b) or " +
"released(received %b)")
.formatted(buttonToTest, isDragged, isReleased));
}
robot.delay(500);
}
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent me) {
System.out.println(me.paramString());
}
public void mouseReleased(MouseEvent me) {
System.out.println(me.paramString());
isReleased = true;
}
public void mouseClicked(MouseEvent me) {
System.out.println(me.paramString());
}
}
class MouseMotionEventHandler extends MouseAdapter {
public void mouseDragged(MouseEvent me) {
System.out.println(me.paramString());
isDragged = true;
}
}
}

View file

@ -0,0 +1,145 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6272965
@summary PIT: Choice triggers MousePressed when pressing mouse outside comp while drop-down is active, XTkt
@key headful
*/
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ChoiceMouseEventOutbounds {
static final int DELAY = 100;
static volatile Choice choice1;
static volatile Frame frame;
static volatile Robot robot;
static volatile boolean mousePressed = false;
static volatile boolean mouseReleased = false;
static volatile boolean mouseClicked = false;
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
choice1 = new Choice();
for (int i = 1; i<10; i++) {
choice1.add("item "+i);
}
choice1.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
mousePressed = true;
System.out.println(me);
}
public void mouseReleased(MouseEvent me) {
mouseReleased = true;
System.out.println(me);
}
public void mouseClicked(MouseEvent me) {
mouseClicked = true;
System.out.println(me);
}
});
frame = new Frame("ChoiceMouseEventOutbounds");
frame.add(choice1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.validate();
}
static void runTest() throws Exception {
// On Windows, Choice will not close its pop-down menu on a RIGHT
// MousePress outside of the Choice. So this scenario isn't
// tested here for that reason.
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(DELAY*10);
testMouseClick(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(DELAY);
testMouseClick(InputEvent.BUTTON2_DOWN_MASK);
robot.delay(DELAY);
testMouseClick(InputEvent.BUTTON3_DOWN_MASK);
System.out.println("Test passed: Choice doesn't generate MOUSEPRESS/CLICK/RELEASE outside Choice.");
}
static void testMouseClick(int button) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(DELAY);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(DELAY);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(DELAY*3);
//they are true because we just pressed mouse
mousePressed = false;
mouseReleased = false;
mouseClicked = false;
//move mouse outside Choice
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y - choice1.getHeight());
robot.delay(DELAY*3);
robot.mousePress(button);
robot.delay(DELAY);
robot.mouseRelease(button);
if (mousePressed || mouseReleased || mouseClicked) {
System.out.println("ERROR: "+ mousePressed+","+mouseReleased +","+mouseClicked);
throw new RuntimeException(
"Test failed. Choice shouldn't generate PRESSED, RELEASED, CLICKED events outside "+ button);
} else {
System.out.println(
"Test passed. Choice didn't generated MouseDragged PRESSED, RELEASED, CLICKED events outside "+ button);
}
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(DELAY);
mousePressed = false;
mouseReleased = false;
mouseClicked = false;
}
}

View file

@ -0,0 +1,123 @@
/*
* Copyright (c) 2000, 2024, 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.
*/
/*
* @test
* @bug 4319246
* @summary Tests that MouseReleased, MouseClicked and MouseDragged are triggered on choice
* @key headful
* @run main ChoiceMouseEventTest
*/
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
public class ChoiceMouseEventTest extends Frame {
static volatile boolean mousePressed = false;
static volatile boolean mouseReleased = false;
static volatile boolean mouseClicked = false;
Choice choice = new Choice();
static Point location;
static Dimension size;
public void setupGUI() {
setTitle("Choice Mouse Event Test");
this.setLayout(new BorderLayout());
choice.add("item-1");
choice.add("item-2");
choice.add("item-3");
choice.add("item-4");
add("Center", choice);
choice.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
mouseClicked = true;
}
@Override
public void mousePressed(MouseEvent e) {
mousePressed = true;
}
@Override
public void mouseReleased(MouseEvent e) {
mouseReleased = true;
}
});
setLocationRelativeTo(null);
setSize(400, 200);
setVisible(true);
}
public Point _location() {
return choice.getLocationOnScreen();
}
public Dimension _size() {
return choice.getSize();
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException, AWTException {
ChoiceMouseEventTest test = new ChoiceMouseEventTest();
try {
EventQueue.invokeAndWait(test::setupGUI);
Robot robot = new Robot();
robot.setAutoDelay(50);
robot.delay(1000);
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
location = test._location();
size = test._size();
});
robot.waitForIdle();
robot.mouseMove(location.x + size.width - 10, location.y + (size.height / 2));
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(2000);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(2000);
robot.waitForIdle();
if (!mouseClicked || !mousePressed || !mouseReleased) {
throw new RuntimeException(String.format("One of the events not arrived: " +
"mouseClicked = %b, mousePressed = %b, mouseReleased = %b",
mouseClicked, mousePressed, mouseReleased));
}
} finally {
if (test != null) {
EventQueue.invokeAndWait(test::dispose);
}
}
}
}

View file

@ -0,0 +1,170 @@
/*
* Copyright (c) 2011, 2025, 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.
*/
/*
* @test
* @key headful
* @bug 7050935
* @summary closed/java/awt/Choice/WheelEventsConsumed/WheelEventsConsumed.html fails on win32
* @library /java/awt/regtesthelpers
* @build Util
* @run main ChoiceMouseWheelTest
*/
import test.java.awt.regtesthelpers.Util;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ChoiceMouseWheelTest extends Frame {
private volatile boolean itemChanged = false;
private volatile boolean wheelMoved = false;
private volatile boolean frameExited = false;
private final Choice choice;
public static void main(String[] args) throws Exception {
ChoiceMouseWheelTest test = Util.invokeOnEDT(ChoiceMouseWheelTest::new);
try {
test.test();
} finally {
EventQueue.invokeAndWait(test::dispose);
}
}
ChoiceMouseWheelTest() {
super("ChoiceMouseWheelTest");
setLayout(new FlowLayout());
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
});
choice = new Choice();
for(int i = 0; i < 50; i++) {
choice.add(Integer.toString(i));
}
choice.addItemListener(e -> itemChanged = true);
choice.addMouseWheelListener(e -> wheelMoved = true);
addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
frameExited = true;
}
});
add(choice);
setSize(200, 300);
setLocationRelativeTo(null);
setVisible(true);
toFront();
}
private void test() throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(20);
robot.waitForIdle();
robot.delay(500);
Rectangle choiceBounds = Util.invokeOnEDT(() -> {
Point pt = choice.getLocationOnScreen();
Dimension size = choice.getSize();
return new Rectangle(pt, size);
});
int x = choiceBounds.x + choiceBounds.width / 3;
robot.mouseMove(x, choiceBounds.y + choiceBounds.height / 2);
// Test mouse wheel over the choice
String name = Toolkit.getDefaultToolkit().getClass().getName();
boolean isXtoolkit = name.equals("sun.awt.X11.XToolkit");
boolean isLWCToolkit = name.equals("sun.lwawt.macosx.LWCToolkit");
// mouse wheel doesn't work for the choice on X11 and Mac, so skip it
if (!isXtoolkit && !isLWCToolkit) {
robot.mouseWheel(1);
robot.waitForIdle();
if (!wheelMoved || !itemChanged) {
throw new RuntimeException("Mouse Wheel over the choice failed!");
}
}
// Test mouse wheel over the drop-down list
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
frameExited = false;
Rectangle frameBounds = Util.invokeOnEDT(this::getBounds);
int y = frameBounds.y + frameBounds.height;
while (!frameExited && y >= frameBounds.y) { // move to the bottom of drop-down list
robot.mouseMove(x, --y);
robot.waitForIdle();
}
if (y < frameBounds.y) {
throw new RuntimeException("Could not enter drop-down list!");
}
y -= choiceBounds.height / 2;
robot.mouseMove(x, y); // move to the last visible item in the drop-down list
robot.waitForIdle();
int scrollDirection = isLWCToolkit ? -1 : 1;
// wheel to the last item
robot.mouseWheel(scrollDirection * choice.getItemCount());
robot.waitForIdle();
// click the last item
itemChanged = false;
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
if (!itemChanged || choice.getSelectedIndex() != choice.getItemCount() - 1) {
throw new RuntimeException("Mouse Wheel scroll position error!");
}
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright (c) 2000, 2023, 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.
*/
/*
@test
@bug 4323906
@summary Test that Choice location is not updated erroneously
@key headful
*/
/**
* summary: The test adds a Choice to a Container with BorderLayout, and
* adds the Container to a Frame with null Layout. When
* the Container is moved in the x direction, the Choice should
* not move in the y direction.
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Frame;
public class ChoiceMoveTest {
static volatile Frame frame;
static volatile Container c;
static volatile Choice ch;
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
frame = new Frame("Choice Move Test");
frame.setSize(500, 500);
frame.setLayout(null);
c = new Container();
c.setBackground(Color.green);
frame.add(c);
c.setSize(200, 200);
c.setLocation(100, 100);
c.setLayout(new BorderLayout());
ch = new Choice();
ch.setSize(100, 27);
c.add(ch, BorderLayout.SOUTH);
frame.setVisible(true);
frame.validate();
}
static void runTest () throws Exception {
Thread.sleep(1000);
// If this test ever gives us problems, try putting getLocation() in a
// ComponentListener.
int xbefore = ch.getLocation().x;
int ybefore = ch.getLocation().y;
System.out.println("Choice location before: " + xbefore + ", " + ybefore);
c.setLocation(200, 100);
Thread.sleep(1000);
java.awt.Toolkit.getDefaultToolkit().sync();
Thread.sleep(1000);
int xafter = ch.getLocation().x;
int yafter = ch.getLocation().y;
System.out.println("Choice location after: " + xafter + ", " + yafter);
if (ybefore != yafter) {
System.out.println("Test FAILED");
throw new RuntimeException("Test failed - Choice should not move in the y direction.");
}
else {
System.out.println("Test passed.");
}
}
}

View file

@ -0,0 +1,135 @@
/*
* Copyright (c) 2017, 2024, 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.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
* @test
* @key headful
* @bug 8176448
* @run main/timeout=300 ChoicePopupLocation
*/
public final class ChoicePopupLocation {
private static final int SIZE = 350;
private static int frameWidth;
private static Rectangle bounds;
public static void main(final String[] args) throws Exception {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] sds = ge.getScreenDevices();
Point left = null;
Point right = null;
for (GraphicsDevice sd : sds) {
GraphicsConfiguration gc = sd.getDefaultConfiguration();
bounds = gc.getBounds();
if (left == null || left.x > bounds.x) {
left = new Point(bounds.x, bounds.y + bounds.height / 2);
}
if (right == null || right.x < bounds.x + bounds.width) {
right = new Point(bounds.x + bounds.width,
bounds.y + bounds.height / 2);
}
Point point = new Point(bounds.x, bounds.y);
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
while (point.y < bounds.y + bounds.height - insets.bottom - SIZE ) {
while (point.x < bounds.x + bounds.width - insets.right - SIZE) {
test(point);
point.translate(bounds.width / 5, 0);
}
point.setLocation(bounds.x, point.y + bounds.height / 5);
}
}
if (left != null) {
left.translate(-50, 0);
test(left);
}
if (right != null) {
right.translate(-frameWidth + 50, 0);
test(right);
}
}
private static void test(final Point tmp) throws Exception {
Choice choice = new Choice();
for (int i = 1; i < 7; i++) {
choice.add("Long-long-long-long-long text in the item-" + i);
}
Frame frame = new Frame();
try {
frame.setAlwaysOnTop(true);
frame.setLayout(new FlowLayout());
frame.add(choice);
frame.pack();
frameWidth = frame.getWidth();
frame.setSize(frameWidth, SIZE);
frame.setVisible(true);
frame.setLocation(tmp.x, tmp.y);
openPopup(choice);
} finally {
frame.dispose();
}
}
private static void openPopup(final Choice choice) throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(100);
robot.setAutoWaitForIdle(true);
robot.waitForIdle();
robot.delay(500);
Point pt = choice.getLocationOnScreen();
robot.mouseMove(pt.x + choice.getWidth() / 2,
pt.y + choice.getHeight() / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
int x = pt.x + choice.getWidth() / 2;
int y = pt.y + choice.getHeight() / 2 + 70;
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
if (choice.getSelectedIndex() == 0) {
BufferedImage failImage = robot.createScreenCapture(bounds);
ImageIO.write(failImage, "png", new File("failImage.png"));
throw new RuntimeException();
}
}
}

View file

@ -0,0 +1,137 @@
/*
* Copyright (c) 1999, 2024, 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.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/*
* @test
* @bug 4075194
* @summary 4075194, Choice may not be displayed at the location requested
* @key headful
*/
public class ChoicePosTest {
private static Robot robot;
private static Frame frame;
private static final int GAP = 10;
private static volatile Choice c1,c2;
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(ChoicePosTest::createAndShowGUI);
robot = new Robot();
robot.waitForIdle();
robot.delay(500);
captureAndTestChoices();
} finally {
EventQueue.invokeAndWait(frame::dispose);
}
System.out.println("Passed");
}
private static void createAndShowGUI() {
frame = new Frame("ChoicePosTest");
Insets insets = frame.getInsets();
frame.setSize( insets.left + 400 + insets.right, insets.top + 400 + insets.bottom );
frame.setBackground(Color.RED);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
c1 = new Choice();
c1.setBackground(Color.GREEN);
frame.add( c1 );
c1.setBounds( 20, 50, 100, 100 );
c2 = new Choice();
c2.setBackground(Color.GREEN);
frame.add(c2);
c2.addItem("One");
c2.addItem("Two");
c2.addItem("Three");
c2.setBounds( 125, 50, 100, 100 );
frame.validate();
frame.setVisible(true);
}
private static void captureAndTestChoices() {
Point c1loc = c1.getLocationOnScreen();
Point c2loc = c2.getLocationOnScreen();
int startX = c1loc.x - GAP;
int startY = c1loc.y - GAP;
int captureWidth = c2loc.x + c2.getWidth() + GAP - startX;
int captureHeight = c2loc.y + c2.getHeight() + GAP - startY;
BufferedImage bi = robot.createScreenCapture(
new Rectangle(startX, startY, captureWidth, captureHeight)
);
int redPix = Color.RED.getRGB();
int lastNonRedCount = 0;
for (int y = 0; y < captureHeight; y++) {
int nonRedCount = 0;
for (int x = 0; x < captureWidth; x++) {
int pix = bi.getRGB(x, y);
if (pix != redPix) {
nonRedCount++;
}
}
if (nonRedCount > 0 && lastNonRedCount > 0) {
if (lastNonRedCount - nonRedCount > 0) {
System.err.printf(
"Failed at %d, nonRedCount: %d lastNonRedCount: %d\n",
y, nonRedCount, lastNonRedCount
);
try {
ImageIO.write(bi, "png", new File("choices.png"));
} catch (IOException ignored) {
}
throw new RuntimeException("Choices are not aligned");
}
}
lastNonRedCount = nonRedCount;
}
}
}

View file

@ -0,0 +1,111 @@
/*
* Copyright (c) 1999, 2024, 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.
*/
/*
* @test
* @bug 4079027
* @summary Removing an item dynamically from a Choice object breaks lower items.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ChoiceRemoveTest
*/
import java.awt.Choice;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ItemEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
public class ChoiceRemoveTest extends Frame {
Choice selector;
static final String INSTRUCTIONS = """
After window 'Choice Remove Test' appears wait for three seconds
and then click on the choice. In popup there should be no
'Choice A' variant. Try selecting each variant with mouse
and verify by the log that the correct variant gets selected.
If after selecting item in the list the correct item gets selected
and correct item name appears in the log press Pass otherwise press Fail.
""";
public static void main(String[] argv) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("Test Instructions")
.testUI(ChoiceRemoveTest::new)
.instructions(INSTRUCTIONS)
.columns(40)
.logArea()
.build()
.awaitAndCheck();
}
public ChoiceRemoveTest() {
super("Choice Remove Test");
Panel p;
Label prompt;
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
super.windowOpened(e);
new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException ignore) {
}
removeFirst();
}).start();
}
});
setLayout(new GridLayout());
p = new Panel();
prompt = new Label("Select different items including the last one");
p.add(prompt);
selector = new Choice();
selector.add("Choice A");
selector.add("Choice B");
selector.add("Choice C");
selector.add("Choice D");
selector.add("Choice E");
selector.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
Object selected = e.getItem();
PassFailJFrame.log(selected.toString());
}
});
p.add(selector);
add(p);
pack();
}
public void removeFirst() {
selector.remove("Choice A");
}
}

View file

@ -0,0 +1,174 @@
/*
* Copyright (c) 1998, 2023, 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.Choice;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Panel;
/*
* @test
* @bug 4115139 4128213
* @summary Tests that the (rather bizarre) rules for handling selection
* in Choice components are implemented as documented in
* "The Java Class Libraries 2nd Edition"
* @key headful
*/
public class ChoiceSelectTest extends Panel {
final Choice c;
public ChoiceSelectTest() {
setLayout(new FlowLayout());
c = new Choice();
add(c);
}
private void test() {
testAddition();
testInsertion();
testRemoval();
testIndices();
}
public void testAddition() {
c.removeAll();
// check that after first item added selection is zero
c.addItem("zero");
if (c.getSelectedIndex() != 0) {
throw new SelectionException("selection wrong after first add");
}
// check that selection doesn't change for subsequent adds
c.addItem("one");
c.select(1);
c.addItem("two");
if (c.getSelectedIndex() != 1) {
throw new SelectionException("selection wrong after subsequent add");
}
}
public void testInsertion() {
c.removeAll();
// check that after first item inserted selection is zero
c.insert("zero", 0);
if (c.getSelectedIndex() != 0) {
throw new SelectionException("selection wrong after first insert");
}
// check that if selected item shifted, selection goes to zero
c.insert("three", 1);
c.select(1);
c.insert("one", 1);
if (c.getSelectedIndex() != 0) {
throw new SelectionException("selection wrong after selected item shifted");
}
// check that if selected item not shifted, selection stays the same
c.select(1);
c.insert("two", 2);
if (c.getSelectedIndex() != 1) {
throw new SelectionException("selection wrong after item inserted after selection");
}
}
public void testRemoval() {
c.removeAll();
// check that if removing selected item, selection goes to 0
c.add("zero");
c.add("one");
c.add("two");
c.select(2);
c.remove(2);
if (c.getSelectedIndex() != 0) {
throw new SelectionException("selection wrong after removing selected item");
}
// check that if removing item before the selection
// the selected index is updated
c.add("two");
c.add("three");
c.select(3);
c.remove(1);
if (c.getSelectedIndex() != 2) {
throw new SelectionException("selection wrong after removing item before it");
}
}
public void testIndices() {
c.removeAll();
c.addItem("zero");
c.addItem("one");
c.addItem("two");
c.addItem("three");
c.addItem("four");
c.addItem("five");
// Test selection of negative index
try {
c.select(-1);
throw new SelectionException("Negative Index Test FAILED");
} catch (IllegalArgumentException expected) {}
// Test selection of zero index
try {
c.select(0);
} catch (IllegalArgumentException iae) {
throw new SelectionException("Zero Index Test FAILED", iae);
}
// Test selection of maximum index
try {
c.select(5);
} catch (IllegalArgumentException iae) {
throw new SelectionException("Maximum Index Test FAILED", iae);
}
// Test selection of index that is too large
try {
c.select(6);
throw new SelectionException("Greater than Maximum Index Test FAILED");
} catch (IllegalArgumentException expected) {}
}
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> new ChoiceSelectTest().test());
}
class SelectionException extends RuntimeException {
SelectionException(String msg, Throwable cause) {
super(msg, cause);
System.out.println(
"Selection item is '" + c.getSelectedItem() +
"' at index " + c.getSelectedIndex());
}
SelectionException(String msg) {
this(msg, null);
}
}
}

View file

@ -0,0 +1,150 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6239938
@summary Choice drop-down does not disappear when it loses focus, on XToolkit
@key headful
@requires (os.family == "linux")
*/
import java.awt.Button;
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ChoiceStaysOpenedOnTAB {
static volatile Robot robot;
static volatile Choice choice1;
static volatile Frame frame;
public static void main(String[] args) throws Exception {
if (!System.getProperty("os.name").toLowerCase().startsWith("linux")) {
System.out.println("This test is for Linux only");
return;
}
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
choice1 = new Choice();
for (int i = 1; i<10; i++) {
choice1.add("item-0"+i);
}
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
Button b1 = new Button("FirstButton");
Button b2 = new Button("SecondButton");
frame = new Frame("ChoiceStaysOpenedOnTAB");
Panel panel = new Panel();
panel.add(b1);
panel.add(choice1);
panel.add(b2);
frame.add(panel);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.validate();
frame.setVisible(true);
}
static void runTest() throws Exception {
/*
* Choice should not lose focus while it is opened with
* TAB/Shitf-TAB KeyPress on XAWT.
* Should only pass on XAWT.
*/
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(1000);
testTABKeyPress(InputEvent.BUTTON1_DOWN_MASK, KeyEvent.VK_TAB, false);
testTABKeyPress(InputEvent.BUTTON1_DOWN_MASK, KeyEvent.VK_TAB, true);
System.out.println("Passed : Choice should not lose focus on TAB key press while it is opened.");
}
static void testTABKeyPress(int openButton, int keyButton, boolean isShiftUsed) {
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.delay(100);
robot.mousePress(openButton);
robot.mouseRelease(openButton);
robot.delay(200);
Color color = robot.getPixelColor(pt.x + choice1.getWidth()/2,
pt.y + 3 * choice1.getHeight());
if (!color.equals(Color.red)) {
throw new RuntimeException(
"Choice wasn't opened with LEFTMOUSE button" + openButton +":"+keyButton+":"+isShiftUsed);
}
robot.delay(200);
if (isShiftUsed) {
robot.keyPress(KeyEvent.VK_SHIFT);
}
robot.keyPress(keyButton);
robot.keyRelease(keyButton);
if (isShiftUsed) {
robot.keyRelease(KeyEvent.VK_SHIFT);
}
robot.delay(200);
if (!choice1.isFocusOwner()) {
System.out.println("Choice has focus=="+choice1.isFocusOwner());
throw new RuntimeException(
"Choice has no focus after pressing TAB/Shitf+TAB" + openButton +":"+keyButton+":"+isShiftUsed);
}
int px = pt.x + choice1.getWidth()/2;
int py = pt.y + 3 * choice1.getHeight();
color = robot.getPixelColor(px, py);
//we should take a color on the point on the choice's menu
System.out.println("color got "+color);
if (!color.equals(Color.red)) {
throw new RuntimeException(
"Choice closed after TAB/Shift+TAB key press" + openButton +":"+keyButton+":"+isShiftUsed);
}
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 1998, 2024, 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.BorderLayout;
import java.awt.Choice;
import java.awt.Frame;
import jdk.test.lib.Platform;
/*
* @test
* @bug 4134619
* @summary Tests that the EventDispatchThread doesn't deadlock with
* user threads which are modifying a Choice component.
* @library /java/awt/regtesthelpers /test/lib
* @build PassFailJFrame jdk.test.lib.Platform
* @run main/manual DeadlockTest
*/
public class DeadlockTest extends Thread {
static volatile Choice choice1;
static volatile Choice choice2;
static volatile Choice choice3;
static volatile Frame frame;
static int itemCount = 0;
private static final boolean isWindows = Platform.isWindows();
private static final String INSTRUCTIONS = """
Click on the top Choice component and hold the mouse still briefly.
Then, without releasing the mouse button, move the cursor to a menu
item and then again hold the mouse still briefly.
%s
Release the button and repeat this process.
Verify that this does not cause a deadlock
or crash within a reasonable amount of time.
""".formatted(
isWindows
? "(menu can automatically collapse sometimes, this is ok)\n"
: ""
) ;
public static void main(String[] args) throws Exception {
DeadlockTest deadlockTest = new DeadlockTest();
PassFailJFrame passFailJFrame = PassFailJFrame.builder()
.title("DeadlockTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(deadlockTest::createAndShowUI)
.build();
deadlockTest.start();
passFailJFrame.awaitAndCheck();
}
public Frame createAndShowUI() {
frame = new Frame("Check Choice");
frame.setLayout(new BorderLayout());
choice1 = new Choice();
choice2 = new Choice();
choice3 = new Choice();
frame.add(choice1, BorderLayout.NORTH);
frame.add(choice3, BorderLayout.CENTER);
frame.add(choice2, BorderLayout.SOUTH);
frame.pack();
return frame;
}
public void run() {
while (true) {
if (choice1 != null && itemCount < 40) {
choice1.add("I am Choice, yes I am : " + itemCount * itemCount);
choice2.add("I am the same, yes I am : " + itemCount * itemCount);
choice3.add("I am the same, yes I am : " + itemCount * itemCount);
itemCount++;
}
if (itemCount >= 20 && choice1 != null &&
choice1.getItemCount() > 0) {
choice1.removeAll();
choice2.removeAll();
choice3.removeAll();
itemCount = 0;
}
frame.validate();
try {
Thread.sleep(1000);
} catch (Exception ignored) {}
}
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2011, 2024, 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.BorderLayout;
import java.awt.Checkbox;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ItemEvent;
/*
* @test
* @bug 6476183
* @summary Drop down of a Choice changed to enabled state has a disabled like appearance
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual DisabledList
*/
public class DisabledList {
private static final String INSTRUCTIONS = """
1) Select the checkbox
2) Open Choice
3) Drag mouse over the scrollbar or drag out it the choice
4) If choice's items become disabled press fail, otherwise pass
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("DisabledList Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 3)
.columns(45)
.testUI(DisabledList::createAndShowUI)
.logArea(4)
.build()
.awaitAndCheck();
}
private static Window createAndShowUI() {
Frame frame = new Frame("DisabledList");
frame.setSize(200, 200);
frame.validate();
Checkbox checkbox = new Checkbox("checkbox");
final Choice choice = new Choice();
choice.setEnabled(false);
for (int i = 0; i < 15; i++) {
choice.addItem("Item" + i);
}
checkbox.addItemListener(event -> {
PassFailJFrame.log("CheckBox.itemStateChanged occurred");
choice.setEnabled(event.getStateChange() == ItemEvent.SELECTED);
});
frame.add(BorderLayout.NORTH, checkbox);
frame.add(BorderLayout.CENTER, choice);
return frame;
}
}

View file

@ -0,0 +1,232 @@
/*
* Copyright (c) 2006, 2018, 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.
*/
/*
@test
@key headful
@bug 6322625
@summary REG:Choice does not trigger MouseReleased when dragging and releasing the mouse outside choice, XAWT
@author andrei.dmitriev area=awt.choice
@run main DragMouseOutAndRelease
*/
import java.awt.*;
import java.awt.event.*;
public class DragMouseOutAndRelease
{
static Frame frame = new Frame("Test Frame");
static Choice choice1 = new Choice();
static Robot robot;
static Point pt;
static volatile boolean mousePressed = false;
static volatile boolean mouseReleased = false;
private static void init()
{
frame.setLayout (new FlowLayout ());
for (int i = 1; i<10;i++){
choice1.add("item "+i);
}
frame.add(choice1);
choice1.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
mousePressed = true;
System.out.println(me);
}
public void mouseReleased(MouseEvent me) {
mouseReleased = true;
System.out.println(me);
}
});
frame.pack();
frame.setVisible(true);
frame.validate();
try {
robot = new Robot();
robot.setAutoDelay(50);
robot.waitForIdle();
testMouseDrag();
} catch (Throwable e) {
new RuntimeException("Test failed. Exception thrown: "+e);
}
DragMouseOutAndRelease.pass();
}//End init()
public static void testMouseDrag(){
mousePressed = false;
mouseReleased = false;
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle();
//move mouse outside Choice
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y - choice1.getHeight());
robot.waitForIdle();
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.waitForIdle();
if (!mousePressed || !mouseReleased)
{
System.out.println("ERROR: "+ mousePressed+","+mouseReleased);
// close the choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.waitForIdle();
DragMouseOutAndRelease.fail("Test failed. Choice should generate PRESSED, RELEASED events outside if pressed on Choice ");
} else{
// close the choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.waitForIdle();
System.out.println("Choice did generated PRESSED and RELEASED after Drag outside the Choice ");
}
}
/*****************************************************
* Standard Test Machinery Section
* DO NOT modify anything in this section -- it's a
* standard chunk of code which has all of the
* synchronisation necessary for the test harness.
* By keeping it the same in all tests, it is easier
* to read and understand someone else's test, as
* well as insuring that all tests behave correctly
* with the test harness.
* There is a section following this for test-
* classes
******************************************************/
private static boolean theTestPassed = false;
private static boolean testGeneratedInterrupt = false;
private static String failureMessage = "";
private static Thread mainThread = null;
private static int sleepTime = 300000;
// Not sure about what happens if multiple of this test are
// instantiated in the same VM. Being static (and using
// static vars), it aint gonna work. Not worrying about
// it for now.
public static void main( String args[] ) throws InterruptedException
{
mainThread = Thread.currentThread();
try
{
init();
}
catch( TestPassedException e )
{
//The test passed, so just return from main and harness will
// interepret this return as a pass
return;
}
//At this point, neither test pass nor test fail has been
// called -- either would have thrown an exception and ended the
// test, so we know we have multiple threads.
//Test involves other threads, so sleep and wait for them to
// called pass() or fail()
try
{
Thread.sleep( sleepTime );
//Timed out, so fail the test
throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
}
catch (InterruptedException e)
{
//The test harness may have interrupted the test. If so, rethrow the exception
// so that the harness gets it and deals with it.
if( ! testGeneratedInterrupt ) throw e;
//reset flag in case hit this code more than once for some reason (just safety)
testGeneratedInterrupt = false;
if ( theTestPassed == false )
{
throw new RuntimeException( failureMessage );
}
}
}//main
public static synchronized void setTimeoutTo( int seconds )
{
sleepTime = seconds * 1000;
}
public static synchronized void pass()
{
System.out.println( "The test passed." );
System.out.println( "The test is over, hit Ctl-C to stop Java VM" );
//first check if this is executing in main thread
if ( mainThread == Thread.currentThread() )
{
//Still in the main thread, so set the flag just for kicks,
// and throw a test passed exception which will be caught
// and end the test.
theTestPassed = true;
throw new TestPassedException();
}
theTestPassed = true;
testGeneratedInterrupt = true;
mainThread.interrupt();
}//pass()
public static synchronized void fail()
{
//test writer didn't specify why test failed, so give generic
fail( "it just plain failed! :-)" );
}
public static synchronized void fail( String whyFailed )
{
System.out.println( "The test failed: " + whyFailed );
System.out.println( "The test is over, hit Ctl-C to stop Java VM" );
//check if this called from main thread
if ( mainThread == Thread.currentThread() )
{
//If main thread, fail now 'cause not sleeping
throw new RuntimeException( whyFailed );
}
theTestPassed = false;
testGeneratedInterrupt = true;
failureMessage = whyFailed;
mainThread.interrupt();
}//fail()
}// class DragMouseOutAndRelease
//This exception is used to exit from any level of call nesting
// when it's determined that the test has passed, and immediately
// end the test.
class TestPassedException extends RuntimeException
{
}

View file

@ -0,0 +1,134 @@
/*
* Copyright (c) 2003, 2023, 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.
*/
/*
@test
@bug 4902933
@summary Test that dragging off an unfurled Choice prevents selecting a new item
@key headful
*/
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class DragOffNoSelectTest implements WindowListener, Runnable {
static volatile DragOffNoSelectTest testInstance;
static volatile Frame frame;
static volatile Choice theChoice;
static volatile Robot robot;
static final String firstItem = new String("First Choice Item");
static volatile Object lock = new Object();
public static void main(String[] args) throws Exception {
testInstance = new DragOffNoSelectTest();
robot = new Robot();
robot.setAutoDelay(500);
try {
EventQueue.invokeAndWait(() -> createUI());
runTest();
} finally {
if (frame != null) {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}
static void createUI() {
frame = new Frame("DragOffNoSelectTest");
theChoice = new Choice();
theChoice.add(firstItem);
for (int i = 0; i < 10; i++) {
theChoice.add(new String("Choice Item " + i));
}
frame.add(theChoice);
frame.addWindowListener(testInstance);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.validate();
}
static void runTest() throws Exception {
robot.mouseMove(10, 30);
synchronized (lock) {
try {
lock.wait(120000);
}
catch (InterruptedException e) {}
}
robot.waitForIdle();
if (!firstItem.equals(theChoice.getSelectedItem())) {
throw new RuntimeException("TEST FAILED - new item was selected");
}
}
public void run() {
robot.delay(1000);
// get loc of Choice on screen
Point loc = theChoice.getLocationOnScreen();
// get bounds of Choice
Dimension size = theChoice.getSize();
robot.mouseMove(loc.x + size.width - 10, loc.y + size.height / 2);
robot.setAutoDelay(500);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseMove(loc.x + size.width / 2, loc.y + size.height + size.height / 2);
robot.mouseMove(loc.x + size.width / 2, loc.y + 2*size.height + size.height / 2);
robot.mouseMove(loc.x + size.width / 2, loc.y + 3*size.height + size.height / 2);
robot.mouseMove(loc.x + size.width / 2, loc.y + 4*size.height + size.height / 2);
robot.mouseMove(loc.x + size.width, loc.y + 4*size.height + size.height / 2);
robot.mouseMove(loc.x + 2*size.width, loc.y + 4*size.height + size.height / 2);
robot.mouseMove(loc.x + 3*size.width, loc.y + 4*size.height + size.height / 2);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
synchronized(lock) {
lock.notify();
}
}
public void windowOpened(WindowEvent e) {
System.out.println("windowActivated()");
Thread testThread = new Thread(testInstance);
testThread.start();
}
public void windowActivated(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2003, 2023, 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.
*/
/*
@test
@bug 4908468
@summary Linux Empty Choice throws NPE
@key headful
@run main EmptyChoiceTest
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.lang.reflect.InvocationTargetException;
public class EmptyChoiceTest
{
Frame frame;
Choice choice = null;
public static void main(String[] args) throws
InterruptedException,
InvocationTargetException {
EventQueue.invokeAndWait(() -> {
EmptyChoiceTest emptyChoiceTest = new EmptyChoiceTest();
emptyChoiceTest.init();
emptyChoiceTest.test();
});
}
public void init() {
frame = new Frame();
frame.setLayout(new BorderLayout());
choice = new Choice();
frame.add(choice, BorderLayout.NORTH);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.validate();
}
public void test () {
try {
int iWidth = choice.getWidth();
int iHeight = choice.getHeight();
Image componentImage =
choice.createImage(iWidth, iHeight);
Graphics graphics =
componentImage.getGraphics();
graphics.setClip(0, 0, iWidth, iHeight);
choice.printAll(graphics);
System.out.println("PrintAll successful!");
} catch (NullPointerException exp) {
throw new RuntimeException("Test failed. " +
"Empty Choice printAll throws NullPointerException");
} catch (Exception exc){
throw new RuntimeException("Test failed.", exc);
} finally {
frame.dispose();
}
}
}

View file

@ -0,0 +1,102 @@
/*
* Copyright (c) 1999, 2020, 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.
*/
/*
@test
@key headful
@bug 4255631
@summary Solaris: Size returned by Choice.getSize() does not match actual size
@author Andrei Dmitriev : area=Choice
run main GetSizeTest.html
*/
import java.awt.Choice;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class GetSizeTest {
static String []s = {"Choice 1",
"Choice 2",
"unselected choices",
"what choices do I have?",
"Will I pick the same thing in the future?",
};
static volatile boolean passed = false;
public static void main(String args[]) throws Exception {
Frame f = null;
try {
Robot robot = new Robot();
robot.setAutoDelay(150);
f = new Frame("choice test");
Panel p = new Panel();
p.setLayout(null);
Choice c = new Choice();
for (int i = 0; i < s.length; i++)
c.addItem(s[i]);
c.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
System.err.println("Test passed");
passed = true;
}
});
p.add(c);
f.add(p);
f.setSize(300, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
c.setSize(200, 200);
f.validate();
robot.waitForIdle();
Point pt = c.getLocationOnScreen();
robot.mouseMove(pt.x + c.getWidth() - 10, pt.y + c.getHeight() / 2);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON2_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON2_DOWN_MASK);
robot.waitForIdle();
} finally {
if (f != null) {
f.dispose();
}
}
if (!passed) {
throw new RuntimeException( "Timeout. Choice component size is not actual size." );
}
System.err.println("Test passed.");
}
}

View file

@ -0,0 +1,111 @@
/*
* Copyright (c) 2003, 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.
*/
/*
@test
@key headful
@bug 4800638
@summary Tests that Choice does not lock the Desktop
@run main GrabLockTest
*/
import java.awt.*;
import java.awt.event.*;
public class GrabLockTest
{
public static void main (String args[])
{
Frame frame = new TestFrame();
}
}
class TestFrame extends Frame implements MouseListener {
public TestFrame() {
Choice choice = new Choice();
choice.addItem("Fist Item");
choice.addItem("Second Item");
add(choice,BorderLayout.NORTH);
Panel panel = new Panel();
panel.addMouseListener(this);
panel.setBackground(Color.RED);
add(panel);
setSize(200, 200);
setVisible(true);
toFront();
try {
Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.waitForIdle();
Point pt = choice.getLocationOnScreen();
robot.mouseMove(pt.x + choice.getWidth() - choice.getHeight()/2,
pt.y + choice.getHeight()/2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle();
robot.mouseMove(pt.x + choice.getWidth()/2,
pt.y + choice.getHeight()*2);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON2_MASK);
robot.waitForIdle();
Point pt1 = panel.getLocationOnScreen();
robot.mouseMove(pt1.x + panel.getWidth()/2,
pt1.y + panel.getHeight()/2);
robot.waitForIdle();
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON2_MASK);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(30);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.waitForIdle();
if (nPressed == 0) {
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
throw new RuntimeException("GrabLockTest failed." + nPressed);
}
} catch (Exception e) {
throw new RuntimeException("The test was not completed.\n\n" + e);
}
}
public int nPressed = 0;
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
nPressed++;
System.out.println("Pressed!");
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}// class TestFrame

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2003, 2023, 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.
*/
/*
@test
@bug 4115130
@summary Tests Inserting/Removing items doesn't cause crash.
@key headful
@run main InsertRemoveTest
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.lang.reflect.InvocationTargetException;
public class InsertRemoveTest {
Choice choice1;
Choice choice2;
Choice choice3;
Frame f;
int itemCount = 0;
int iterCount = 0;
public static void main(String[] args)
throws InterruptedException, InvocationTargetException {
EventQueue.invokeAndWait(() -> new InsertRemoveTest().start());
}
public void start() {
f = new Frame("Check Choice");
f.setLayout(new BorderLayout());
choice1 = new Choice();
choice2 = new Choice();
choice3 = new Choice();
f.add(choice1, BorderLayout.NORTH);
f.add(choice3, BorderLayout.CENTER);
f.add(choice2, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
try {
for (int i = 0; i < 50; i++) {
if (choice1 != null && itemCount < 40) {
choice1.insert("I am Choice, yes I am : " + iterCount,
0);
choice2.add("I am the same, yes I am : " + iterCount);
choice3.insert("I am the same, yes I am : " + iterCount,
10);
itemCount++;
iterCount++;
}
if (itemCount >= 20 && choice1 != null
&& choice1.getItemCount() > 0) {
choice1.remove(0);
choice2.remove(10);
choice3.remove(19);
itemCount--;
}
f.validate();
}
} finally {
f.dispose();
}
}
}

View file

@ -0,0 +1,132 @@
/*
* Copyright (c) 2012, 2018, 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.
*/
/*
@test
@key headful
@bug 7171412
@summary awt Choice doesn't fire ItemStateChange when selecting item after select() call
@author Oleg Pekhovskiy: area=awt-choice
@library ../../regtesthelpers
@library /test/lib
@modules java.desktop/sun.awt
@build Util
@build jdk.test.lib.Platform
@run main ItemStateChangeTest
*/
import jdk.test.lib.Platform;
import test.java.awt.regtesthelpers.Util;
import java.awt.*;
import java.awt.event.*;
public class ItemStateChangeTest extends Frame {
int events = 0;
public static void main(String args[]) {
new ItemStateChangeTest();
}
public ItemStateChangeTest() {
if (!Platform.isWindows()) {
return;
}
try {
final Robot robot = new Robot();
robot.setAutoDelay(20);
Util.waitForIdle(robot);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
final Choice choice = new Choice();
choice.add("A");
choice.add("B");
choice.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
++events;
}
});
add(choice);
setSize(200, 150);
setVisible(true);
toFront();
// choose B
int y = chooseB(choice, robot, 16);
// reset to A
choice.select(0);
robot.delay(20);
Util.waitForIdle(robot);
// choose B again
chooseB(choice, robot, y);
if (events == 2) {
System.out.println("Test passed!");
}
else {
throw new RuntimeException("Test failed!");
}
}
catch (AWTException e) {
throw new RuntimeException("Test failed!");
}
}
final int chooseB(Choice choice, Robot robot, int y) {
while (true) {
// show drop-down list
Util.clickOnComp(choice, robot);
Util.waitForIdle(robot);
Point pt = choice.getLocationOnScreen();
Dimension size = choice.getSize();
// try to click B item
robot.mouseMove(pt.x + size.width / 2, pt.y + size.height + y);
Util.waitForIdle(robot);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
Util.waitForIdle(robot);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Util.waitForIdle(robot);
if (choice.getSelectedIndex() == 1) {
break;
}
// if it's not B, position cursor lower by 2 pixels and try again
y += 2;
}
return y;
}
}

View file

@ -0,0 +1,74 @@
/*
* Copyright (c) 2005, 2024, 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.
*/
/*
* @test
* @bug 6367251
* @summary 2 items are highlighted when pressing, dragging the mouse inside the choice, XToolkit
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MultiItemSelected_DragOut
*/
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.lang.reflect.InvocationTargetException;
public class MultiItemSelected_DragOut extends Frame {
static final String INSTRUCTIONS = """
1) Open Choice.
2) Start drag from first item to second or third one.
3) Without releasing left mouse button
press and release right mouse button.
4) Release left mouse button.
5) Open choice again.
6) If there is only one selection cursor
in the dropdown list press Pass otherwise press Fail.
""";
public MultiItemSelected_DragOut() {
Choice choice = new Choice();
for (int i = 1; i < 10; i++) {
choice.add("item " + i);
}
add(choice);
choice.addItemListener(ie -> System.out.println(ie));
setLayout(new FlowLayout());
setSize(200, 200);
validate();
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("MultiItemSelected Drag Out Test")
.testUI(MultiItemSelected_DragOut::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 2005, 2024, 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.
*/
/*
* @test
* @bug 6367251
* @summary 2 items are highlighted when dragging inside and press ESC or ENTER
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MultiItemSelected_KeySelect
*/
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.lang.reflect.InvocationTargetException;
public class MultiItemSelected_KeySelect extends Frame {
static final String INSTRUCTIONS = """
1) Open Choice.
2) Start drag from first item to another one.
3) Without releasing the mouse button press ESC key.
4) Open choice again.
5) Verify that there is only one
selection cursor in the dropdown list.
6) Repeat steps 2-5 once again but this time
press ENTER key instead of ESC.
7) If in both scenarios there is only one selection cursor
press Pass otherwise press Fail.
""";
public MultiItemSelected_KeySelect() {
Choice choice = new Choice();
for (int i = 1; i < 10; i++) {
choice.add("item " + i);
}
add(choice);
choice.addItemListener(ie -> System.out.println(ie));
setLayout(new FlowLayout());
setSize(200, 200);
validate();
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("MultiItemSelected Key Select Test")
.testUI(MultiItemSelected_KeySelect::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,76 @@
/*
* Copyright (c) 2005, 2024, 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.
*/
/*
* @test
* @bug 6367251
* @summary 2 items are highlighted when dragging outside and press UP or DOWN
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MultiItemSelected_UpDown
*/
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.lang.reflect.InvocationTargetException;
public class MultiItemSelected_UpDown extends Frame {
static final String INSTRUCTIONS = """
1) Open Choice.
2) Start drag from first item to another one.
3) Without interrupting drag
move mouse cursor outside the choice popup.
4) Press UP, DOWN key several times to position
selection cursor to a different item.
5) Release mouse button.
6) If popup is closed upon mouse button release open Choice again.
7) Verify that there is only one
selection cursor in the dropdown list.
8) If true then press Pass, otherwise press Fail.
""";
public MultiItemSelected_UpDown() {
Choice choice = new Choice();
for (int i = 1; i < 20; i++) {
choice.add(" item " + i);
}
add(choice);
choice.addItemListener(ie -> System.out.println(ie));
setLayout(new FlowLayout());
setSize(200, 200);
validate();
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("MultiItemSelected Up/Down Test")
.testUI(MultiItemSelected_UpDown::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2007, 2024, 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.
*/
/*
* @test
* @bug 6519005
* @summary regression: Selection the item on the choice don't work properly in vista ultimate.
* @key headful
* @run main NonFocusablePopupMenuTest
*/
import java.awt.AWTException;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
public class NonFocusablePopupMenuTest extends Frame {
Choice choice;
volatile Point pos;
volatile Dimension size;
volatile int selection1, selection2;
public void performTest() throws AWTException,
InterruptedException, InvocationTargetException {
Robot robot = new Robot();
robot.setAutoDelay(100);
EventQueue.invokeAndWait(() -> {
choice = new Choice();
choice.add("111");
choice.add("222");
choice.add("333");
choice.add("444");
choice.setFocusable(false);
this.add(choice);
this.setLayout(new FlowLayout());
setSize (200, 200);
setLocationRelativeTo(null);
setVisible(true);
});
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
pos = choice.getLocationOnScreen();
size = choice.getSize();
selection1 = choice.getSelectedIndex();
});
robot.mouseMove(pos.x + size.width / 2, pos.y + size.height / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
robot.delay(500);
robot.mouseMove(pos.x + size.width / 2, pos.y + size.height * 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
selection2 = choice.getSelectedIndex();
setVisible(false);
dispose();
});
if (selection1 == selection2) {
throw new RuntimeException("Can not change choice selection with the mouse click");
}
}
public static void main(String[] args) throws AWTException,
InterruptedException, InvocationTargetException {
NonFocusablePopupMenuTest me = new NonFocusablePopupMenuTest();
me.performTest();
}
}

View file

@ -0,0 +1,145 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6246503
@summary Disabling a choice after selection locks keyboard, \
mouse and makes the system unusable
@key headful
@run main OpenedChoiceHangs
*/
import java.awt.AWTException;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Robot;
import java.awt.event.FocusEvent;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
public class OpenedChoiceHangs implements ItemListener {
static final Object FOCUS_LOCK = new Object();
Frame frame;
Choice ch = new Choice();
Button b = new Button("A button");
Robot robot;
public static void main(String[] args)
throws InterruptedException, InvocationTargetException {
OpenedChoiceHangs openedChoiceHangs = new OpenedChoiceHangs();
EventQueue.invokeAndWait(openedChoiceHangs::init);
openedChoiceHangs.test();
}
public void init() {
frame = new Frame();
frame.setLayout(new FlowLayout());
for (int i = 1; i < 10; i++) {
ch.add("item " + i);
}
frame.add(ch);
frame.add(b);
ch.setBackground(new Color(255, 0, 0));
ch.setForeground(new Color(255, 0, 0));
ch.addItemListener(this);
frame.setSize(200, 200);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.validate();
}
public void test() {
try {
robot = new Robot();
robot.setAutoDelay(100);
robot.setAutoWaitForIdle(true);
robot.delay(1000);
robot.mouseMove(ch.getLocationOnScreen().x + ch.getWidth() / 2,
ch.getLocationOnScreen().y + ch.getHeight() / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
if (!ch.isFocusOwner()) {
synchronized (FOCUS_LOCK) {
FOCUS_LOCK.wait(3000);
}
}
if (!ch.isFocusOwner()){
throw new RuntimeException(
"Test failed. Choice has no focus after mouse press.");
}
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
robot.delay(1000);
Color color = robot.getPixelColor(
ch.getLocationOnScreen().x + ch.getWidth() / 2,
ch.getLocationOnScreen().y + ch.getHeight() * 4);
System.out.println("Color is " + color);
if (color.equals(new Color(255, 0,0))){
throw new RuntimeException(
"Test failed. Choice is disabled and still opened. ");
}
} catch (AWTException e) {
throw new RuntimeException(
"Test interrupted due to AWTException. Robot=" + robot, e);
} catch (InterruptedException e) {
throw new RuntimeException("Test interrupted. Robot=" + robot, e);
} finally {
EventQueue.invokeLater(frame::dispose);
}
System.out.println("Test passed: Choice became closed after disabling.");
}
public void itemStateChanged (ItemEvent ie) {
System.out.println("Choice Item has changed: "+ie);
ch.setEnabled(false);
}
public void focusGained(FocusEvent fEvent){
System.out.println("focusGained"+fEvent);
synchronized(FOCUS_LOCK){
FOCUS_LOCK.notify();
}
}
public void focusLost(FocusEvent fEvent){
System.out.println("focusLost"+fEvent);
}
}

View file

@ -0,0 +1,122 @@
/*
* Copyright (c) 2006, 2025, 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.
*/
/*
* @test
* @bug 6405689
* @key headful
* @summary Reg: Painting is not happening properly,
* when Choice scrollbar gets disappeared after selected item
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual PaintArtefacts
*/
import java.awt.Button;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class PaintArtefacts {
static boolean removeItems = true;
private static final String INSTRUCTIONS = """
The problem is seen on XToolkit only.
Open the choice and press down or up key several times
until the scrollbar gets disappeared.
At that moment you may see a painting artefacts on dropdown menu
If you see them, press Fail.
If you don't see them press Add/Remove switch button and
again open the choice and press Up/Down key several times
until Scrollbar gets appeared back.
If you still don't see any painting artefacts press Pass.
""";
private static Frame init() {
Frame frame = new Frame("Painting Frame");
Button b = new Button ("Add/Remove switch");
final Choice ch = new Choice();
ch.add("Praveen");
ch.add("Mohan");
ch.add("Rakesh");
ch.add("Menon");
ch.add("Girish");
ch.add("Ramachandran");
ch.add("Elancheran");
ch.add("Subramanian");
ch.add("Raju");
ch.add("Pallath");
ch.add("Mayank");
ch.add("Joshi");
ch.add("Sundar");
ch.add("Srinivas");
ch.add("Mandalika");
ch.add("Suresh");
ch.add("Chandar");
ch.select(1);
frame.setLayout(new FlowLayout());
frame.add(ch);
frame.add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
PassFailJFrame.log(ae.toString());
PassFailJFrame.log("selected index = " + ch.getSelectedIndex());
removeItems = !removeItems;
}
});
ch.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
PassFailJFrame.log(ie.toString());
PassFailJFrame.log("selected index = " + ch.getSelectedIndex());
if (removeItems) {
PassFailJFrame.log("REMOVE : " + ch.getSelectedIndex());
ch.remove(ch.getSelectedIndex());
} else {
PassFailJFrame.log("ADD : "+ch.getSelectedIndex() + "/" + "new item");
ch.add("new item");
}
}
});
frame.setSize(200, 200);
for (int i = 0; i < 5; i++){
ch.remove(ch.getSelectedIndex());
}
return frame;
}
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(PaintArtefacts::init)
.logArea()
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,144 @@
/*
* Copyright (c) 2011, 2018, 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.
*/
/*
@test
@key headful
@bug 6200670
@summary MouseMoved events are triggered by Choice when mouse is moved outside the component, XToolkit
@library ../../regtesthelpers/
@build Util
@run main PopdownGeneratesMouseEvents
*/
import test.java.awt.regtesthelpers.Util;
import java.awt.*;
import java.awt.event.*;
public class PopdownGeneratesMouseEvents extends Frame {
private volatile Robot robot;
private final Choice choice1 = new Choice();
private volatile MouseMotionHandler mmh;
public static void main(final String[] args) {
PopdownGeneratesMouseEvents app = new PopdownGeneratesMouseEvents();
app.init();
app.start();
}
public void init() {
for (int i = 1; i < 10; i++) {
choice1.add("item-0" + i);
}
choice1.setForeground(Color.RED);
choice1.setBackground(Color.RED);
mmh = new MouseMotionHandler();
choice1.addMouseMotionListener(mmh);
Button b1 = new Button("FirstButton");
Button b2 = new Button("SecondButton");
add(b1);
add(choice1);
add(b2);
setLayout (new FlowLayout());
}
public void start() {
setSize(300, 200);
setLocationRelativeTo(null);
setVisible(true);
validate();
String toolkit = Toolkit.getDefaultToolkit().getClass().getName();
/*
* Choice should not generate MouseEvents outside of Choice
* Test for XAWT only.
*/
try{
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
if (toolkit.equals("sun.awt.X11.XToolkit")) {
testMouseMoveOutside();
} else {
System.out.println("This test is for XToolkit only. Now using "
+ toolkit + ". Automatically passed.");
return;
}
} catch (Throwable e) {
throw new RuntimeException("Test failed. Exception thrown: " + e);
}
System.out.println("Passed : Choice should not generate MouseEvents outside of Choice.");
}
private void testMouseMoveOutside() {
waitForIdle();
Point pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth() / 2, pt.y + choice1.getHeight() / 2);
waitForIdle();
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
waitForIdle();
Color color = robot.getPixelColor(pt.x + choice1.getWidth() / 2,
pt.y + 3 * choice1.getHeight());
if (!color.equals(Color.RED)) {
throw new RuntimeException("Choice wasn't opened with LEFTMOUSE button");
}
pt = getLocationOnScreen();
robot.mouseMove(pt.x + getWidth() * 2, pt.y + getHeight() * 2);
mmh.testStarted = true;
int x0 = pt.x + getWidth() * 3 / 2;
int y0 = pt.y + getHeight() * 3 / 2;
int x1 = pt.x + getWidth() * 2;
int y1 = pt.y + getHeight() * 2;
Util.mouseMove(robot, new Point(x0, y0), new Point(x1, y0));
Util.mouseMove(robot, new Point(x1, y0), new Point(x1, y1));
waitForIdle();
//close opened choice
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
}
private void waitForIdle() {
Util.waitForIdle(robot);
robot.delay(500);
}
}
class MouseMotionHandler extends MouseMotionAdapter {
public volatile boolean testStarted;
public void mouseMoved(MouseEvent ke) {
if (testStarted) {
throw new RuntimeException("Test failed: Choice generated MouseMove events while moving mouse outside of Choice");
}
}
public void mouseDragged(MouseEvent ke) {
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright (c) 2005, 2024, 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.
*/
/*
* @test
* @bug 6240046
* @summary REG:Choice's Drop-down does not disappear when clicking somewhere, after popup menu is disposed-XTkt
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual PopupMenuOnChoiceArea
*/
import java.awt.CheckboxMenuItem;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.PopupMenu;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
public class PopupMenuOnChoiceArea extends Frame {
static final String INSTRUCTIONS = """
You would see a window named 'Popup menu on choice area'
with Choice in it. Move the mouse pointer to the choice.
Click right mouse button on it.
You should see a popup menu with 'File' in it.
Close this popup menu by pressing Esc.
Click the left mouse button on the Choice.
You should see a Choice drop-down menu.
Move mouse pointer into drop-down menu.
Click right mouse button on any item in it.
If you see a 'File' popup menu press Fail.
If Choice drop-down closes instead press Pass.
""";
public PopupMenuOnChoiceArea() {
super("Popup menu on choice area");
this.setLayout(new FlowLayout());
Choice choice = new Choice();
choice.add("item-1");
choice.add("item-2");
choice.add("item-3");
choice.add("item-4");
add("Center", choice);
Menu fileMenu = new Menu("File");
Menu open = new Menu("Open");
Menu save = new Menu("save");
CheckboxMenuItem exit = new CheckboxMenuItem("Exit");
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(exit);
final PopupMenu pop = new PopupMenu();
pop.setLabel("This is a popup menu");
pop.setName("a menu");
pop.add(fileMenu);
choice.add(pop);
choice.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger()) {
pop.show(me.getComponent(), me.getX(), me.getY());
}
}
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
pop.show(me.getComponent(), me.getX(), me.getY());
}
}
});
setSize(200, 200);
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("Test Instructions")
.testUI(PopupMenuOnChoiceArea::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,154 @@
/*
* Copyright (c) 2004, 2025, 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.
*/
/*
@test
@key headful
@bug 5044150
@summary Tests that pupup doesn't popdown if no space to display under
@requires (os.family == "linux")
@run main PopupPosTest
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
public class PopupPosTest {
public static void main(final String[] args) {
Frame frame = new TestFrame();
}
}
class TestFrame extends Frame implements ItemListener {
Robot robot;
Toolkit tk = Toolkit.getDefaultToolkit();
Choice choice = new Choice();
boolean indexChanged = false;
final static int INITIAL_ITEM = 99;
volatile boolean stateChanged;
public TestFrame() {
for (int i = 0; i < 100; i++) {
choice.addItem("Item Item Item " + i);
}
choice.addItemListener(this);
choice.select(INITIAL_ITEM);
choice.setFont(new Font("Courier", Font.BOLD + Font.ITALIC, 100));
add(choice, BorderLayout.CENTER);
Dimension screen = tk.getScreenSize();
setSize(screen.width - 10, screen.height - 70);
setVisible(true);
toFront();
try {
robot = new Robot();
robot.setAutoDelay(50);
robot.waitForIdle();
robot.delay(500);
// fix for 6175418. When we take "choice.getHeight()/2"
// divider 2 is not sufficiently big to hit into the
// small box Choice. We should use bigger divider to get
// smaller value choice.getHeight()/i. 4 is sufficient.
Point pt = choice.getLocationOnScreen();
// click on 1/4 of Choice's height
mouseMoveAndPressOnChoice(pt.x + choice.getWidth()/2,
pt.y + choice.getHeight()/4);
// click on center of Choice's height
mouseMoveAndPressOnChoice(pt.x + choice.getWidth()/2,
pt.y + choice.getHeight()/2);
// click on 3/4 of Choice's height
mouseMoveAndPressOnChoice(pt.x + choice.getWidth()/2,
pt.y + choice.getHeight()*3/4);
// testing that ItemEvent doesn't generated on a simple
// mouse click when the dropdown appears under mouse : 6425067
robot.waitForIdle();
robot.delay(250);
stateChanged = false;
openChoice();
closeChoice();
} catch (Throwable e) {
throw new RuntimeException("The test was not completed.\n\n" + e);
}
if (!indexChanged){
throw new RuntimeException("Test failed. Another item wasn't selected.");
}
if(stateChanged){
throw new RuntimeException("Test failed. ItemEvent was generated on a simple mouse click when the dropdown appears under mouse");
}
}// start()
public void itemStateChanged(ItemEvent ie) {
System.out.println("choice.stateChanged = "+ ie);
stateChanged = true;
}
public void mouseMoveAndPressOnChoice(int x, int y){
openChoice();
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(30);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
//should close choice after each test stage
closeChoice();
checkSelectedIndex();
}
public void openChoice(){
Point pt = choice.getLocationOnScreen();
robot.mouseMove(pt.x + choice.getWidth() - choice.getHeight()/4,
pt.y + choice.getHeight()/2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(30);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
}
public void closeChoice(){
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.waitForIdle();
}
public void checkSelectedIndex(){
if (choice.getSelectedIndex() != INITIAL_ITEM) {
System.out.println("choice.getSelectedIndex = "+ choice.getSelectedIndex());
indexChanged = true;
}
}
}// class TestFrame

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 2005, 2023, 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.
*/
/*
@test
@bug 6259328
@summary Choice scrolls when dragging the parent frame while drop-down \
is active
@key headful
@run main PressOutsideOpenedChoice
*/
import java.awt.Choice;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
public class PressOutsideOpenedChoice extends Frame {
Robot robot;
Choice choice1 = new Choice();
Point pt;
public static void main(String[] args)
throws InterruptedException, InvocationTargetException {
PressOutsideOpenedChoice pressOutsideOpenedChoice =
new PressOutsideOpenedChoice();
EventQueue.invokeAndWait(pressOutsideOpenedChoice::init);
pressOutsideOpenedChoice.start();
}
public void init() {
for (int i = 1; i < 50; i++) {
choice1.add("item-" + i);
}
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
add(choice1);
setLayout(new FlowLayout());
setSize (200,200);
setLocationRelativeTo(null);
setVisible(true);
validate();
}
public void start() {
try {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.delay(1000);
testPressOutsideOpenedChoice(InputEvent.BUTTON1_DOWN_MASK);
} catch (Throwable e) {
throw new RuntimeException("Test failed. Exception thrown: " + e);
} finally {
EventQueue.invokeLater(this::dispose);
}
}
public void testPressOutsideOpenedChoice(int button) {
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth() - choice1.getHeight() / 4,
pt.y + choice1.getHeight() / 2);
robot.delay(100);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
//move mouse outside of the choice
robot.mouseMove(pt.x - choice1.getWidth() / 2,
pt.y + choice1.getHeight() / 2);
robot.delay(400);
robot.mousePress(button);
robot.mouseRelease(button);
robot.delay(200);
Color color = robot.getPixelColor(pt.x + choice1.getWidth() / 2,
pt.y + 3 * choice1.getHeight());
System.out.println("color got " +
robot.getPixelColor(pt.x + choice1.getWidth() / 2,
pt.y + 3 * choice1.getHeight()));
if (color.equals(Color.red)) {
throw new RuntimeException("Test failed. Choice didn't close " +
"after mouse press outside of Choice " + button);
} else {
System.out.println("Test passed. " +
"Choice closed with MousePress outside");
}
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2014, 2020, 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.
*/
/*
@test
@key headful
@bug 4851798 8041896 8225126
@summary Tests Choice List shrinks after removeAll
@run main RemoveAllShrinkTest
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
public class RemoveAllShrinkTest {
public static void main(String[] args) {
Frame f = new Frame();
try {
Choice choice = new Choice();
for (int i = 0; i < 10; ++i) {
choice.addItem("Item " + i);
}
f.add(choice, BorderLayout.NORTH);
Panel panel = new Panel();
panel.setBackground(Color.RED);
f.add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.toFront();
choice.removeAll();
try {
Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.waitForIdle();
Thread.sleep(200);
Point pt = choice.getLocationOnScreen();
robot.mouseMove(pt.x + choice.getWidth() - choice.getHeight() / 2,
pt.y + choice.getHeight() / 2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(400);
Point pt1 = panel.getLocationOnScreen();
Color color = robot.getPixelColor(pt1.x + panel.getWidth() / 2,
pt1.y + panel.getHeight() / 2);
if (!color.equals(Color.RED)) {
throw new RuntimeException("RemoveAllShrinkTest failed. " + color);
}
} catch (Exception e) {
throw new RuntimeException("The test was not completed.\n\n" + e);
}
} finally {
f.dispose();
}
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2005, 2024, 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.
*/
/*
* @test
* @bug 6292186
* @summary Choice is not refreshed properly when the last item gets removed
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual RepaintAfterRemoveLastItemTest
*/
import java.awt.Button;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
public class RepaintAfterRemoveLastItemTest extends Frame implements ActionListener {
Choice ch = new Choice();
static final String INSTRUCTIONS = """
Press on the 'remove' button after that if the choice does not display
'only item' press Pass. If 'only item' is still displayed press Fail.
""";
public RepaintAfterRemoveLastItemTest() {
ch.add("only item");
add(ch);
Button b = new Button("remove");
add(b);
b.addActionListener(this);
setLayout(new FlowLayout());
setSize(200, 200);
validate();
}
public void actionPerformed(ActionEvent ae) {
if (ch.getItemCount() != 0) {
ch.remove(0);
}
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("Repaint After Remove Test")
.testUI(RepaintAfterRemoveLastItemTest::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,114 @@
/*
* Copyright (c) 2006, 2018, 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.
*/
/*
@test
@key headful
@bug 6399679
@summary Choice is not invalidated when the frame gets resized programmatically when the drop-down is visible
@author andrei.dmitriev area=awt.choice
@library /test/lib
@build jdk.test.lib.Platform
@run main ResizeAutoClosesChoice
*/
import java.awt.*;
import java.awt.event.*;
import jdk.test.lib.Platform;
public class ResizeAutoClosesChoice
{
static Frame frame = new Frame("Test Frame");
static Choice choice1 = new Choice();
static Robot robot;
static Point pt;
static String passed = null;
static Button button = new Button("This button causes Frame to be resized on pack()");
public static void main(String args[]) throws Exception
{
if (Platform.isOSX()) {
System.out.println("Not for OS OX");
return;
}
choice1.setForeground(Color.red);
choice1.setBackground(Color.red);
frame.setLayout (new BorderLayout ());
for (int i = 1; i<10;i++){
choice1.add("item "+i);
}
frame.setSize(300, 300);
choice1.setLocation(50, 50);
choice1.setSize(70, 20);
button.setLocation(150, 100);
button.setSize(150, 20);
frame.add(choice1, BorderLayout.SOUTH);
frame.pack();
frame.validate();
frame.setVisible(true);
robot = new Robot();
robot.waitForIdle();
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/10*9, pt.y + choice1.getHeight()/2);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(1000);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Color color = robot.getPixelColor(pt.x + choice1.getWidth()/2,
pt.y + 3 * choice1.getHeight());
//should take a color on the point on the choice's menu
System.out.println("Choice opened. Color got : "+color);
if ( !color.equals(Color.red) ){
passed = "Choice wasn't opened with the mouse";
}
Rectangle oldBounds = choice1.getBounds();
System.out.println("Choice's old bounds : "+oldBounds);
frame.add(button, BorderLayout.NORTH);
// frame.setSize(500, 500);
frame.pack();
robot.waitForIdle();
System.out.println("Choice's new bounds : "+choice1.getBounds());
if (!choice1.getBounds().equals(oldBounds)){
pt = choice1.getLocationOnScreen();
color = robot.getPixelColor(pt.x + choice1.getWidth()/2,
pt.y + 3 * choice1.getHeight());
System.out.println("Choice opened. Color got : "+color);
if (color.equals(Color.red) ){
passed = "Choice wasn't closed when toplevel repacked.";
}
} else {
System.out.println("frame.pack didn't changed Choice's size - dropdown menu should remain the same. Test passed.");
}
if (passed != null){
throw new RuntimeException(passed);
}
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2006, 2024, 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.
*/
/*
* @test
* @bug 6405707
* @summary Choice popup & scrollbar gets Flickering when mouse is pressed & drag on the scrollbar
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ScrollbarFlickers
*/
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Frame;
import java.lang.reflect.InvocationTargetException;
public class ScrollbarFlickers extends Frame {
static final String INSTRUCTIONS = """
Open the choice popup. Select any item in it and
drag it with the mouse above or below the choice.
Keep the choice opened.
Continue dragging the mouse outside of the choice
making content of the popup scroll.
If you see that scrollbar flickers press Fail.
Otherwise press Pass.
""";
public ScrollbarFlickers() {
super("Scrollbar Flickering Test");
Choice ch = new Choice();
setLayout(new BorderLayout());
ch.add("Praveen");
ch.add("Mohan");
ch.add("Rakesh");
ch.add("Menon");
ch.add("Girish");
ch.add("Ramachandran");
ch.add("Elancheran");
ch.add("Subramanian");
ch.add("Raju");
ch.add("Pallath");
ch.add("Mayank");
ch.add("Joshi");
ch.add("Sundar");
ch.add("Srinivas");
ch.add("Mandalika");
ch.add("Suresh");
ch.add("Chandar");
add(ch);
setSize(200, 200);
validate();
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame.builder()
.title("Test Instructions")
.testUI(ScrollbarFlickers::new)
.instructions(INSTRUCTIONS)
.columns(40)
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,146 @@
/*
* Copyright (c) 2005, 2025, 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.
*/
/*
* @test
* @bug 6318746
* @key headful
* @summary REG: File Selection is failing for every second selection made in the FileDlg drop-down, XToolkit
*/
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SelectBetweenPressRelease {
static Frame frame;
static Choice ch;
static Robot r;
static volatile Point loc;
static volatile int selectedIndex;
public static void main(final String[] args) throws Exception {
r = new Robot();
try {
EventQueue.invokeAndWait(() -> init());
r.waitForIdle();
r.delay(1000);
test();
} finally {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
private static void init() {
frame = new Frame("SelectBetweenPressRelease");
ch = new Choice();
ch.add("0");
ch.add("1");
frame.add(ch);
frame.setLayout (new FlowLayout ());
addListener();
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.validate();
}
private static void test() throws Exception {
EventQueue.invokeAndWait(() -> ch.select(0));
EventQueue.invokeAndWait(() -> {
loc = ch.getLocationOnScreen();
});
r.delay(1000);
r.waitForIdle();
r.mouseMove(loc.x+ch.getWidth()/2, loc.y+ch.getHeight()/2);
r.delay(10);
r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
r.delay(100);
// This code leads to the bug
EventQueue.invokeAndWait(() -> ch.select(1));
r.delay(100);
r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
r.delay(1000);
r.waitForIdle();
// 'selected' variable wich stored in the peer still equals 0
// if the bug is reproducible
// so the next ISC to the first item by mouse will be ignored
// try to hit the first item
if (System.getProperty("os.name").startsWith("Mac")) {
r.mouseMove(loc.x + ch.getWidth() / 2, loc.y + ch.getHeight() / 2);
} else {
r.mouseMove(loc.x + ch.getWidth() / 2,
loc.y + ch.getHeight() * 3 / 2);
}
r.delay(10);
r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
r.delay(100);
r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
r.delay(1000);
r.waitForIdle();
EventQueue.invokeAndWait(() -> {
selectedIndex = ch.getSelectedIndex();
});
if (selectedIndex != 0){
throw new RuntimeException("Test failed. ch.getSelectedIndex() = "+selectedIndex);
}
}
// just for logging
private static void addListener(){
frame.addMouseListener(
new MouseAdapter(){
public void mousePressed(MouseEvent me){
System.out.println(me);
}
public void mouseReleased(MouseEvent me){
System.out.println(me);
}
});
ch.addMouseListener(
new MouseAdapter(){
public void mousePressed(MouseEvent me){
System.out.println(me);
}
public void mouseReleased(MouseEvent me){
System.out.println(me);
}
});
}
}

View file

@ -0,0 +1,207 @@
/*
* Copyright (c) 2002, 2024, 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.AWTException;
import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/*
* @test
* @bug 4902933 8197810
* @summary Test that selecting the current item does not send an ItemEvent
* @key headful
* @run main SelectCurrentItemTest
*/
public class SelectCurrentItemTest
extends WindowAdapter
implements ItemListener {
private static Frame frame;
private static Choice choice;
private final Robot robot;
private final CountDownLatch windowOpened = new CountDownLatch(1);
private final CountDownLatch mouseClicked = new CountDownLatch(1);
protected final CountDownLatch itemStateChanged = new CountDownLatch(1);
protected SelectCurrentItemTest() throws AWTException {
robot = new Robot();
robot.setAutoDelay(250);
}
private void createUI() {
frame = new Frame(getClass().getName());
frame.setLayout(new BorderLayout());
choice = new Choice();
for (int i = 0; i < 10; i++) {
choice.add("Choice Item " + i);
}
choice.addItemListener(this);
choice.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked()");
mouseClicked.countDown();
}
});
frame.add(choice, BorderLayout.CENTER);
frame.addWindowListener(this);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
protected final void runTest()
throws InterruptedException, InvocationTargetException {
try {
doTest();
} finally {
EventQueue.invokeAndWait(this::dispose);
}
}
private void doTest()
throws InterruptedException, InvocationTargetException {
EventQueue.invokeAndWait(this::createUI);
if (!windowOpened.await(2, TimeUnit.SECONDS)) {
throw new RuntimeException("Frame is not open in time");
}
robot.waitForIdle();
final int initialIndex = getSelectedIndex();
final Rectangle choiceRect = getChoiceRect();
// Open the choice popup
robot.mouseMove(choiceRect.x + choiceRect.width - 10,
choiceRect.y + choiceRect.height / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
if (!mouseClicked.await(500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Mouse is not clicked in time");
}
robot.waitForIdle();
// Click an item in the choice popup
final Point pt = getClickLocation(choiceRect);
robot.mouseMove(pt.x, pt.y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
checkItemStateChanged();
final int currentIndex = getSelectedIndex();
System.out.println("initialIndex = " + initialIndex);
System.out.println("currentIndex = " + currentIndex);
checkSelectedIndex(initialIndex, currentIndex);
}
protected void checkItemStateChanged() throws InterruptedException {
if (itemStateChanged.await(500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("ItemEvent is received but unexpected");
}
}
protected void checkSelectedIndex(final int initialIndex,
final int currentIndex) {
if (initialIndex != currentIndex) {
throw new RuntimeException("Selected index in Choice should not change");
}
}
/**
* {@return the location for clicking choice popup to select an item}
* @param choiceRect the bounds of the Choice component
*/
protected Point getClickLocation(final Rectangle choiceRect) {
// Click on the first item in the popup, it's the selected item
return new Point(choiceRect.x + choiceRect.width / 2,
choiceRect.y + choiceRect.height + 3);
}
private int getSelectedIndex()
throws InterruptedException, InvocationTargetException {
AtomicInteger index = new AtomicInteger();
EventQueue.invokeAndWait(() -> index.set(choice.getSelectedIndex()));
return index.get();
}
private Rectangle getChoiceRect()
throws InterruptedException, InvocationTargetException {
AtomicReference<Rectangle> rect = new AtomicReference<>();
EventQueue.invokeAndWait(
() -> rect.set(new Rectangle(choice.getLocationOnScreen(),
choice.getSize())));
return rect.get();
}
public static void main(String... args) throws Exception {
new SelectCurrentItemTest().runTest();
}
private void dispose() {
if (frame != null) {
frame.dispose();
}
}
@Override
public final void itemStateChanged(ItemEvent e) {
System.out.println("itemStateChanged: " + e);
itemStateChanged.countDown();
}
@Override
public final void windowOpened(WindowEvent e) {
System.out.println("windowActivated()");
windowOpened.countDown();
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2019, 2024, 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.AWTException;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.concurrent.TimeUnit;
/*
* @test
* @bug 8215921
* @summary Test that selecting a different item does send an ItemEvent
* @key headful
* @run main SelectNewItemTest
*/
public final class SelectNewItemTest
extends SelectCurrentItemTest {
private SelectNewItemTest() throws AWTException {
super();
}
@Override
protected void checkItemStateChanged() throws InterruptedException {
if (!itemStateChanged.await(500, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("ItemEvent is not received");
}
}
@Override
protected void checkSelectedIndex(final int initialIndex,
final int currentIndex) {
if (initialIndex == currentIndex) {
throw new RuntimeException("Selected index in Choice should've changed");
}
}
@Override
protected Point getClickLocation(final Rectangle choiceRect) {
// Click a different item the popup, not the first one
return new Point(choiceRect.x + choiceRect.width / 2,
choiceRect.y + choiceRect.height * 3);
}
public static void main(String... args) throws Exception {
new SelectNewItemTest().runTest();
}
}

View file

@ -0,0 +1,65 @@
/*
* Copyright (c) 2003, 2020, 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.Choice;
import java.awt.Frame;
import java.awt.Graphics;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @test
* @bug 4790927 4783342 4930678 8225126
* @key headful
* @summary Tests Choice doesn't flash
*/
public final class SetBoundsPaintTest {
public static void main(String[] args) throws Exception {
CountDownLatch go = new CountDownLatch(10);
Choice choice = new Choice();
choice.addItem("first");
choice.addItem("second");
Frame frame = new Frame() {
@Override
public void paint(Graphics g) {
g.fillRect(0, 0, 200, 200);
choice.setBounds(50, 50, 180, 30);
go.countDown();
}
};
try {
frame.setLayout(null);
frame.add(choice);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
if (go.await(5, TimeUnit.SECONDS)) {
throw new RuntimeException("recursive setBounds paint");
}
} finally {
frame.dispose();
}
}
}

View file

@ -0,0 +1,91 @@
/*
* Copyright (c) 1999, 2024, 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.BorderLayout;
import java.awt.Choice;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
/*
* @test
* @bug 4293346
* @summary Checks that Choice does update its dimensions on font change
* @requires (os.family == "windows")
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual SetFontTest
*/
public class SetFontTest {
private static final String INSTRUCTIONS = """
Choice component used to not update its dimension on font change.
Select one of fonts on the choice pull down list.
Pull down the list after the font change; if items in the list are
shown correctly the test is passed, otherwise it failed.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("SetFontTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(SetFontTest::createAndShowUI)
.build()
.awaitAndCheck();
}
private static Frame createAndShowUI() {
Frame frame = new Frame("SetFontTest");
Choice choice = new Choice();
frame.setBounds(100, 400, 400, 100);
choice.addItem("dummy");
choice.addItem("Set LARGE Font");
choice.addItem("Set small Font");
choice.addItem("addNewItem");
choice.addItem("deleteItem");
choice.addItemListener(e -> {
if (e.getItem().toString().equals("addNewItem")) {
choice.addItem("very very very very long item");
frame.validate();
} else if (e.getItem().toString().equals("deleteItem")) {
if (choice.getItemCount() > 4) {
choice.remove(4);
frame.validate();
}
} else if (e.getItem().toString().equals("Set LARGE Font")) {
choice.setFont(new Font("Dialog", Font.PLAIN, 24));
frame.validate();
} else if (e.getItem().toString().equals("Set small Font")) {
choice.setFont(new Font("Dialog", Font.PLAIN, 10));
frame.validate();
}
});
Panel panel = new Panel();
panel.add(choice);
frame.add(panel, BorderLayout.CENTER);
return frame;
}
}

View file

@ -0,0 +1,232 @@
/*
* Copyright (c) 2006, 2018, 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.
*/
/*
@test
@key headful
@bug 6390103
@summary Non-Focusable choice throws exception when selecting an item, Win32
@author andrei.dmitriev area=awt.choice
@run main UnfocusableCB_ERR
*/
import java.awt.*;
import java.awt.event.*;
public class UnfocusableCB_ERR
{
static final int delay = 100;
static Frame frame = new Frame("Test Frame");
static Choice choice1 = new Choice();
static Button button = new Button("Test");
static Robot robot;
static Point pt;
static String failed = "";
private static void init()
{
EventQueue.invokeLater(new Runnable() {
public void run() {
Thread.currentThread().setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler(){
public void uncaughtException(Thread t, Throwable exc){
failed = exc.toString();
}
});
}
});
frame.setLayout (new FlowLayout ());
for (int i = 1; i<10;i++){
choice1.add("item "+i);
}
frame.add(button);
frame.add(choice1);
choice1.setFocusable(false);
frame.pack();
frame.setVisible(true);
frame.validate();
try {
robot = new Robot();
robot.setAutoDelay(50);
robot.waitForIdle();
testSpacePress();
} catch (Throwable e) {
UnfocusableCB_ERR.fail("Test failed. Exception thrown: "+e);
}
if (failed.equals("")){
UnfocusableCB_ERR.pass();
} else {
UnfocusableCB_ERR.fail("Test failed:");
}
}//End init()
public static void testSpacePress(){
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + choice1.getHeight()/2);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle();
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.waitForIdle();
//position mouse cursor over dropdown menu
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y + 2 * choice1.getHeight());
robot.waitForIdle();
//move mouse outside Choice
robot.mouseMove(pt.x + choice1.getWidth()/2, pt.y - choice1.getHeight());
robot.waitForIdle();
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
robot.waitForIdle();
}
/*****************************************************
* Standard Test Machinery Section
* DO NOT modify anything in this section -- it's a
* standard chunk of code which has all of the
* synchronisation necessary for the test harness.
* By keeping it the same in all tests, it is easier
* to read and understand someone else's test, as
* well as insuring that all tests behave correctly
* with the test harness.
* There is a section following this for test-
* classes
******************************************************/
private static boolean theTestPassed = false;
private static boolean testGeneratedInterrupt = false;
private static String failureMessage = "";
private static Thread mainThread = null;
private static int sleepTime = 300000;
// Not sure about what happens if multiple of this test are
// instantiated in the same VM. Being static (and using
// static vars), it aint gonna work. Not worrying about
// it for now.
public static void main( String args[] ) throws InterruptedException
{
mainThread = Thread.currentThread();
try
{
init();
}
catch( TestPassedException e )
{
//The test passed, so just return from main and harness will
// interepret this return as a pass
return;
}
//At this point, neither test pass nor test fail has been
// called -- either would have thrown an exception and ended the
// test, so we know we have multiple threads.
//Test involves other threads, so sleep and wait for them to
// called pass() or fail()
try
{
Thread.sleep( sleepTime );
//Timed out, so fail the test
throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" );
}
catch (InterruptedException e)
{
//The test harness may have interrupted the test. If so, rethrow the exception
// so that the harness gets it and deals with it.
if( ! testGeneratedInterrupt ) throw e;
//reset flag in case hit this code more than once for some reason (just safety)
testGeneratedInterrupt = false;
if ( theTestPassed == false )
{
throw new RuntimeException( failureMessage );
}
}
}//main
public static synchronized void setTimeoutTo( int seconds )
{
sleepTime = seconds * 1000;
}
public static synchronized void pass()
{
System.out.println( "The test passed." );
System.out.println( "The test is over, hit Ctl-C to stop Java VM" );
//first check if this is executing in main thread
if ( mainThread == Thread.currentThread() )
{
//Still in the main thread, so set the flag just for kicks,
// and throw a test passed exception which will be caught
// and end the test.
theTestPassed = true;
throw new TestPassedException();
}
theTestPassed = true;
testGeneratedInterrupt = true;
mainThread.interrupt();
}//pass()
public static synchronized void fail()
{
//test writer didn't specify why test failed, so give generic
fail( "it just plain failed! :-)" );
}
public static synchronized void fail( String whyFailed )
{
System.out.println( "The test failed: " + whyFailed );
System.out.println( "The test is over, hit Ctl-C to stop Java VM" );
//check if this called from main thread
if ( mainThread == Thread.currentThread() )
{
//If main thread, fail now 'cause not sleeping
throw new RuntimeException( whyFailed );
}
theTestPassed = false;
testGeneratedInterrupt = true;
failureMessage = whyFailed;
mainThread.interrupt();
}//fail()
}// class UnfocusableCB_ERR
//This exception is used to exit from any level of call nesting
// when it's determined that the test has passed, and immediately
// end the test.
class TestPassedException extends RuntimeException
{
}

View file

@ -0,0 +1,147 @@
/*
* Copyright (c) 2007, 2020, 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.
*/
/*
@test
@key headful
@bug 6566434 8039467
@library ../../regtesthelpers
@build Util Sysout AbstractTest
@summary Choice in unfocusable window responds to keyboard
@author Andrei Dmitriev: area=awt-choice
@run main UnfocusableToplevel
*/
/**
* UnfocusableToplevel.java
*
* summary:
*/
import java.awt.AWTEvent;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Robot;
import java.awt.Window;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import test.java.awt.regtesthelpers.AbstractTest;
import test.java.awt.regtesthelpers.Util;
public class UnfocusableToplevel {
final static Robot robot = Util.createRobot();
final static int REASONABLE_PATH_TIME = 5000;
public static void main(String []s)
{
Frame f = new Frame();
Window w = new Window(f);
final Choice ch = new Choice();
ch.add("item 1");
ch.add("item 2");
ch.add("item 3");
ch.add("item 4");
ch.add("item 5");
w.add(ch);
w.setLayout(new FlowLayout());
w.setSize(200, 200);
// Note that Window w is non focusable. Key press events will not be
// consumed by w, but by any previously focused window & this can
// disturb the environment. So creating tempFrameToHoldFocus frame,
// to consume key press events.
Frame tempFrameToHoldFocus = new Frame();
tempFrameToHoldFocus.setSize(300, 300);
tempFrameToHoldFocus.setLocationRelativeTo(null);
tempFrameToHoldFocus.setVisible(true);
Util.waitForIdle(robot);
tempFrameToHoldFocus.requestFocus();
Util.clickOnComp(tempFrameToHoldFocus, robot);
Util.waitForIdle(robot);
ch.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e){
traceEvent("keytyped", e);
}
public void keyPressed(KeyEvent e){
traceEvent("keypress", e);
}
public void keyReleased(KeyEvent e){
traceEvent("keyrelease", e);
}
});
ch.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
traceEvent("stateChanged", ie);
}
});
w.setLocationRelativeTo(null);
w.setVisible(true);
Util.waitForIdle(robot);
Util.clickOnComp(ch, robot);
Util.waitForIdle(robot);
// will not test if the dropdown become opened as there is no reliable
// technique to accomplish that rather then checking color of dropdown
// Will suppose that the dropdown appears
testKeys();
Util.waitForIdle(robot);
tempFrameToHoldFocus.dispose();
w.dispose();
f.dispose();
}
private static void testKeys(){
typeKey(KeyEvent.VK_UP);
typeKey(KeyEvent.VK_DOWN);
typeKey(KeyEvent.VK_K);
typeKey(KeyEvent.VK_PAGE_UP);
typeKey(KeyEvent.VK_PAGE_DOWN);
}
private static void typeKey(int keyChar){
try {
robot.keyPress(keyChar);
robot.delay(5);
} finally {
robot.keyRelease(keyChar);
}
robot.delay(100);
}
private static void traceEvent(String message, AWTEvent e){
AbstractTest.fail(message + " " + e.toString());
}
}

View file

@ -0,0 +1,156 @@
/*
* Copyright (c) 2005, 2024, 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.Choice;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
/*
* @test
* @bug 6253211
* @summary PIT: MouseWheel events not triggered for Choice drop down in XAWT
* @requires (os.family == "linux")
* @key headful
* @run main WheelEventsConsumed
*/
public class WheelEventsConsumed extends Frame implements MouseWheelListener
{
Robot robot;
Choice choice1 = new Choice();
Point pt;
final static int delay = 100;
boolean mouseWheeled = false;
final static int OUTSIDE_CHOICE = 1;
final static int INSIDE_LIST_OF_CHOICE = 2;
final static int INSIDE_CHOICE_COMPONENT = 3;
static String toolkit;
private static volatile WheelEventsConsumed frame = null;
public static void main(String[] args) throws Exception {
toolkit = Toolkit.getDefaultToolkit().getClass().getName();
try {
EventQueue.invokeAndWait(() -> {
frame = new WheelEventsConsumed();
frame.initAndShow();
});
frame.test();
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
public void mouseWheelMoved(MouseWheelEvent me) {
mouseWheeled = true;
System.out.println(me);
}
public void initAndShow() {
setTitle("WheelEventsConsumed test");
for (int i = 1; i < 10; i++) {
choice1.add("item-0" + i);
}
choice1.addMouseWheelListener(this);
add(choice1);
setLayout(new FlowLayout());
setSize(200, 200);
setLocationRelativeTo(null);
setVisible(true);
validate();
}
public void test() {
try {
robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.setAutoDelay(50);
robot.waitForIdle();
robot.delay(delay * 5);
testMouseWheel(1, OUTSIDE_CHOICE);
robot.delay(delay);
testMouseWheel(-1, INSIDE_LIST_OF_CHOICE);
robot.delay(delay);
testMouseWheel(1, INSIDE_CHOICE_COMPONENT);
robot.delay(delay);
} catch (Throwable e) {
throw new RuntimeException("Test failed. Exception thrown: " + e);
}
}
public void testMouseWheel(int amt, int mousePosition) {
pt = choice1.getLocationOnScreen();
robot.mouseMove(pt.x + choice1.getWidth() / 2, pt.y + choice1.getHeight() / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(50);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(50);
switch (mousePosition) {
case OUTSIDE_CHOICE:
robot.mouseMove(pt.x + choice1.getWidth() * 3 / 2, pt.y + choice1.getHeight() / 2);
break;
case INSIDE_LIST_OF_CHOICE:
robot.mouseMove(pt.x + choice1.getWidth() / 2, pt.y + choice1.getHeight() * 4);
break;
case INSIDE_CHOICE_COMPONENT:
robot.mouseMove(pt.x + choice1.getWidth() / 2, pt.y + choice1.getHeight() / 2);
break;
}
robot.delay(delay);
for (int i = 0; i < 10; i++) {
robot.mouseWheel(amt);
robot.delay(delay);
}
if (!mouseWheeled) {
if (toolkit.equals("sun.awt.windows.WToolkit") && mousePosition == OUTSIDE_CHOICE) {
System.out.println("Passed. Separate case on Win32. Choice generated MouseWheel events" + mousePosition);
} else {
throw new RuntimeException("Test failed. Choice should generate MOUSE_WHEEL events." + mousePosition);
}
} else {
System.out.println("Passed. Choice generated MouseWheel events" + mousePosition);
}
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.delay(10);
robot.keyRelease(KeyEvent.VK_ESCAPE);
robot.delay(200);
mouseWheeled = false;
}
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 2002, 2025, 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.
*/
/*
* @test
* @bug 4177171 4180145 4180148
* @summary Can't copy to clipboard
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ClipRWTest
*/
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
public class ClipRWTest {
private static final String INSTRUCTIONS = """
1. Type some text in the text field and press Copy Text.
2. Switch to a _native_ application (e.g. Notepad) and paste the text in
3. Verify the text that is pasted matches what you typed in the Java window
4. In the native app, type some new text and copy it
5. Switch back to the test frame and press Paste Text
6. Verify the text that is pasted matches what you typed in the native app
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("ClipRWTest Instructions")
.instructions(INSTRUCTIONS)
.columns(40)
.testUI(ClipFrame::new)
.build()
.awaitAndCheck();
}
private static class ClipFrame extends Frame {
TextField field =new TextField(50);
Button copyText = new Button("Copy Text");
Button pasteText = new Button("Paste Text");
Clipboard clipboard;
public ClipFrame() {
super("ClipRWTest 4177171");
setLayout(new FlowLayout());
clipboard = getToolkit().getSystemClipboard();
add(field);
add(copyText);
add(pasteText);
copyText.addActionListener(
ev -> {
String text = field.getText();
try {
clipboard.setContents(new StringSelection(text), null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
);
pasteText.addActionListener(
ev -> {
String text = "";
try {
text = (String) clipboard.getContents(null)
.getTransferData(DataFlavor.stringFlavor);
} catch (Exception ex) {
ex.printStackTrace();
}
field.setText(text);
}
);
pack();
}
}
}

View file

@ -0,0 +1,156 @@
/*
* Copyright (c) 2000, 2025, 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.
*/
/*
* @test
* @bug 4274061
* @summary Tests that Transferable.getTransferData() and
* SelectionOwner.lostOwnership is not called on Toolkit thread.
* @key headful
* @library /test/lib
* @run main ClipboardSecurity
*/
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
public class ClipboardSecurity {
static Clipboard clip = null;
public static final CountDownLatch latch = new CountDownLatch(1);
public static volatile boolean hasError = false;
public static void main(String[] args) throws Exception {
if (args.length == 0) {
ClipboardSecurity clipboardSecurity = new ClipboardSecurity();
clipboardSecurity.start();
return;
}
try {
clip = Toolkit.getDefaultToolkit().getSystemClipboard();
if ( clip == null ) {
throw (new RuntimeException("Clipboard is null"));
}
Transferable data = clip.getContents(null);
if ( data == null ) {
throw (new RuntimeException("Data is null"));
}
System.out.println("Clipboard contents: " + data);
// First check - getTransferData
try {
String contData =
(String) data.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException exc) {
throw(new RuntimeException("Couldn't get transfer data - "
+ exc.getMessage()));
}
// Second check - lostOwnership
MyClass clipData = new MyClass("clipbard test data");
clip.setContents(clipData, clipData);
System.out.println("exit 0");
System.exit(0);
} catch (RuntimeException exc) {
System.err.println(exc.getMessage());
System.out.println("exit 2");
System.exit(2);
}
}
public void start() throws Exception {
clip = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clip == null) {
throw (new RuntimeException("Clipboard is null"));
}
MyClass clipData = new MyClass("clipboard test data");
clip.setContents(clipData, clipData);
ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
ClipboardSecurity.class.getName(),
"child"
);
Process process = ProcessTools.startProcess("Child", pb);
OutputAnalyzer outputAnalyzer = new OutputAnalyzer(process);
if (!process.waitFor(15, TimeUnit.SECONDS)) {
process.destroyForcibly();
throw new TimeoutException("Timed out waiting for Child");
}
System.out.println("WAIT COMPLETE");
outputAnalyzer.shouldHaveExitValue(0);
if (!latch.await(10, TimeUnit.SECONDS)) {
throw new RuntimeException("timed out");
}
if (hasError) {
throw new RuntimeException("Detected call on Toolkit thread");
}
System.out.println("Passed.");
}
}
class MyClass extends StringSelection implements ClipboardOwner {
MyClass(String title) {
super(title);
}
private void checkIsCorrectThread(String reason) {
System.out.println("Checking " + reason + " for thread "
+ Thread.currentThread().getName());
String name = Thread.currentThread().getName();
if (name.equals("AWT-Windows") || name.equals("AWT-Motif")) {
ClipboardSecurity.hasError = true;
System.err.println(reason + " is called on Toolkit thread!");
}
}
public void lostOwnership(Clipboard clip, Transferable cont) {
checkIsCorrectThread("lostOwnership");
ClipboardSecurity.latch.countDown();
System.out.println("lost ownership on "
+ Thread.currentThread().getName() + " thread");
}
public Object getTransferData(DataFlavor flav)
throws UnsupportedFlavorException, IOException {
System.out.println("getTransferData on "
+ Thread.currentThread().getName() + " thread");
checkIsCorrectThread("getTransferData");
return super.getTransferData(flav);
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2025, 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.
*/
/*
@test
@bug 8332271
@summary tests that concurrent access to the clipboard does not crash the JVM
@key headful
@requires (os.family == "windows")
@run main ConcurrentClipboardAccessTest
*/
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
public class ConcurrentClipboardAccessTest {
public static void main(String[] args) {
Thread clipboardLoader1 = new Thread(new ClipboardLoader());
clipboardLoader1.setDaemon(true);
clipboardLoader1.start();
Thread clipboardLoader2 = new Thread(new ClipboardLoader());
clipboardLoader2.setDaemon(true);
clipboardLoader2.start();
long start = System.currentTimeMillis();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
long now = System.currentTimeMillis();
if ((now - start) > (10L * 1000L)) {
break;
}
}
// Test is considered successful if the concurrent repeated reading
// from clipboard succeeds for the allotted time and the JVM does not
// crash.
System.out.println("Shutdown normally");
}
public static class ClipboardLoader implements Runnable {
@Override
public void run() {
final Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
while (true) {
try {
if (systemClipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
systemClipboard.getData(DataFlavor.stringFlavor);
}
} catch (Exception ignored) {
}
}
}
}
}

View file

@ -0,0 +1,166 @@
/*
* Copyright (c) 2023, 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.Canvas;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.concurrent.CountDownLatch;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/*
* @test
* @key headful
* @bug 6176679
* @summary Tests that an application doesn't freeze when copying an animated
* gif image to the system clipboard. We run the test two times. First with
* image displayed on screen and second with it not displayed.
* @run main CopyAnimatedGIFTest
*/
public class CopyAnimatedGIFTest {
private static final long TIMEOUT = 10000;
private final CountDownLatch latch = new CountDownLatch(1);
private final Image img = Toolkit.getDefaultToolkit().createImage(imageData);
private static final byte[] imageData = {
(byte) 0x47, (byte) 0x49, (byte) 0x46, (byte) 0x38, (byte) 0x39,
(byte) 0x61, (byte) 0x04, (byte) 0x00, (byte) 0x04, (byte) 0x00,
(byte) 0xa1, (byte) 0x03, (byte) 0x00, (byte) 0xff, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0x00, (byte) 0xff,
(byte) 0xff, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff,
(byte) 0x21, (byte) 0xff, (byte) 0x0b, (byte) 0x4e, (byte) 0x45,
(byte) 0x54, (byte) 0x53, (byte) 0x43, (byte) 0x41, (byte) 0x50,
(byte) 0x45, (byte) 0x32, (byte) 0x2e, (byte) 0x30, (byte) 0x03,
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x21,
(byte) 0xf9, (byte) 0x04, (byte) 0x00, (byte) 0x0a, (byte) 0x00,
(byte) 0xff, (byte) 0x00, (byte) 0x2c, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x04,
(byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x04, (byte) 0x84,
(byte) 0x8f, (byte) 0x09, (byte) 0x05, (byte) 0x00, (byte) 0x21,
(byte) 0xf9, (byte) 0x04, (byte) 0x01, (byte) 0x0a, (byte) 0x00,
(byte) 0x03, (byte) 0x00, (byte) 0x2c, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x04,
(byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x04, (byte) 0x94,
(byte) 0x8f, (byte) 0x29, (byte) 0x05, (byte) 0x00, (byte) 0x21,
(byte) 0xf9, (byte) 0x04, (byte) 0x01, (byte) 0x0a, (byte) 0x00,
(byte) 0x03, (byte) 0x00, (byte) 0x2c, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x04,
(byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x04, (byte) 0x8c,
(byte) 0x8f, (byte) 0x19, (byte) 0x05, (byte) 0x00, (byte) 0x3b
};
private void createGUI() {
ImageCanvas canvas = new ImageCanvas(img);
canvas.setBackground(Color.BLUE);
Frame frame = new Frame("CopyAnimatedGIFTest");
frame.setSize(400, 200);
frame.add(canvas);
frame.setVisible(true);
}
private void copyImage() {
Clipboard sys = Toolkit.getDefaultToolkit().getSystemClipboard();
sys.setContents(new MyTransferable(img), null);
}
private void runTest(boolean isImageDisplayed) throws Exception {
if (isImageDisplayed) {
Robot robot = new Robot();
EventQueue.invokeAndWait(this::createGUI);
robot.waitForIdle();
robot.delay(1000);
}
EventQueue.invokeLater(() -> {
copyImage();
latch.countDown();
});
if (!latch.await(TIMEOUT, MILLISECONDS)) {
String str = isImageDisplayed ? " displayed":" not displayed";
throw new RuntimeException("Image copying taking too long for image"
+ str + " case");
}
}
public static void main(String[] args) throws Exception {
// run test with Image showing up on screen
new CopyAnimatedGIFTest().runTest(true);
// run test without Image showing up
new CopyAnimatedGIFTest().runTest(false);
}
private static class ImageCanvas extends Canvas {
private final Image img;
public ImageCanvas(Image img) {
this.img = img;
}
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
private static class MyTransferable implements Transferable {
private final Image img;
private final DataFlavor[] flavors = {DataFlavor.imageFlavor};
public MyTransferable(Image img) {
this.img = img;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavors[0].equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return img;
}
}
}

View file

@ -0,0 +1,252 @@
/*
* Copyright (c) 2000, 2023, 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.
*/
/*
@test
@bug 4085183 8000630
@summary tests that clipboard contents is retrieved even if the app didn't
receive native events for a long time.
@requires (os.family != "mac")
@key headful
@run main DelayedQueryTest
*/
import java.awt.AWTException;
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.InputEvent;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
public class DelayedQueryTest implements ClipboardOwner, Runnable {
int returnCode = Child.CHILD_RETURN_CODE_NOT_READY;
Process childProcess = null;
Frame frame;
public static void main(String[] args)
throws InterruptedException, InvocationTargetException {
String osName = System.getProperty("os.name");
if (osName.toLowerCase().contains("os x")) {
System.out.println("This test is not for MacOS, considered passed.");
return;
}
DelayedQueryTest delayedQueryTest = new DelayedQueryTest();
EventQueue.invokeAndWait(delayedQueryTest::initAndShowGui);
try {
delayedQueryTest.start();
} finally {
EventQueue.invokeAndWait(() -> delayedQueryTest.frame.dispose());
}
}
public void initAndShowGui(){
frame = new Frame("DelayedQueryTest");
frame.add(new Panel());
frame.setBounds(200,200, 200, 200);
frame.setVisible(true);
}
public void start() {
try {
Robot robot = new Robot();
// Some mouse activity to update the Xt time stamp at
// the parent process.
robot.delay(1000);
robot.waitForIdle();
Point p = frame.getLocationOnScreen();
robot.mouseMove(p.x + 100, p.y + 100);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} catch (AWTException e) {
e.printStackTrace();
throw new RuntimeException("The test failed.");
}
Child.sysClipboard.setContents(Child.transferable, this);
String javaPath = System.getProperty("java.home", "");
String[] command = {
javaPath + File.separator + "bin" + File.separator + "java",
"-cp", System.getProperty("test.classes", "."),
"Child"
};
try {
Process process = Runtime.getRuntime().exec(command);
childProcess = process;
returnCode = process.waitFor();
childProcess = null;
InputStream errorStream = process.getErrorStream();
int count = errorStream.available();
if (count > 0) {
byte[] b = new byte[count];
errorStream.read(b);
System.err.println("========= Child VM System.err ========");
System.err.print(new String(b));
System.err.println("======================================");
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException("The test failed.");
}
if (returnCode != Child.CHILD_RETURN_CODE_OK) {
System.err.println("Child VM: returned " + returnCode);
throw new RuntimeException("The test failed.");
}
} // start()
public void lostOwnership(Clipboard clipboard,
Transferable contents) {
// At this moment the child process has definitely started.
// So we can try to retrieve the clipboard contents set
// by the child process.
new Thread(this).start();
}
public void run() {
// We are going to check if it is possible to retrieve the data
// after the child process has set the clipboard contents twice,
// since after the first setting the retrieval is always successful.
// So we wait to let the child process set the clipboard contents
// twice.
try {
Thread.sleep(Child.CHILD_SELECTION_CHANGE_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
String s = (String)Child.sysClipboard
.getContents(null)
.getTransferData(DataFlavor.stringFlavor);
if (!"String".equals(s)) {
System.err.println("Data retrieved: " + s);
throw new RuntimeException("Retrieved data is incorrect.");
}
} catch (Exception e) {
e.printStackTrace();
if (childProcess != null) {
childProcess.destroy();
childProcess = null;
}
throw new RuntimeException("Failed to retrieve the data.");
}
Child.sysClipboard.setContents(Child.transferable, null);
}
}
class Child {
static final Clipboard sysClipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
static final Transferable transferable = new StringSelection("String");
/*
* Timeouts.
*/
static final int FRAME_ACTIVATION_TIMEOUT = 1000;
static final int PARENT_TIME_STAMP_TIMEOUT = 1000;
static final int CHILD_SELECTION_CHANGE_TIMEOUT =
FRAME_ACTIVATION_TIMEOUT + PARENT_TIME_STAMP_TIMEOUT + 5000;
static final int PARENT_RETRIEVE_DATA_TIMEOUT = 10000;
/*
* Child process return codes.
*/
static final int CHILD_RETURN_CODE_NOT_READY = -1;
static final int CHILD_RETURN_CODE_OK = 0;
static final int CHILD_RETURN_CODE_UNEXPECTED_EXCEPTION = 1;
static final int CHILD_RETURN_CODE_OTHER_FAILURE = 2;
static Button button;
static void initAndShowGui() {
final Frame frame = new Frame();
button = new Button("button");
frame.add(button);
frame.pack();
frame.setLocation(100, 100);
frame.setVisible(true);
}
public static void main(String[] args) {
sysClipboard.setContents(
new StringSelection("First String"), null);
// Some mouse activity to update the Xt time stamp at
// the child process.
try {
EventQueue.invokeAndWait(Child::initAndShowGui);
try {
Thread.sleep(FRAME_ACTIVATION_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(CHILD_RETURN_CODE_UNEXPECTED_EXCEPTION);
}
Robot robot = new Robot();
robot.waitForIdle();
Point p = button.getLocationOnScreen();
robot.mouseMove(p.x + 10, p.y + 10);
// Wait to let the Xt time stamp become out-of-date.
try {
Thread.sleep(PARENT_TIME_STAMP_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(CHILD_RETURN_CODE_UNEXPECTED_EXCEPTION);
}
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} catch (Exception e) {
e.printStackTrace();
System.exit(CHILD_RETURN_CODE_UNEXPECTED_EXCEPTION);
}
sysClipboard.setContents(transferable, new ClipboardOwner() {
public void lostOwnership(Clipboard clipboard,
Transferable contents) {
System.exit(CHILD_RETURN_CODE_OK);
}
});
// Wait to let the parent process retrieve the data.
try {
Thread.sleep(PARENT_RETRIEVE_DATA_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Parent failed to set clipboard contents, so we signal test failure
System.exit(CHILD_RETURN_CODE_OTHER_FAILURE);
}
}

View file

@ -0,0 +1,291 @@
/*
* Copyright (c) 2003, 2023, 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.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
public class Common {}
class FlavorListenerImpl implements FlavorListener {
public boolean notified1, notified2;
private int count;
public void flavorsChanged(FlavorEvent evt) {
switch (count) {
case 0:
notified1 = true;
break;
case 1:
notified2 = true;
break;
}
count++;
System.err.println("listener's " + this +
" flavorChanged() called " + count + " time");
}
public String toString() {
return "notified1=" + notified1 + " notified2=" + notified2 +
" count=" + count;
}
};
class Util {
public static void setClipboardContents(Clipboard cb,
Transferable contents,
ClipboardOwner owner) {
while (true) {
try {
cb.setContents(contents, owner);
return;
} catch (IllegalStateException ise) {
ise.printStackTrace();
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
public static Image createImage() {
int w = 100;
int h = 100;
int[] pix = new int[w * h];
int index = 0;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int red = 127;
int green = 127;
int blue = y > h / 2 ? 127 : 0;
int alpha = 255;
if (x < w / 4 && y < h / 4) {
alpha = 0;
red = 0;
}
pix[index++] = (alpha << 24) | (red << 16) | (green << 8) | blue;
}
}
return Toolkit
.getDefaultToolkit().
createImage(new java.awt.image.MemoryImageSource(
w, h, pix, 0, w
));
}
}
class TransferableUnion implements Transferable {
private static final DataFlavor[] ZERO_LENGTH_ARRAY = new DataFlavor[0];
private final Transferable TRANSF1, TRANSF2;
private final DataFlavor[] FLAVORS;
public TransferableUnion(Transferable t1, Transferable t2) {
if (t1 == null) {
throw new NullPointerException("t1");
}
if (t2 == null) {
throw new NullPointerException("t2");
}
this.TRANSF1 = t1;
this.TRANSF2 = t2;
java.util.Set<DataFlavor> flavorSet = new java.util.HashSet<>();
flavorSet.addAll(java.util.Arrays.asList(t1.getTransferDataFlavors()));
flavorSet.addAll(java.util.Arrays.asList(t2.getTransferDataFlavors()));
FLAVORS = flavorSet.toArray(ZERO_LENGTH_ARRAY);
}
/**
* Returns an array of flavors in which this <code>Transferable</code>
* can provide the data.
*/
public DataFlavor[] getTransferDataFlavors() {
return FLAVORS.clone();
}
/**
* Returns whether the requested flavor is supported by this
* <code>Transferable</code>.
*
* @param flavor the requested flavor for the data
* @throws NullPointerException if flavor is <code>null</code>
*/
public boolean isDataFlavorSupported(DataFlavor flavor) {
if (flavor == null) {
throw new NullPointerException("flavor");
}
return TRANSF1.isDataFlavorSupported(flavor)
|| TRANSF2.isDataFlavorSupported(flavor);
}
/**
* Returns the <code>Transferable</code>'s data in the requested
* <code>DataFlavor</code> if possible.
*
* @param flavor the requested flavor for the data
* @return the data in the requested flavor
* @throws UnsupportedFlavorException if the requested data flavor is
* not supported by this Transferable
* @throws IOException if an <code>IOException</code> occurs while
* retrieving the data.
* @throws NullPointerException if flavor is <code>null</code>
*/
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, java.io.IOException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
java.io.IOException ioexc = null;
if (TRANSF1.isDataFlavorSupported(flavor)) {
try {
return TRANSF1.getTransferData(flavor);
} catch (java.io.IOException exc) {
ioexc = exc;
}
}
if (TRANSF2.isDataFlavorSupported(flavor)) {
return TRANSF2.getTransferData(flavor);
}
if (ioexc != null) {
throw ioexc;
}
// unreachable
return null;
}
}
/**
* A <code>Transferable</code> that implements the capability required
* to transfer an <code>Image</code>.
*
* This <code>Transferable</code> properly supports
* <code>DataFlavor.imageFlavor</code>
* and all equivalent flavors.
* No other <code>DataFlavor</code>s are supported.
*
* @see java.awt.datatransfer.DataFlavor.imageFlavor
*/
class ImageSelection implements Transferable {
private static final DataFlavor[] flavors = { DataFlavor.imageFlavor };
private Image data;
/**
* Creates a <code>Transferable</code> capable of transferring
* the specified <code>Image</code>.
*/
public ImageSelection(Image data) {
this.data = data;
}
/**
* Returns an array of flavors in which this <code>Transferable</code>
* can provide the data. <code>DataFlavor.stringFlavor</code>
* is supported.
*
* @return an array of length one, whose element is <code>DataFlavor.
* imageFlavor</code>
*/
public DataFlavor[] getTransferDataFlavors() {
return flavors.clone();
}
/**
* Returns whether the requested flavor is supported by this
* <code>Transferable</code>.
*
* @param flavor the requested flavor for the data
* @return true if <code>flavor</code> is equal to
* <code>DataFlavor.imageFlavor</code>;
* false otherwise
* @throws NullPointerException if flavor is <code>null</code>
*/
public boolean isDataFlavorSupported(DataFlavor flavor) {
for (int i = 0; i < flavors.length; i++) {
if (flavor.equals(flavors[i])) {
return true;
}
}
return false;
}
/**
* Returns the <code>Transferable</code>'s data in the requested
* <code>DataFlavor</code> if possible. If the desired flavor is
* <code>DataFlavor.imageFlavor</code>, or an equivalent flavor,
* the <code>Image</code> representing the selection is
* returned.
*
* @param flavor the requested flavor for the data
* @return the data in the requested flavor, as outlined above
* @throws UnsupportedFlavorException if the requested data flavor is
* not equivalent to <code>DataFlavor.imageFlavor</code>
* @throws IOException if an <code>IOException</code> occurs while
* retrieving the data. By default, <code>ImageSelection</code>
* never throws this exception, but a subclass may.
* @throws NullPointerException if flavor is <code>null</code>
*/
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, java.io.IOException {
if (flavor.equals(DataFlavor.imageFlavor)) {
return data;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
} // class ImageSelection

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