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,141 @@
/*
* 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.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
/*
* @test
* @bug 4111098
* @key headful
* @summary Test for no window activation on control requestFocus()
* @run main/timeout=30 ActivateOnFocusTest
*/
public class ActivateOnFocusTest {
static MyFrame mf1;
static Point p;
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> {
mf1 = new MyFrame();
mf1.setBounds(100, 100, 300, 300);
mf1.mc1.requestFocusInWindow();
});
Robot robot = new Robot();
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(() -> {
p = mf1.mb.getLocationOnScreen();
});
robot.waitForIdle();
robot.mouseMove(p.x + 5, p.y + 5);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
robot.delay(250);
} finally {
if (mf1 != null) {
EventQueue.invokeAndWait(mf1::dispose);
}
}
}
}
class MyFrame extends Frame implements ActionListener {
public Button mb;
public MyComponent mc1;
public MyComponent mc2;
public MyFrame() {
super();
setTitle("ActivateOnFocusTest");
setLayout(new FlowLayout());
mb = new Button("Pull");
mb.addActionListener(this);
add(mb);
mc1 = new MyComponent(Color.red);
add(mc1);
mc2 = new MyComponent(Color.blue);
add(mc2);
addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
mc1.requestFocusInWindow();
}
@Override
public void windowDeactivated(WindowEvent e) {
mc2.requestFocusInWindow();
}
});
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
MyFrame mf2 = new MyFrame();
mf2.setBounds(200, 200, 300, 300);
mf2.setVisible(true);
mf2.mc1.requestFocusInWindow();
}
}
class MyComponent extends Component {
public MyComponent(Color c) {
super();
setBackground(c);
}
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(getBackground());
g.fillRect(0, 0, d.width, d.height);
}
public boolean isFocusTraversable() {
return true;
}
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 2008, 2011, 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 %I% %E%
* @key headful
* @bug 2161766
* @summary Component is missing after changing the z-order of the component & focus is not transfered in
* @author Andrei Dmitriev : area=awt.container
* @run main CheckZOrderChange
*/
import java.awt.*;
import java.awt.event.*;
public class CheckZOrderChange {
private static Button content[] = new Button[]{new Button("Button 1"), new Button("Button 2"), new Button("Button 3"), new Button("Button 4")};
private static Frame frame;
public static void main(String[] args) {
frame = new Frame("Test Frame");
frame.setLayout(new FlowLayout());
for (Button b: content){
frame.add(b);
}
frame.setSize(300, 300);
frame.setVisible(true);
/* INITIAL ZORDERS ARE*/
for (Button b: content){
System.out.println("frame.getComponentZOrder("+ b +") = " + frame.getComponentZOrder(b));
}
//Change the Z Order
frame.setComponentZOrder(content[0], 2);
System.out.println("ZOrder of button1 changed to 2");
if (frame.getComponentZOrder(content[0]) != 2 ||
frame.getComponentZOrder(content[1]) != 0 ||
frame.getComponentZOrder(content[2]) != 1 ||
frame.getComponentZOrder(content[3]) != 3)
{
for (Button b: content){
System.out.println("frame.getComponentZOrder("+ b +") = " + frame.getComponentZOrder(b));
}
throw new RuntimeException("TEST FAILED: getComponentZOrder did not return the correct value");
}
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Button;
import java.awt.Component;
import java.awt.Container;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @test
* @key headful
* @bug 8059590
* @summary ArrayIndexOutOfBoundsException occurs when Container with overridden getComponents() is deserialized.
* @author Alexey Ivanov
* @run main ContainerAIOOBE
*/
public class ContainerAIOOBE {
public static void main(final String[] args) throws Exception {
ZContainer z = new ZContainer();
z.add(new Button());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(z);
oos.flush();
oos.close();
byte[] array = baos.toByteArray();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(array));
// Reading the object must not throw ArrayIndexOutOfBoundsException
ZContainer zz = (ZContainer) ois.readObject();
if (zz.getComponentCount() != 1) {
throw new Exception("deserialized object must have 1 component");
}
if (!(zz.getComponent(0) instanceof Button)) {
throw new Exception("deserialized object must contain Button component");
}
if (zz.getComponents().length != 0) {
throw new Exception("deserialized object returns non-empty array");
}
System.out.println("Test passed");
}
static class ZContainer extends Container {
public Component[] getComponents() {
return new Component[0];
}
}
}

View file

@ -0,0 +1,86 @@
/*
* 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 4311614
@summary findComponentAt() should check for isShowing() instead of isVisible()
@key headful
*/
import java.awt.Button;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
public class FindComponentAtTest {
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> {
Panel aContainer;
Panel bContainer;
Panel cContainer;
Button button = new Button("button4");
Frame frame = new Frame("FindComponentAtTest");
try {
aContainer = new Panel();
bContainer = new Panel();
cContainer = new Panel();
aContainer.setName("ACONT");
bContainer.setName("BCONT");
frame.add(aContainer);
aContainer.add(bContainer);
bContainer.add(cContainer);
cContainer.add(button);
bContainer.setVisible(false);
frame.setSize(200, 200);
frame.setVisible(true);
frame.validate();
System.out.println("Test set for FindComponentAt() method.");
System.out.println("aContainer - visible");
System.out.println("bContainer - child of aContainer - is invisible");
System.out.println("cContainer - child of bContainer - is visible");
System.out.println("button4 - child of cContainer - is visible");
Component comp = cContainer.findComponentAt(
cContainer.getWidth() / 2,
cContainer.getHeight() / 2);
if (comp != null) {
throw new RuntimeException(
"cContainer: Visible component inserted into "
+ "invisible container have found "
+ "by findComponentAt(x, y) method");
}
} finally {
frame.dispose();
}
System.out.println("FindComponentAt Test Succeeded.");
});
}
}

View file

@ -0,0 +1,90 @@
/*
* 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 4196100
@summary Make sure findComponentAt() only returns visible components.
@key headful
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
public class FindComponentTest {
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> {
FindComponentFrame findComponentAtTest = new FindComponentFrame();
try {
if (!findComponentAtTest.didItWork()) {
throw new RuntimeException(
"findComponentAt() returned non-visible component");
}
} finally {
findComponentAtTest.dispose();
}
});
}
}
class FindComponentFrame extends JFrame {
public FindComponentFrame() {
super("FindComponentFrame");
}
public boolean didItWork() {
setTitle("FindComponentTest");
setSize(new Dimension(200, 200));
JTabbedPane tabbedpane = new JTabbedPane();
setContentPane(tabbedpane);
JPanel panel1 = new JPanel();
panel1.setName("Panel 1");
panel1.setLayout(new BorderLayout());
tabbedpane.add(panel1);
JPanel subPanel = new JPanel();
subPanel.setName("Sub-Panel");
subPanel.setBackground(Color.green);
panel1.add(subPanel); // add sub panel to 1st tab
JPanel panel2 = new JPanel();
panel2.setName("Panel 2");
tabbedpane.add(panel2);
tabbedpane.setSelectedIndex(1); // display 2nd tab
setVisible(true);
boolean success = tabbedpane.findComponentAt(50,50)
.getName().equals("Panel 2");
return success;
}
}

View file

@ -0,0 +1,509 @@
/*
* 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
@summary unit test for ability of FocusTraversalPolicyProvider
@key headful
*/
import java.awt.Button;
import java.awt.Component;
import java.awt.Container;
import java.awt.ContainerOrderFocusTraversalPolicy;
import java.awt.DefaultFocusTraversalPolicy;
import java.awt.EventQueue;
import java.awt.FocusTraversalPolicy;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.Robot;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.LayoutFocusTraversalPolicy;
public class FocusTraversalPolicyProviderTest {
final String errorOrderMessage = "Test Failed. Traversal Order not correct.";
final String successStage = "Test stage completed.Passed.";
final int n_buttons = 4;
final int jumps = 3 * n_buttons;
Container[] cycle_roots = new Container[3];
Panel[] a_conts = new Panel[cycle_roots.length];
Panel[] b_conts = new Panel[cycle_roots.length];
Component[][] a_buttons = new Component[cycle_roots.length][n_buttons];
Component[][] b_buttons = new Component[cycle_roots.length][n_buttons];
static volatile Frame mainFrame = null;
static volatile Frame frame = null;
static volatile JFrame jframe = null;
static Robot robot;
public static void main(String[] args) throws Exception {
FocusTraversalPolicyProviderTest test
= new FocusTraversalPolicyProviderTest();
try {
robot = new Robot();
EventQueue.invokeAndWait(test::init);
robot.delay(1000);
EventQueue.invokeAndWait(test::testStages);
EventQueue.invokeAndWait(test::initSwingContInFrame);
robot.delay(1000);
EventQueue.invokeAndWait(test::testSwingContInFrame);
// test for Swing container in java.awt.Frame
System.out.println("Test passed.");
} finally {
EventQueue.invokeAndWait(() -> {
if (mainFrame != null) mainFrame.dispose();
if (frame != null) frame.dispose();
if (jframe != null) jframe.dispose();
});
}
}
public void init() {
mainFrame = new Frame("FocusTraversalPolicyProviderTest - main");
mainFrame.setSize(400, 400);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
for (int i = 0; i < cycle_roots.length; i++) {
cycle_roots[i] = new Panel();
cycle_roots[i].setFocusable(false);
cycle_roots[i].setName("root" + i);
cycle_roots[i].setFocusCycleRoot(true);
cycle_roots[i].setLayout (new GridLayout(1, 2));
mainFrame.add(cycle_roots[i]);
a_conts[i] = new Panel();
a_conts[i].setName("ac" + i);
a_conts[i].setFocusable(false);
cycle_roots[i].add(a_conts[i]);
b_conts[i] = new Panel();
b_conts[i].setName("bc" + i);
b_conts[i].setFocusable(false);
cycle_roots[i].add(b_conts[i]);
for (int j = 0; j < n_buttons; j++){
String name = "a" + i + "x" + j;
a_buttons[i][j] = new Button(name);
a_buttons[i][j].setName(name);
a_conts[i].add(a_buttons[i][j]);
}
for (int j = 0; j < n_buttons; j++){
String name = "b" + i + "x" + j;
b_buttons[i][j] = new Button(name);
b_buttons[i][j].setName(name);
b_conts[i].add(b_buttons[i][j]);
}
}
cycle_roots[0].setFocusTraversalPolicy(new DefaultFocusTraversalPolicy());
cycle_roots[1].setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy());
cycle_roots[2].setFocusTraversalPolicy(new LayoutFocusTraversalPolicy());
}
public void testStages() {
for (int i = 0; i < cycle_roots.length; i++) {
testStage(cycle_roots[i], a_conts[i], b_conts[i],
a_buttons[i], b_buttons[i]);
}
}
void testStage(Container aFCR, Container aCont, Container bCont,
Component[] a_comps, Component[] b_comps) {
System.out.println("focus cycle root = " + aFCR.getName());
System.out.println("policy = " + aFCR.getFocusTraversalPolicy());
System.out.println("aContainer = " + aCont.getName());
System.out.println("bContainer = " + bCont.getName());
System.out.println("Both containers are not Providers.");
Component[] a_comps_backward = revertArray(a_comps);
Component[] b_comps_backward = revertArray(b_comps);
testForwardStage(aFCR, aCont, bCont,
false, a_comps, false, b_comps);
testBackwardStage(aFCR, aCont, bCont,
false, a_comps_backward,
false, b_comps_backward);
System.out.println("Both containers are Providers.");
testForwardStage(aFCR, aCont, bCont,
true, a_comps, true, b_comps);
testForwardStage(aFCR, aCont, bCont,
true, shakeArray(a_comps),
true, shakeArray(b_comps));
testBackwardStage(aFCR, aCont, bCont,
true, a_comps_backward,
true, b_comps_backward);
testBackwardStage(aFCR, aCont, bCont,
true, shakeArray(a_comps_backward),
true, shakeArray(b_comps_backward));
System.out.println("aContainer.isProvider = true. "
+ "bContainer.isProvider = false.");
testForwardStage(aFCR, aCont, bCont,
true, a_comps, false, b_comps);
testForwardStage(aFCR, aCont, bCont,
true, shakeArray(a_comps),
false, b_comps);
testBackwardStage(aFCR, aCont, bCont,
true, a_comps_backward,
false, b_comps_backward);
testBackwardStage(aFCR, aCont, bCont,
true, shakeArray(a_comps_backward),
false, b_comps_backward);
System.out.println("aContainer.isProvider = false. "
+ "bContainer.isProvider = true.");
testForwardStage(aFCR, aCont, bCont,
false, a_comps,
true, b_comps);
testForwardStage(aFCR, aCont, bCont,
false, a_comps,
true, shakeArray(b_comps));
testBackwardStage(aFCR, aCont, bCont,
false, a_comps_backward,
true, b_comps_backward);
testBackwardStage(aFCR, aCont, bCont,
false, a_comps_backward,
true, shakeArray(b_comps_backward));
System.out.println("Stage completed.");
}
public void printGoldOrder(Component[] comps) {
String goldOrderStr = "";
for (int i =0;i < jumps; i++){
goldOrderStr += " " + comps[i].getName();
}
System.out.println("GoldOrder: " + goldOrderStr);
}
public void testForwardStage(Container focusCycleRoot,
Container aContainer,
Container bContainer,
boolean aProvider, Component[] aComps,
boolean bProvider, Component[] bComps) {
System.out.println("test forward traversal");
System.out.println("\taProvider = " + aProvider);
System.out.println("\tbProvider = " + bProvider);
Component[] goldOrder = new Component[2*aComps.length + bComps.length];
System.arraycopy(aComps, 0, goldOrder, 0, aComps.length);
System.arraycopy(bComps, 0, goldOrder,
aComps.length, bComps.length);
System.arraycopy(aComps, 0, goldOrder,
aComps.length + bComps.length,
aComps.length);
printGoldOrder(goldOrder);
String jumpStr = "";
aContainer.setFocusTraversalPolicyProvider(aProvider);
aContainer.setFocusTraversalPolicy(
new ArrayOrderFocusTraversalPolicy(aContainer, aComps));
bContainer.setFocusTraversalPolicyProvider(bProvider);
bContainer.setFocusTraversalPolicy(
new ArrayOrderFocusTraversalPolicy(bContainer, bComps));
FocusTraversalPolicy policy = focusCycleRoot.getFocusTraversalPolicy();
System.out.println("policy=" + policy);
Component current = policy.getFirstComponent(focusCycleRoot);
for (int i = 0;i<jumps;i++){
jumpStr += " " + current.getName();
if (current != goldOrder[i]) {
System.out.println("i=" + i + " label = "+ current.getName()
+ " i%8= " + i%goldOrder.length );
throw new RuntimeException(errorOrderMessage);
}
System.out.println("getComponentAfter() on " + focusCycleRoot + ", " + current);
current = policy.getComponentAfter(focusCycleRoot, current);
System.out.println("RealOrder :" + jumpStr);
}
System.out.println(successStage);
}
public void testBackwardStage(Container focusCycleRoot,
Container aContainer,
Container bContainer,
boolean aProvider, Component[] aComps,
boolean bProvider, Component[] bComps)
{
System.out.println("test backward traversal");
System.out.println("\taProvider = " + aProvider);
System.out.println("\tbProvider = " + bProvider);
Component[] goldOrder = new Component[2*bComps.length + bComps.length];
System.arraycopy(bComps, 0, goldOrder, 0, bComps.length);
System.arraycopy(aComps, 0, goldOrder, bComps.length, aComps.length);
System.arraycopy(bComps, 0, goldOrder,
aComps.length + bComps.length, bComps.length);
printGoldOrder(goldOrder);
String jumpStr = "";
aContainer.setFocusTraversalPolicyProvider(aProvider);
aContainer.setFocusTraversalPolicy(
new ArrayOrderFocusTraversalPolicy(aContainer, revertArray(aComps)));
bContainer.setFocusTraversalPolicyProvider(bProvider);
bContainer.setFocusTraversalPolicy(
new ArrayOrderFocusTraversalPolicy(bContainer, revertArray(bComps)));
FocusTraversalPolicy policy = focusCycleRoot.getFocusTraversalPolicy();
System.out.println("policy=" + policy);
Component current = policy.getLastComponent(focusCycleRoot);
for (int i = 0;i<jumps;i++){
jumpStr += " " + current.getName();
if (current != goldOrder[i]) {
System.out.println("i=" + i + " label = "+ current.getName());
throw new RuntimeException(errorOrderMessage);
}
System.out.println("getComponentBefore() on "
+ focusCycleRoot.getName() + ", " + current.getName());
current = policy.getComponentBefore(focusCycleRoot, current);
System.out.println("RealOrder :" + jumpStr);
}
System.out.println(successStage);
}
Component[] shakeArray(Component[] comps) {
Component[] new_comps = new Component[comps.length];
System.arraycopy(comps, 0, new_comps, 0, comps.length);
new_comps[0] = comps[1];
new_comps[1] = comps[0];
return new_comps;
}
Component[] revertArray(Component[] comps) {
Component[] new_comps = new Component[comps.length];
for (int i=0; i < comps.length; i++) {
new_comps[i] = comps[comps.length - 1 - i];
}
return new_comps;
}
public void initSwingContInFrame() {
System.out.println("test Swing policy provider in AWT Frame.");
jframe = new JFrame("FocusTraversalPolicyProviderTest - JFrame");
jframe.setName("JFrame");
JPanel panel1 = createPanel();
jframe.getContentPane().add(panel1);
frame = new Frame("FocusTraversalPolicyProviderTest - Frame");
frame.setName("Frame");
JPanel panel2 = createPanel();
panel2.setFocusTraversalPolicyProvider(true);
panel2.setFocusTraversalPolicy(jframe.getFocusTraversalPolicy());
frame.add(panel2);
jframe.pack();
jframe.setVisible(true);
frame.pack();
frame.setVisible(true);
}
public void testSwingContInFrame() {
FocusTraversalPolicy policy = frame.getFocusTraversalPolicy();
FocusTraversalPolicy jpolicy = jframe.getFocusTraversalPolicy();
System.out.println("policy = " + policy);
System.out.println("jpolicy = " + jpolicy);
assertEquals("Different default components.",
jpolicy.getDefaultComponent(jframe),
policy.getDefaultComponent(frame));
assertEquals("Different first components.",
jpolicy.getFirstComponent(jframe),
policy.getFirstComponent(frame));
assertEquals("Different last components.",
jpolicy.getLastComponent(jframe),
policy.getLastComponent(frame));
System.out.println("test forward traversal order.");
Component jcur = jpolicy.getFirstComponent(jframe);
Component cur = jpolicy.getFirstComponent(frame);
for (int i = 0; i < 2 * n_buttons; i++) {
assertEquals("Wrong sequence (step=" + i + ")",
jcur, cur);
jcur = jpolicy.getComponentAfter(jframe, jcur);
cur = policy.getComponentAfter(frame, cur);
}
System.out.println("test backward traversal order.");
jcur = jpolicy.getLastComponent(jframe);
cur = jpolicy.getLastComponent(frame);
for (int i = 0; i < 2 * n_buttons; i++) {
assertEquals("Wrong sequence (step=" + i + ")",
jcur, cur);
jcur = jpolicy.getComponentBefore(jframe, jcur);
cur = policy.getComponentBefore(frame, cur);
}
}
public void assertEquals(String msg, Component expected, Component actual) {
if (expected == null && actual != null
|| actual == null && expected != null)
{
throw new RuntimeException(msg + "(expected=" + expected
+ ", actual=" + actual + ")");
}
String expected_name = expected.getName();
String actual_name = actual.getName();
if ((expected_name != null && !expected_name.equals(actual_name))
|| (actual_name != null && !actual_name.equals(expected_name)))
{
throw new RuntimeException(msg + "(expected_name=" + expected_name
+ ", actual_name=" + actual_name + ")");
}
}
public JPanel createPanel() {
JPanel pane = new JPanel();
pane.setName("jpanel");
for (int i = 0; i < n_buttons; i++) {
JButton btn = new JButton("jbtn" + i);
btn.setName("jbtn" + i);
pane.add(btn);
}
return pane;
}
}
class ArrayOrderFocusTraversalPolicy extends FocusTraversalPolicy {
final Component[] comps;
final Container cont;
public ArrayOrderFocusTraversalPolicy(Container aCont, Component[] aComps) {
if (aCont == null) {
throw new NullPointerException("aCont is null.");
}
cont = aCont;
comps = new Component[aComps.length];
for (int i = 0; i < comps.length; i++) {
comps[i] = aComps[i];
}
}
private void checkContainer(Container aCont) {
if (aCont != cont) {
System.err.println("aCont = " + aCont);
System.err.println("cont = " + cont);
throw new IllegalArgumentException(
"Policy is not registered for this container.");
}
}
private int findIndex(Component aComp) {
for (int i = 0; i < comps.length; i++) {
if (aComp == comps[i]) {
return i;
}
}
return -1;
}
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
checkContainer(focusCycleRoot);
int current_index = findIndex(aComponent);
if (current_index < 0) {
return null;
}
current_index++;
if (current_index < comps.length) {
return comps[current_index];
}
if (focusCycleRoot.isFocusCycleRoot()) {
return getFirstComponent(focusCycleRoot);
} else {
return null;
}
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
checkContainer(focusCycleRoot);
int current_index = findIndex(aComponent);
if (current_index < 0) {
return null;
}
current_index--;
if (current_index >= 0) {
return comps[current_index];
}
if (focusCycleRoot.isFocusCycleRoot()) {
return getLastComponent(focusCycleRoot);
} else {
return null;
}
}
public Component getFirstComponent(Container focusCycleRoot) {
checkContainer(focusCycleRoot);
return comps[0];
}
public Component getLastComponent(Container focusCycleRoot) {
checkContainer(focusCycleRoot);
return comps[comps.length - 1];
}
public Component getDefaultComponent(Container focusCycleRoot) {
return getFirstComponent(focusCycleRoot);
}
public Component getInitialComponent(Window window) {
throw new UnsupportedOperationException("getInitialComponent() is not supported.");
}
public Component[] getCycle(Container focusCycleRoot) {
checkContainer(focusCycleRoot);
Component[] temp = new Component[comps.length];
System.arraycopy(comps, 0, temp, 0, comps.length);
return temp;
}
}

View file

@ -0,0 +1,244 @@
/*
* 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.Component;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/*
* @test
* @bug 4159745
* @key headful
* @summary Mediumweight popup dragging broken
* @run main MouseEnteredTest
*/
public class MouseEnteredTest extends JFrame implements ActionListener {
static volatile MouseEnteredTest test;
static volatile Point p;
static volatile Point p2;
static String strMotif = "Motif";
static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
static char cMotif = 'o';
static String strWindows = "Windows";
static String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
static char cWindows = 'W';
static String strMetal = "Metal";
static String metalClassName = "javax.swing.plaf.metal.MetalLookAndFeel";
static char cMetal = 'M';
static JMenu m;
static JMenu menu;
static MouseListener ml = new MouseEnteredTest.MouseEventListener();
public MouseEnteredTest() {
setTitle("MouseEnteredTest");
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
setJMenuBar(getMyMenuBar());
getContentPane().add("Center", new JTextArea());
setSize(400, 500);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> {
test = new MouseEnteredTest();
});
Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(() -> {
p = m.getLocationOnScreen();
p2 = menu.getLocationOnScreen();
});
robot.waitForIdle();
robot.delay(250);
robot.mouseMove(p.x + 5, p.y + 10);
robot.waitForIdle();
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
for (int i = p.x; i < p2.x + 10; i = i + 2) {
robot.mouseMove(i, p2.y + 10);
}
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(2000);
if (m.isPopupMenuVisible()) {
throw new RuntimeException("First menu is showing. Test Failed.");
}
} finally {
if (test != null) {
EventQueue.invokeAndWait(test::dispose);
}
}
}
public JMenuBar getMyMenuBar() {
JMenuBar menubar;
JMenuItem menuItem;
menubar = GetLNFMenuBar();
menu = menubar.add(new JMenu("Test"));
menu.setName("Test");
menu.addMouseListener(ml);
menu.setMnemonic('T');
menuItem = menu.add(new JMenuItem("Menu Item"));
menuItem.addActionListener(this);
menuItem.setMnemonic('M');
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.ALT_MASK));
JRadioButtonMenuItem mi = new JRadioButtonMenuItem("Radio Button");
mi.addActionListener(this);
mi.setMnemonic('R');
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
menu.add(mi);
JCheckBoxMenuItem mi1 = new JCheckBoxMenuItem("Check Box");
mi1.addActionListener(this);
mi1.setMnemonic('C');
mi1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK));
menu.add(mi1);
return menubar;
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if (str.equals(metalClassName) || str.equals(windowsClassName) || str.equals(motifClassName)) {
changeLNF(str);
} else {
System.out.println("ActionEvent: " + str);
}
}
public void changeLNF(String str) {
System.out.println("Changing LNF to " + str);
try {
UIManager.setLookAndFeel(str);
SwingUtilities.updateComponentTreeUI(this);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
public JMenuBar GetLNFMenuBar() {
JMenuBar mbar = new JMenuBar();
m = new JMenu("Look and Feel");
m.setName("Look and Feel");
m.addMouseListener(ml);
m.setMnemonic('L');
ButtonGroup bg = new ButtonGroup();
JRadioButtonMenuItem mi;
mi = new JRadioButtonMenuItem(strMetal);
mi.addActionListener(this);
mi.setActionCommand(metalClassName);
mi.setMnemonic(cMetal);
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
mi.setSelected(true);
bg.add(mi);
m.add(mi);
mi = new JRadioButtonMenuItem(strWindows);
mi.addActionListener(this);
mi.setActionCommand(windowsClassName);
mi.setMnemonic(cWindows);
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
bg.add(mi);
m.add(mi);
mi = new JRadioButtonMenuItem(strMotif);
mi.addActionListener(this);
mi.setActionCommand(motifClassName);
mi.setMnemonic(cMotif);
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.ALT_MASK));
bg.add(mi);
m.add(mi);
mbar.add(m);
return mbar;
}
static class MouseEventListener implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent e) {
System.out.println("In mouseClicked for " + e.getComponent().getName());
}
public void mousePressed(MouseEvent e) {
Component c = e.getComponent();
System.out.println("In mousePressed for " + c.getName());
}
public void mouseReleased(MouseEvent e) {
System.out.println("In mouseReleased for " + e.getComponent().getName());
}
public void mouseEntered(MouseEvent e) {
System.out.println("In mouseEntered for " + e.getComponent().getName());
System.out.println("MouseEvent:" + e.getComponent());
}
public void mouseExited(MouseEvent e) {
System.out.println("In mouseExited for " + e.getComponent().getName());
}
public void mouseDragged(MouseEvent e) {
System.out.println("In mouseDragged for " + e.getComponent().getName());
}
public void mouseMoved(MouseEvent e) {
System.out.println("In mouseMoved for " + e.getComponent().getName());
}
}
}

View file

@ -0,0 +1,88 @@
/*
* 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.
*/
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.lang.reflect.InvocationTargetException;
/* @test
@bug 8160696
@summary IllegalArgumentException: adding a component to a container on a different GraphicsDevice
@author Mikhail Cherkasov
@run main MoveToOtherScreenTest
@key headful
*/
public class MoveToOtherScreenTest {
private static volatile boolean twoDisplays = true;
private static final Canvas canvas = new Canvas();
private static final Frame[] frms = new JFrame[2];
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
if (gds.length < 2) {
System.out.println("Test requires at least 2 displays");
twoDisplays = false;
return;
}
for (int i = 0; i < 2; i++) {
GraphicsConfiguration conf = gds[i].getConfigurations()[0];
JFrame frm = new JFrame("Frame " + i);
frm.setLocation(conf.getBounds().x, 0); // On first screen
frm.setSize(new Dimension(400, 400));
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
frms[i] = frm;
}
canvas.setBackground(Color.red);
frms[0].add(canvas);
}
});
if(!twoDisplays){
return;
}
Thread.sleep(200);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
frms[1].add(canvas);
}
});
for (Frame frm : frms) {
frm.dispose();
}
}
}

View file

@ -0,0 +1,127 @@
/*
* 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 4852790
@summary Frame disposal must remove opened popup without exception
@key headful
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class OpenedPopupFrameDisposal {
public static final int SIZE = 300;
volatile JFrame jf = null;
volatile JComboBox<String> jcb = null;
public void start() {
jf = new JFrame("OpenedPopupFrameDisposal - Frame to dispose");
// Note that original bug cannot be reproduced without JMenuBar present.
jf.setJMenuBar(new JMenuBar());
jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
jf.setVisible(false);
jf.dispose();
}
});
JPanel panel = new JPanel(new FlowLayout());
jcb = new JComboBox<>();
jcb.addItem("one");
jcb.addItem("two");
jcb.addItem("Three");
panel.add(jcb);
jf.getContentPane().add(panel, BorderLayout.CENTER);
jf.pack();
jf.setSize(new Dimension(SIZE, SIZE));
jf.setVisible(true);
}
public void test() throws Exception {
Robot robot = new Robot();
robot.delay(1000); // wait for jf visible
Point pt = jf.getLocationOnScreen();
int x, y;
x = pt.x + SIZE / 2;
y = pt.y + SIZE / 2;
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
pt = jcb.getLocationOnScreen();
x = pt.x + jcb.getWidth() / 2;
y = pt.y + jcb.getHeight() / 2;
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
// Here on disposal we had a NullPointerException
EventQueue.invokeAndWait(() -> {
if (jf != null) {
jf.setVisible(false);
jf.dispose();
}
});
}
public static void main(String[] args) throws Exception {
OpenedPopupFrameDisposal imt = new OpenedPopupFrameDisposal();
try {
EventQueue.invokeAndWait(imt::start);
imt.test();
} finally {
EventQueue.invokeAndWait(() -> {
if (imt.jf != null) {
imt.jf.dispose();
}
});
}
}
}

View file

@ -0,0 +1,129 @@
/*
* 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
@summary unit test for ability of FocusTraversalPolicyProvider
*/
import java.awt.Container;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class PropertyEventsTest implements PropertyChangeListener {
final String PROPERTY = "focusTraversalPolicyProvider";
public static void main(String[] args) throws Exception {
new PropertyEventsTest().start();
}
public void start () {
Container c1 = new Container();
c1.addPropertyChangeListener(PROPERTY, this);
assertEquals("Container shouldn't be a provider by default",
false, c1.isFocusTraversalPolicyProvider());
prepareForEvent(false, true);
c1.setFocusTraversalPolicyProvider(true);
assertEventOccured();
assertEquals("Policy provider property was not set.",
true, c1.isFocusTraversalPolicyProvider());
prepareForEvent(true, false);
c1.setFocusTraversalPolicyProvider(false);
assertEventOccured();
assertEquals("Policy provider property was not reset.",
false, c1.isFocusTraversalPolicyProvider());
prepareForEvent(false, true);
c1.setFocusCycleRoot(true);
assertEventMissed();
assertEquals("Cycle root shouldn't be a policy provider.",
false, c1.isFocusTraversalPolicyProvider());
prepareForEvent(true, false);
c1.setFocusCycleRoot(false);
assertEventMissed();
assertEquals("setFocusCycleRoot(false) should reset "
+ "policy provider property.",
false, c1.isFocusTraversalPolicyProvider());
System.out.println("Test passed.");
}// start()
void assertEquals(String msg, boolean expected, boolean actual) {
if (expected != actual) {
Assert(msg + "(expected=" + expected + ", actual=" + actual + ")");
}
}
void assertEquals(String msg, Object expected, Object actual) {
if ((expected != null && !expected.equals(actual))
|| (actual != null && !actual.equals(expected)))
{
Assert(msg + "(expected=" + expected + ", actual=" + actual + ")");
}
}
void Assert(String msg) {
throw new RuntimeException(msg);
}
void prepareForEvent(boolean old_val, boolean new_val) {
property_change_fired = false;
expected_new_value = Boolean.valueOf(new_val);
expected_old_value = Boolean.valueOf(old_val);
}
void assertEventOccured() {
if (!property_change_fired) {
Assert("Property Change Event missed.");
}
}
void assertEventMissed() {
if (property_change_fired) {
Assert("Unexpected property change event.");
}
}
boolean property_change_fired;
Boolean expected_new_value;
Boolean expected_old_value;
public void propertyChange(PropertyChangeEvent e) {
System.out.println("PropertyChangeEvent[property=" + e.getPropertyName()
+ ", new=" + e.getNewValue()
+ ", old=" + e.getOldValue() + "]");
assertEquals("Wrong proeprty name.",
PROPERTY, e.getPropertyName());
assertEquals("Wrong new value.",
expected_new_value, e.getNewValue());
assertEquals("Wrong old value.",
expected_old_value, e.getOldValue());
property_change_fired = true;
}
}

View file

@ -0,0 +1,56 @@
/*
* 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 4546535
@summary java.awt.Container.remove(int) throws unexpected NPE
*/
import java.awt.Canvas;
import java.awt.Panel;
public class RemoveByIndexExceptionTest {
public static void main(String[] args) throws Exception {
Panel p = new Panel();
p.add(new Canvas());
p.remove(0);
int[] bad = {-1, 0, 1};
for (int i = 0; i < bad.length; i++) {
try {
System.out.println("Removing " + bad[i]);
p.remove(bad[i]);
System.out.println("No exception");
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("This is correct exception - " + e);
} catch (NullPointerException e) {
e.printStackTrace();
throw new RuntimeException("Test Failed: NPE was thrown.");
}
}
System.out.println("Test Passed.");
}
}

View file

@ -0,0 +1,105 @@
/*
* 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 4924516
@summary Verifies that SHOWING_CHANGED event is propagated to \
HierarchyListeners then toolkit enabled
@key headful
*/
import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ShowingChangedEventTest
implements AWTEventListener, HierarchyListener{
private boolean eventRegisteredOnButton = false;
private final JFrame frame = new JFrame("ShowingChangedEventTest");
private final JPanel panel = new JPanel();
private final JButton button = new JButton();
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> {
ShowingChangedEventTest showingChangedEventTest
= new ShowingChangedEventTest();
try {
showingChangedEventTest.start();
} finally {
showingChangedEventTest.frame.dispose();
}
});
}
public void start () {
frame.getContentPane().add(panel);
panel.add(button);
frame.pack();
frame.setVisible(true);
Toolkit.getDefaultToolkit()
.addAWTEventListener(this, AWTEvent.HIERARCHY_EVENT_MASK);
button.addHierarchyListener(this);
panel.setVisible(false);
if (!eventRegisteredOnButton){
throw new RuntimeException("Event wasn't registered on Button.");
}
}
@Override
public void eventDispatched(AWTEvent awtevt) {
if (awtevt instanceof HierarchyEvent) {
HierarchyEvent hevt = (HierarchyEvent) awtevt;
if (hevt != null && (hevt.getChangeFlags()
& HierarchyEvent.SHOWING_CHANGED) != 0) {
System.out.println("Hierarchy event was received on Toolkit. "
+ "SHOWING_CHANGED for "
+ hevt.getChanged().getClass().getName());
}
}
}
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ((HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags()) != 0) {
System.out.println("Hierarchy event was received on Button. "
+ "SHOWING_CHANGED for "
+ e.getChanged().getClass().getName());
}
eventRegisteredOnButton = true;
}
}

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2009, 2011, 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 6852592
@summary invalidate() must stop when it encounters a validate root
@author anthony.petrov@sun.com
@run main/othervm -Djava.awt.smartInvalidate=true InvalidateMustRespectValidateRoots
*/
import javax.swing.*;
import java.awt.event.*;
public class InvalidateMustRespectValidateRoots {
private static volatile JRootPane rootPane;
public static void main(String args[]) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// The JRootPane is a validate root. We'll check if
// invalidate() stops on the root pane, or goes further
// up to the frame.
JFrame frame = new JFrame();
final JButton button = new JButton();
frame.add(button);
// To enable running the test manually: use the Ctrl-Shift-F1
// to print the component hierarchy to the console
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if (button.isValid()) {
button.invalidate();
} else {
button.revalidate();
}
}
});
rootPane = frame.getRootPane();
// Now the component hierarchy looks like:
// frame
// --> rootPane
// --> layered pane
// --> content pane
// --> button
// Make all components valid first via showing the frame
// We have to make the frame visible. Otherwise revalidate() is
// useless (see RepaintManager.addInvalidComponent()).
frame.pack(); // To enable running this test manually
frame.setVisible(true);
if (!frame.isValid()) {
throw new RuntimeException(
"setVisible(true) failed to validate the frame");
}
// Now invalidate the button
button.invalidate();
// Check if the 'valid' status is what we expect it to be
if (rootPane.isValid()) {
throw new RuntimeException(
"invalidate() failed to invalidate the root pane");
}
if (!frame.isValid()) {
throw new RuntimeException(
"invalidate() invalidated the frame");
}
// Now validate the hierarchy again
button.revalidate();
// Now let the validation happen on the EDT
}
});
Thread.sleep(1000);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// Check if the root pane finally became valid
if (!rootPane.isValid()) {
throw new RuntimeException(
"revalidate() failed to validate the hierarchy");
}
}
});
}
}

View file

@ -0,0 +1,78 @@
/*
* 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.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
/*
* @test
* @bug 4136190
* @requires (os.family == "windows")
* @summary Recursive validation calls would cause major USER resource leakage
* @key headful
* @run main/timeout=30 ValidateTest
*/
public class ValidateTest {
static Frame frame;
public static void main(String args[]) throws Exception {
try {
EventQueue.invokeAndWait(() -> {
createGUI();
});
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
public static void createGUI() {
frame = new Frame("Test for 4136190 : JVM and win95 resource leakage issues");
frame.setLayout(new GridLayout(1, 1));
MyPanel panel = new MyPanel();
frame.add(panel);
frame.invalidate();
frame.validate();
frame.setSize(500, 400);
frame.setVisible(true);
}
static class MyPanel extends Panel {
int recurseCounter = 0;
public void validate() {
recurseCounter++;
if (recurseCounter >= 100) {
return;
}
getParent().validate();
super.validate();
}
}
}

View file

@ -0,0 +1,243 @@
/*
* Copyright (c) 2007, 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 6552803
@summary moveToFront shouldn't remove peers of HW components
@author anthony.petrov@...: area=awt.container
@library ../../regtesthelpers
@build Util
@run main JInternalFrameTest
*/
/**
* JInternalFrameTest.java
*
* summary: movtToFront invoked on the JInternalFrame shouldn't
* recreate peers of HW descendants of the JInternalFrame.
*/
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyVetoException;
import javax.swing.*;
import test.java.awt.regtesthelpers.Util;
public class JInternalFrameTest
{
// Indicates whether the removeNotify() was invoked on the HW Canvas
static volatile boolean isRemoveNotify = false;
// The HW Canvas class.
private static final class MyCanvas extends Canvas {
private final Color background;
public MyCanvas(Color background) {
this.background = background;
setPreferredSize(new Dimension(100, 100));
}
public void paint(Graphics g) {
g.setColor(background);
g.fillRect(0, 0, getWidth(), getHeight());
}
public void addNotify() {
super.addNotify();
System.err.println("addNotify() on " + background);
}
public void removeNotify() {
super.removeNotify();
isRemoveNotify = true;
System.err.println("removeNotify() on " + background);
Thread.dumpStack();
}
}
private static void init()
{
// We create a JFrame with two JInternalFrame.
// Each JInternalFrame contains a HW Canvas component.
JFrame jframe = new JFrame("mixing test");
JDesktopPane desktop = new JDesktopPane();
jframe.setContentPane(desktop);
JInternalFrame iframe1 = new JInternalFrame("iframe 1");
iframe1.setIconifiable(true);
iframe1.add(new MyCanvas(Color.RED));
iframe1.setBounds(10, 10, 100, 100);
iframe1.setVisible(true);
desktop.add(iframe1);
JInternalFrame iframe2 = new JInternalFrame("iframe 2");
iframe2.setIconifiable(true);
iframe2.add(new MyCanvas(Color.BLUE));
iframe2.setBounds(50, 50, 100, 100);
iframe2.setVisible(true);
desktop.add(iframe2);
jframe.setSize(300, 300);
jframe.setVisible(true);
// Wait until everything gets shown
Util.waitForIdle(null);
// Now cause a couple of z-order changing operations
iframe2.moveToFront();
Util.waitForIdle(null);
iframe1.moveToFront();
Util.waitForIdle(null);
iframe2.moveToFront();
// Wait until all the operations complete
Util.waitForIdle(null);
if (isRemoveNotify) {
fail("The removeNotify() was invoked on the HW Canvas");
}
JInternalFrameTest.pass();
}//End init()
/*****************************************************
* 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 JInternalFrameTest
//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
{
}