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,60 @@
/*
* Copyright (c) 2012, 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 7024749 8019990
* @summary JDK7 b131---a crash in: Java_sun_awt_windows_ThemeReader_isGetThemeTransitionDurationDefined+0x75
* @library ../../regtesthelpers
* @build Util
* @author Oleg Pekhovskiy: area=awt.toplevel
@run main bug7024749
*/
import java.awt.*;
import test.java.awt.regtesthelpers.Util;
public class bug7024749 {
public static void main(String[] args) {
final Frame f = new Frame("F");
f.setBounds(0,0,200,200);
f.setEnabled(false); // <- disable the top-level
f.setVisible(true);
Window w = new Window(f);
w.setBounds(300,300,300,300);
w.add(new TextField(20));
w.setVisible(true);
Robot robot = Util.createRobot();
robot.setAutoDelay(1000);
Util.waitForIdle(robot);
robot.delay(1000);
Util.clickOnTitle(f, robot);
Util.waitForIdle(robot);
f.dispose();
System.out.println("Test passed!");
}
}

View file

@ -0,0 +1,50 @@
/*
* 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 8158918
* @summary setExtendedState(1) for maximized Frame results in state==7
* @run main SetExtendedState
*/
import java.awt.Frame;
public class SetExtendedState {
public static void main(String[] args) {
Frame frame = new Frame("frame");
frame.setBounds(100, 100, 200, 200);
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setExtendedState(Frame.ICONIFIED);
if (frame.getExtendedState() != Frame.ICONIFIED) {
frame.dispose();
throw new RuntimeException("Test Failed");
}
frame.dispose();
}
}

View file

@ -0,0 +1,116 @@
/*
* Copyright (c) 2006, 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.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import javax.swing.SwingUtilities;
/*
* @test
* @bug 6435804
* @summary REGRESSION: NetBeans 5.0 icon no longer shows up when you alt-tab on XP
* @key headful
* @requires (os.family != "mac")
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ALTTABIconBeingErased
*/
public class ALTTABIconBeingErased {
private static final String INSTRUCTIONS =
"This test verifies that the Frame's icon is not corrupted after showing\n"
+ "and disposing owned dialog\n"
+ "You would see a button in a Frame.\n"
+ "1) The frame should have icon with 2 black and 2 white squares.\n"
+ "2) Verify that icon appearing on ALT-TAB is also a\n"
+ "light icon.\n"
+ "3) Now open a child by pressing on \"Open Child\" button.\n"
+ "Child Dialog should appear. It should have the same icon as frame.\n"
+ "4) Now close the dialog by pressing Space or clicking on a button in it.\n"
+ "Dialog should be disposed now.\n"
+ "5) Verify that icon on ALT-TAB is the same as before";
private static Frame frame;
private static final int SIZE = 300;
private static void updateIconImage() {
BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
Graphics gr = image.createGraphics();
gr.setColor(Color.WHITE);
gr.fillRect(0, 0, SIZE, SIZE);
gr.setColor(Color.BLACK);
gr.fillRect(0, 0, SIZE / 2, SIZE / 2);
gr.fillRect(SIZE / 2, SIZE / 2, SIZE, SIZE);
frame.setIconImage(image);
}
private static void createAndShowGUI(){
frame = new Frame();
Button setImageButton5 = new Button("Open Child");
updateIconImage();
setImageButton5.addActionListener(event -> {
try {
final Dialog d1 = new Dialog(frame, true);
d1.setSize(100, 100);
Button ok = new Button("OK");
ok.addActionListener(e -> {
d1.setVisible(false);
d1.dispose();
});
d1.add(ok);
d1.setLocation(frame.getX(), frame.getY() + 70);
d1.setVisible(true);
} catch (Exception e) {
throw new RuntimeException("Test failed because of" +
" exception" + e + ". Press Fail.");
}
});
frame.add(setImageButton5, BorderLayout.CENTER);
frame.setSize(200,65);
PassFailJFrame.addTestWindow(frame);
PassFailJFrame.positionTestWindow(frame,
PassFailJFrame.Position.HORIZONTAL);
frame.setVisible(true);
}
public static void main(String[] args) throws InterruptedException,
InvocationTargetException {
PassFailJFrame passFailJFrame = new PassFailJFrame("Large Icon " +
"Test Instructions", INSTRUCTIONS, 5, 12, 50);
SwingUtilities.invokeAndWait(ALTTABIconBeingErased::createAndShowGUI);
passFailJFrame.awaitAndCheck();
}
}

View file

@ -0,0 +1,120 @@
/*
* 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.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.Robot;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
* @test
* @key headful
* @bug 4159883
* @summary Adding/Removing a menu causes frame to unexpected small size
* @requires (os.family == "linux" | os.family == "windows")
*/
public class AddRemoveMenuBarTest_5 {
static Frame frame;
static MenuBar menu;
static Button btnAdd, btnRemove;
static Dimension oldSize;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
try {
EventQueue.invokeAndWait(AddRemoveMenuBarTest_5::initAndShowGui);
robot.waitForIdle();
robot.delay(500);
EventQueue.invokeAndWait(() -> {
oldSize = frame.getSize();
changeMenubar(true);
});
robot.waitForIdle();
robot.delay(500);
EventQueue.invokeAndWait(() -> {
checkSize();
changeMenubar(false);
});
robot.waitForIdle();
robot.delay(500);
EventQueue.invokeAndWait(AddRemoveMenuBarTest_5::checkSize);
} finally {
EventQueue.invokeAndWait(frame::dispose);
}
}
public static void initAndShowGui() {
frame = new Frame();
frame.setLocationRelativeTo(null);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("Frame size:" + frame.getSize().toString());
System.out.println("Button size:" + btnAdd.getSize().toString());
}
});
frame.add("West", btnAdd = new Button("TRY:ADD"));
frame.add("East", btnRemove = new Button("TRY:REMOVE"));
btnAdd.addActionListener((e) -> changeMenubar(true));
btnRemove.addActionListener((e) -> changeMenubar(false));
frame.setSize(500, 100);
frame.setVisible(true);
}
private static void changeMenubar(boolean enable) {
if (enable) {
menu = new MenuBar();
menu.add(new Menu("BAAAAAAAAAAAAAAA"));
menu.add(new Menu("BZZZZZZZZZZZZZZZ"));
menu.add(new Menu("BXXXXXXXXXXXXXXX"));
} else {
menu = null;
}
frame.setMenuBar(menu);
frame.invalidate();
frame.validate();
System.out.println("Frame size:" + frame.getSize().toString());
System.out.println("Button size:" + btnAdd.getSize().toString());
}
private static void checkSize() {
Dimension newSize = frame.getSize();
if (!oldSize.equals(newSize)) {
throw new RuntimeException("Frame size changed: old %s new %s"
.formatted(oldSize, newSize));
}
}
}

View file

@ -0,0 +1,120 @@
/*
* Copyright (c) 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.
*/
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.Panel;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/*
* @test
* @bug 8265586
* @key headful
* @summary Tests whether correct native frame insets are obtained
* for Resizable & Non-Resizable AWT Frame by checking the actual
* and expected/preferred frame sizes.
* @run main AwtFramePackTest
*/
public class AwtFramePackTest {
private static Frame frame;
private static Robot robot;
private static StringBuffer errorLog = new StringBuffer();
public static void main(String[] args) throws AWTException {
robot = new Robot();
robot.setAutoDelay(300);
// Resizable frame
createAWTFrame(true);
robot.waitForIdle();
robot.delay(500);
// Non-Resizable frame
createAWTFrame(false);
if (!errorLog.isEmpty()) {
throw new RuntimeException("Test failed due to the following" +
" one or more errors: \n" + errorLog);
}
}
private static void createAWTFrame(boolean isResizable) {
try {
frame = new Frame();
frame.setLayout(new BorderLayout());
Panel panel = new Panel();
panel.add(new Button("Panel Button B1"));
panel.add(new Button("Panel Button B2"));
frame.add(panel, BorderLayout.CENTER);
MenuBar mb = new MenuBar();
Menu m = new Menu("Menu");
mb.add(m);
frame.setMenuBar(mb);
frame.setResizable(isResizable);
frame.pack();
frame.setVisible(true);
robot.waitForIdle();
robot.delay(500);
Dimension actualFrameSize = frame.getSize();
Dimension expectedFrameSize = frame.getPreferredSize();
if (!actualFrameSize.equals(expectedFrameSize)) {
String frameType = isResizable ? "ResizableFrame" : "NonResizableFrame";
System.out.println("Expected frame size: " + expectedFrameSize);
System.out.println("Actual frame size: " + actualFrameSize);
saveScreenCapture(frameType + ".png");
errorLog.append(frameType + ": Expected and Actual frame size" +
" are different. frame.pack() does not work!! \n");
}
} finally {
if (frame != null) {
frame.dispose();
}
}
}
// for debugging purpose, saves screen capture when test fails.
private static void saveScreenCapture(String filename) {
BufferedImage image = robot.createScreenCapture(frame.getBounds());
try {
ImageIO.write(image,"png", new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright Amazon.com Inc. 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.Window;
/**
* @test
* @bug 8346952 8361521
* @summary Verifies no exception occurs when triggering updateCG()
* for an ownerless window.
* @key headful
*/
public final class BogusFocusableWindowState {
public static void main(String[] args) {
Window frame = new Window(null) {
@Override
public boolean getFocusableWindowState() {
removeNotify();
return true;
}
};
try {
frame.pack();
frame.setVisible(true);
} finally {
frame.dispose();
}
}
}

View file

@ -0,0 +1,142 @@
/*
* Copyright (c) 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 8206392
@requires (os.family == "mac")
@summary Cycle through frames using keyboard shortcut doesn't work on Mac
@compile CycleThroughFrameTest.java
@run main/manual CycleThroughFrameTest
*/
import java.awt.Frame;
import java.awt.Button;
import java.awt.TextArea;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class CycleThroughFrameTest {
public static final int maxFrames = 5;
private static JFrame[] frame;
private static Frame instructionFrame;
private static volatile boolean testContinueFlag = true;
private static final String TEST_INSTRUCTIONS =
" This is a manual test\n\n" +
" 1) Configure Keyboard shortcut if not done in your system:\n" +
" 2) Open System Preferences, go to -> Keyboard -> Shortcuts -> Keyboard\n" +
" 3) Enable 'Move focus to next window' if disabled\n" +
" 4) Enable 'Move focus to next window drawer' if disabled\n" +
" 5) Close System Preferences\n" +
" 5) Press COMMAND + ` keys to cycle through frames in forward order\n" +
" 6) Press FAIL if focus doesn't move to next frame\n" +
" 7) Press COMMAND + SHIFT + ` to cycle through frames in reverse order\n" +
" 8) Press FAIL if focus doesn't move to next frame in reverse order\n" +
" 9) Press PASS otherwise";
private static final String FAIL_MESSAGE = "Focus doesn't move to next frame";
public void showJFrame(int frameNumber) {
String title = "Frame " + frameNumber;
frame[frameNumber] = new JFrame(title);
frame[frameNumber].setSize(300, 200);
frame[frameNumber].setLocation(50+(frameNumber*20), 50+(frameNumber*20));
frame[frameNumber].setVisible(true);
}
private void createAndShowFrame() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
frame = new JFrame[maxFrames];
for (int i = 0; i < maxFrames; i++) {
showJFrame(i);
}
}
});
}
public void createAndShowInstructionFrame() {
Button passButton = new Button("Pass");
passButton.setEnabled(true);
Button failButton = new Button("Fail");
failButton.setEnabled(true);
TextArea instructions = new TextArea(12, 70);
instructions.setText(TEST_INSTRUCTIONS);
instructionFrame = new Frame("Test Instructions");
instructionFrame.add(passButton);
instructionFrame.add(failButton);
instructionFrame.add(instructions);
instructionFrame.setSize(200,200);
instructionFrame.setLayout(new FlowLayout());
instructionFrame.pack();
instructionFrame.setVisible(true);
passButton.addActionListener(ae -> {
dispose();
testContinueFlag = false;
});
failButton.addActionListener(ae -> {
dispose();
testContinueFlag = false;
throw new RuntimeException(FAIL_MESSAGE);
});
}
private static void dispose() {
for (int i = 0; i < maxFrames; i++) {
frame[i].dispose();
}
instructionFrame.dispose();
}
public static void main(String[] args) throws Exception {
CycleThroughFrameTest testObj = new CycleThroughFrameTest();
testObj.createAndShowFrame();
testObj.createAndShowInstructionFrame();
final int sleepTime = 300000;
final int sleepLoopTime = 1000;
int remainingSleepTime = sleepTime;
while(remainingSleepTime > 0 && testContinueFlag) {
Thread.sleep(sleepLoopTime);
remainingSleepTime -= sleepLoopTime;
}
if (testContinueFlag) {
dispose();
throw new RuntimeException("Timed out after " +
(sleepTime - remainingSleepTime) / 1000 + " seconds");
}
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2011, 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.*;
/*
* @test
* @key headful
* @summary An attempt to set non-trivial background, shape, or translucency
* to a decorated toplevel should end with an exception.
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library /lib/client
* @build ExtendedRobot
* @run main DecoratedExceptions
*/
public class DecoratedExceptions {
public static void main(String args[]) throws Exception{
ExtendedRobot robot = new ExtendedRobot();
Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(() -> {
Frame frame = new Frame("Frame");
frame.setBounds(50,50,400,200);
try {
frame.setOpacity(0.5f);
throw new RuntimeException("No exception when Opacity set to a decorated Frame");
}catch(IllegalComponentStateException e) {
}
try {
frame.setShape(new Rectangle(50,50,400,200));
throw new RuntimeException("No exception when Shape set to a decorated Frame");
}catch(IllegalComponentStateException e) {
}
try {
frame.setBackground(new Color(50, 50, 50, 100));
throw new RuntimeException("No exception when Alpha background set to a decorated Frame");
}catch(IllegalComponentStateException e) {
}
frame.setVisible(true);
Dialog dialog = new Dialog( frame );
try {
dialog.setOpacity(0.5f);
throw new RuntimeException("No exception when Opacity set to a decorated Dialog");
}catch(IllegalComponentStateException e) {
}
try {
dialog.setShape(new Rectangle(50,50,400,200));
throw new RuntimeException("No exception when Shape set to a decorated Dialog");
}catch(IllegalComponentStateException e) {
}
try {
dialog.setBackground(new Color(50, 50, 50, 100));
throw new RuntimeException("No exception when Alpha background set to a decorated Dialog");
}catch(IllegalComponentStateException e) {
}
dialog.setVisible(true);
});
robot.waitForIdle(1000);
}
}

View file

@ -0,0 +1,82 @@
/*
* 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 8165619
* @summary Frame is not repainted if created in state=MAXIMIZED_BOTH on Unity
* @run main DecoratedFrameInsetsTest
*/
import java.awt.*;
public class DecoratedFrameInsetsTest {
static Robot robot;
private static Insets expectedInsets;
public static void main(String[] args) throws Exception {
robot = new Robot();
expectedInsets = getExpectedInsets();
System.out.println("Normal state insets: " + expectedInsets);
testState(Frame.MAXIMIZED_BOTH);
testState(Frame.ICONIFIED);
testState(Frame.MAXIMIZED_HORIZ);
testState(Frame.MAXIMIZED_VERT);
}
private static Insets getExpectedInsets() {
Frame frame = new Frame();
frame.setVisible(true);
robot.waitForIdle();
robot.delay(200);
Insets expectedInsets = frame.getInsets();
frame.dispose();
return expectedInsets;
}
static void testState(int state) {
Frame frame = new Frame();
if( Toolkit.getDefaultToolkit().isFrameStateSupported(state)) {
frame.setBounds(150, 150, 200, 200);
frame.setExtendedState(state);
frame.setVisible(true);
robot.waitForIdle();
robot.delay(200);
System.out.println("State " + state +
" insets: " + frame.getInsets());
frame.setExtendedState(Frame.NORMAL);
frame.toFront();
robot.waitForIdle();
robot.delay(200);
Insets insets = frame.getInsets();
frame.dispose();
System.out.println("State " + state +
" back to normal insets: " + insets);
if(!expectedInsets.equals(insets)) {
throw new RuntimeException("Insets are wrong " + insets);
}
}
}
}

View file

@ -0,0 +1,67 @@
/*
* 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.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.util.List;
/*
* @test
* @bug 4240766 8259023
* @summary Frame Icon is wrong - should be Coffee Cup or Duke image icon
* @requires (os.family == "windows")
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual DefaultFrameIconTest
*/
public class DefaultFrameIconTest {
private static final String INSTRUCTIONS = """
You should see a dialog and a frame.
If both have Coffee Cup or Duke image icon in the upper left corner,
the test passes, otherwise it fails.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("DefaultFrameIconTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(DefaultFrameIconTest::createAndShowUI)
.positionTestUIRightRow()
.build()
.awaitAndCheck();
}
private static List<Window> createAndShowUI() {
Frame testFrame = new Frame("Frame DefaultFrameIconTest");
Dialog testDialog = new Dialog(testFrame, "Dialog DefaultFrameIconTest");
testDialog.setSize(250, 100);
testFrame.setSize(250, 100);
return List.of(testFrame, testDialog);
}
}

View file

@ -0,0 +1,66 @@
/*
* 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.Label;
/*
* @test
* @bug 4085599
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @summary Test default location for frame
* @run main/manual DefaultLocationTest
*/
public class DefaultLocationTest {
private static Frame f;
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
A small frame containing the label 'Hello World' should
appear in the upper left hand corner of the screen. The
exact location is dependent upon the window manager.
On Linux and Mac machines, the default location for frame
is below the taskbar or close to top-left corner.
Upon test completion, click Pass or Fail appropriately.""";
PassFailJFrame passFailJFrame = new PassFailJFrame("DefaultLocationTest " +
" Instructions", INSTRUCTIONS, 5, 10, 40);
EventQueue.invokeAndWait(DefaultLocationTest::createAndShowUI);
passFailJFrame.awaitAndCheck();
}
private static void createAndShowUI() {
f = new Frame("DefaultLocation");
f.add("Center", new Label("Hello World"));
f.pack();
PassFailJFrame.addTestWindow(f);
PassFailJFrame.positionTestWindow(
null, PassFailJFrame.Position.HORIZONTAL);
f.setVisible(true);
}
}

View file

@ -0,0 +1,57 @@
/*
* 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.Frame;
/*
* @test 4033151
* @summary Test that frame default size is minimum possible size
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual DefaultSizeTest
*/
public class DefaultSizeTest {
private static final String INSTRUCTIONS = """
An empty frame is created.
It should be located to the right of this window
and should be the minimum size allowed by the window manager.
For any WM, the frame should be very small.
If the frame is not large, click Pass or Fail otherwise.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("DefaultSizeTest Instructions Frame")
.instructions(INSTRUCTIONS)
.testTimeOut(5)
.rows(10)
.columns(45)
.testUI(() -> new Frame("DefaultSize"))
.screenCapture()
.build()
.awaitAndCheck();
}
}

View file

@ -0,0 +1,140 @@
/*
* 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.
*/
/*
* DeiconifyClipTest.java
*
* summary:
*
* What happens is that we call AwtWindow::UpdateInsets when
* processing WM_NCCALCSIZE delivered on programmatic deiconification.
* At this point IsIconic returns false (so UpdateInsets proceeds),
* but the rect sizes still seems to be those weird of the iconic
* state. Based on them we compute insets with top = left = 0 (and
* bottom and right that are completely bogus) and pass them to
* PaintUpdateRgn which results in incorrect clip origin. Immediately
* after that we do UpdateInsets again during WM_SIZE processing and
* get real values.
*/
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Insets;
/*
* @test
* @bug 4792958
* @summary Incorrect clip region after programmatic restore
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual DeiconifyClipTest
*/
public class DeiconifyClipTest {
private static final String INSTRUCTIONS = """
This test creates a frame that is automatically iconified/deiconified
in a cycle.
The test FAILS if after deiconfication the frame has a greyed-out area
in the lower-right corner.
If the frame contents is drawn completely - the test PASSES.
Press PASS or FAIL button accordingly.
""";
static TestFrame testFrame;
static volatile boolean shouldContinue = true;
public static void main(String[] args) throws Exception {
PassFailJFrame passFailJFrame = PassFailJFrame.builder()
.title("DeiconifyClipTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(DeiconifyClipTest::createAndShowUI)
.build();
try {
runThread();
} finally {
passFailJFrame.awaitAndCheck();
shouldContinue = false;
}
}
private static void runThread() {
new Thread(() -> {
for (int i = 0; i < 1000 && shouldContinue; ++i) {
try {
Thread.sleep(3000);
SwingUtilities.invokeAndWait(() -> {
if ((testFrame.getExtendedState() & Frame.ICONIFIED)
!= 0) {
testFrame.setExtendedState(Frame.NORMAL);
} else {
testFrame.setState(Frame.ICONIFIED);
}
});
} catch (Exception ignored) {
}
}
}).start();
}
static Frame createAndShowUI() {
testFrame = new TestFrame();
testFrame.getContentPane().setLayout(new BoxLayout(testFrame.getContentPane(),
BoxLayout.Y_AXIS));
testFrame.getContentPane().setBackground(Color.yellow);
testFrame.setSize(300, 300);
return testFrame;
}
static class TestFrame extends JFrame {
public TestFrame() {
super("DeiconifyClipTest");
}
// make it more visible if the clip is wrong.
public void paint(Graphics g) {
Insets b = getInsets();
Dimension d = getSize();
int x = b.left;
int y = b.top;
int w = d.width - x - b.right;
int h = d.height - y - b.bottom;
g.setColor(Color.white);
g.fillRect(0, 0, d.width, d.height);
g.setColor(Color.green);
g.drawRect(x, y, w-1, h-1);
g.drawLine(x, y, x+w, y+h);
g.drawLine(x, y+h, x+w, y);
}
}
}

View file

@ -0,0 +1,99 @@
/*
* Copyright (c) 2004, 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.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Window;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/*
* @test
* @bug 5062118
* @key headful
* @summary Disabling of a parent should not disable Window.
* @run main DisabledParentOfToplevel
*/
public class DisabledParentOfToplevel {
private static Button okBtn;
private static Window ww;
private static Frame parentFrame;
private static volatile Point p;
private static volatile Dimension d;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(100);
try {
EventQueue.invokeAndWait(() -> {
createAndShowUI();
});
robot.delay(1000);
EventQueue.invokeAndWait(() -> {
p = okBtn.getLocationOnScreen();
d = okBtn.getSize();
});
robot.mouseMove(p.x + d.width / 2, p.x + d.height / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(500);
if (ww.isVisible()) {
throw new RuntimeException("Window is visible but should be hidden: failure.");
}
} finally {
EventQueue.invokeAndWait(() -> {
if (parentFrame != null) {
parentFrame.dispose();
}
});
}
}
private static void createAndShowUI() {
parentFrame = new Frame("parentFrame");
parentFrame.setSize(100, 100);
parentFrame.setEnabled(false);
ww = new Window(parentFrame);
ww.setLayout(new BorderLayout());
okBtn = new Button("Click to Close Me");
ww.add(okBtn);
ww.setSize(250, 250);
ww.setLocation(110, 110);
okBtn.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
System.out.println("Pressed: close");
ww.setVisible(false);
}
});
parentFrame.setVisible(true);
ww.setVisible(true);
okBtn.requestFocus();
}
}

View file

@ -0,0 +1,188 @@
/*
* Copyright (c) 2014, 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.Canvas;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Label;
import java.awt.List;
import java.awt.Point;
import java.awt.Scrollbar;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.Frame;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.Vector;
/*
* @test
* @key headful
* @summary Display a dialog with a parent, the dialog contains all awt components
* added to it & each components are setted with different cursors types.
* Dispose the parent & collect GC. Garbage collection should happen
* @library /lib/client
* @build ExtendedRobot
* @run main/othervm -Xmx20m DisposeParentGC
*/
public class DisposeParentGC {
Frame parentFrame;
ExtendedRobot robot;
ArrayList<PhantomReference<Dialog>> refs = new ArrayList<PhantomReference<Dialog>>();
ReferenceQueue<Dialog> que = new ReferenceQueue<>();
public static void main(String []args) throws Exception {
new DisposeParentGC().doTest();
}
DisposeParentGC() throws Exception {
robot = new ExtendedRobot();
EventQueue.invokeAndWait(this::initGui);
}
void initGui(){
parentFrame = new Frame("Parent Frame");
parentFrame.setLayout(new FlowLayout());
for (int i = 1; i <= 3; i++)
createDialog(i);
parentFrame.setLocation(250, 20);
parentFrame.pack();
parentFrame.setVisible(true);
}
public void doTest() throws Exception{
robot.waitForIdle();
parentFrame.dispose();
robot.waitForIdle();
Vector garbage = new Vector();
while (true) {
try {
garbage.add(new byte[1000]);
} catch (OutOfMemoryError er) {
break;
}
}
garbage = null;
int count = 1;
for (; count <= 3; count++)
if(que.remove(5000) == null)
break;
if (count < 3)
throw new RuntimeException("Count = "+count+". GC didn't collect the objects after the parent is disposed!");
}
public void createDialog(int number) {
Dialog child = new Dialog(parentFrame);
child.setTitle("Dialog " + number);
child.setLayout(new FlowLayout());
child.setLocation(20, 140 * number);
Button button = new Button("Press Me") ;
TextArea textArea = new TextArea(5, 5);
TextField textField = new TextField(10);
Choice choice = new Choice();
choice.add("One");
choice.add("Two");
choice.add("Three");
choice.add("Four");
choice.add("Five");
List list = new List();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
Checkbox checkBox = new Checkbox("Hai");
Scrollbar scrollBar = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 200);
CheckboxGroup checkboxGroup = new CheckboxGroup();
Checkbox radioButton = new Checkbox("Hello", true, checkboxGroup);
Canvas canvas = new Canvas();
Label label = new Label("I am label!");
Cursor customCursor = null;
child.setLayout(new FlowLayout());
canvas.setSize(100, 100);
canvas.setBackground(Color.red);
button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
label.setCursor(new Cursor(Cursor.TEXT_CURSOR));
choice.setCursor(new Cursor(Cursor.WAIT_CURSOR));
list.setCursor(new Cursor(Cursor.HAND_CURSOR));
checkBox.setCursor(new Cursor(Cursor.MOVE_CURSOR));
radioButton.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
scrollBar.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
canvas.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR));
textField.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
/* create a custom cursor */
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getBestCursorSize(32, 32);
int color = toolkit.getMaximumCursorColors();
if (!d.equals(new Dimension(0,0)) && color != 0) {
customCursor = toolkit.createCustomCursor(
new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB),
new Point(10, 10), "custom cursor.");
}
else {
System.err.println("Platform doesn't support to create a custom cursor.");
}
textArea.setCursor(customCursor);
child.add(label);
child.add(button);
child.add(choice);
child.add(list);
child.add(checkBox);
child.add(radioButton);
child.add(scrollBar);
child.add(canvas);
child.add(textArea);
child.add(textField);
child.add(button);
child.revalidate();
child.pack();
child.setVisible(true);
refs.add(new PhantomReference<Dialog>(child, que));
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2014, 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 4051487 4145670
@summary Tests that disposing of an empty Frame or a Frame with a MenuBar
while it is being created does not crash the VM.
@run main/timeout=7200 DisposeStressTest
*/
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
public class DisposeStressTest {
public static void main(final String[] args) {
for (int i = 0; i < 1000; i++) {
Frame f = new Frame();
f.setBounds(10, 10, 10, 10);
f.show();
f.dispose();
Frame f2 = new Frame();
f2.setBounds(10, 10, 100, 100);
MenuBar bar = new MenuBar();
Menu menu = new Menu();
menu.add(new MenuItem("foo"));
bar.add(menu);
f2.setMenuBar(bar);
f2.show();
f2.dispose();
}
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 1998, 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.
*/
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/*
* @test
* @key headful
* @bug 4127271
* @summary Tests that disposing of a Frame with MenuBar removes all traces
* of the Frame from the screen.
*/
public class DisposeTest {
private static Frame backgroundFrame;
private static Frame testedFrame;
private static final int PIXEL_OFFSET = 4;
private static final Rectangle backgroundFrameBounds =
new Rectangle(100, 100, 200, 200);
private static final Rectangle testedFrameBounds =
new Rectangle(150, 150, 100, 100);
private static Robot robot;
public static void main(String[] args) throws Exception {
robot = new Robot();
try {
EventQueue.invokeAndWait(DisposeTest::initAndShowGui);
robot.waitForIdle();
robot.delay(500);
EventQueue.invokeAndWait(testedFrame::dispose);
robot.waitForIdle();
robot.delay(500);
test();
} finally {
EventQueue.invokeAndWait(() -> {
backgroundFrame.dispose();
testedFrame.dispose();
});
}
}
private static void test() {
BufferedImage bi = robot.createScreenCapture(backgroundFrameBounds);
int redPix = Color.RED.getRGB();
for (int x = PIXEL_OFFSET; x < bi.getWidth() - PIXEL_OFFSET; x++) {
for (int y = PIXEL_OFFSET; y < bi.getHeight() - PIXEL_OFFSET; y++) {
if (bi.getRGB(x, y) != redPix) {
try {
ImageIO.write(bi, "png",
new File("failure.png"));
} catch (IOException ignored) {}
throw new RuntimeException("Test failed");
}
}
}
}
private static void initAndShowGui() {
backgroundFrame = new Frame("DisposeTest background");
backgroundFrame.setUndecorated(true);
backgroundFrame.setBackground(Color.RED);
backgroundFrame.setBounds(backgroundFrameBounds);
backgroundFrame.setVisible(true);
testedFrame = new UglyFrame();
}
static class UglyFrame extends Frame {
public UglyFrame() {
super("DisposeTest");
MenuBar mb = new MenuBar();
Menu m = new Menu("menu");
mb.add(m);
setMenuBar(mb);
setBounds(testedFrameBounds);
setVisible(true);
}
}
}

View file

@ -0,0 +1,246 @@
/*
* 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 6500477
@summary Tests whether DynamicLayout is really off
@author anthony.petrov@...: area=awt.toplevel
@library ../../regtesthelpers
@build Util
@run main DynamicLayout
*/
/**
* DynamicLayout.java
*
* summary: tests whether DynamicLayout is really off
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import test.java.awt.regtesthelpers.Util;
public class DynamicLayout
{
//*** test-writer defined static variables go here ***
private static void init() {
//*** Create instructions for the user here ***
// Turn off the dynamic layouting
Toolkit.getDefaultToolkit().setDynamicLayout(false);
System.out.println("isDynamicLayoutActive(): " + Toolkit.getDefaultToolkit().isDynamicLayoutActive());
final Frame frame = new Frame("Test Frame");
// Add some components to check their position later
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
JTextField jf = new JTextField (10);
JTextField jf1 = new JTextField (10);
JButton jb = new JButton("Test");
panel.add(jf);
panel.add(jf1);
panel.add(jb);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
Robot robot = Util.createRobot();
robot.setAutoDelay(20);
// To be sure the window is shown and packed
Util.waitForIdle(robot);
// The initial JTextField position. While resizing the position supposed to stay the same.
Point loc1 = jf1.getLocation();
System.out.println("The initial position of the JTextField is: " + loc1);
Insets insets = frame.getInsets();
if (insets.right == 0 || insets.bottom == 0) {
System.out.println("The test environment must have non-zero right & bottom insets! The current insets are: " + insets);
pass();
return;
}
// Let's move the mouse pointer to the bottom-right coner of the frame (the "size-grip")
Rectangle bounds = frame.getBounds();
robot.mouseMove(bounds.x + bounds.width - 1, bounds.y + bounds.height - 1);
// ... and start resizing
robot.mousePress( InputEvent.BUTTON1_MASK );
robot.mouseMove(bounds.x + bounds.width + 20, bounds.y + bounds.height + 15);
Util.waitForIdle(robot);
// And check whether the location of the JTextField has changed.
Point loc2 = jf1.getLocation();
System.out.println("Position of the JTextField while resizing is: " + loc2);
robot.mouseRelease( InputEvent.BUTTON1_MASK );
// Location of the component changed if relayouting has happened.
if (!loc2.equals(loc1)) {
fail("Location of a component has been changed.");
return;
}
DynamicLayout.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 DynamicLayout
//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,99 @@
/*
* 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.Color;
import java.awt.Dimension;
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
* @bug 4237529
* @key headful
* @summary Test repainting of an empty frame
* @run main EmptyFrameTest
*/
public class EmptyFrameTest {
private static Frame f;
private static Robot robot;
private static volatile Point p;
private static volatile Dimension d;
private static final int TOLERANCE = 5;
public static void main(String[] args) throws Exception {
robot = new Robot();
robot.setAutoDelay(100);
try {
EventQueue.invokeAndWait(() -> {
createAndShowUI();
});
robot.delay(1000);
f.setSize(50, 50);
robot.delay(500);
EventQueue.invokeAndWait(() -> {
p = f.getLocation();
d = f.getSize();
});
Rectangle rect = new Rectangle(p, d);
BufferedImage img = robot.createScreenCapture(rect);
if (chkImgBackgroundColor(img)) {
try {
ImageIO.write(img, "png", new File("Frame.png"));
} catch (IOException ignored) {}
throw new RuntimeException("Frame doesn't repaint itself on resize");
}
} finally {
EventQueue.invokeAndWait(() -> {
if (f != null) {
f.dispose();
}
});
}
}
private static void createAndShowUI() {
f = new Frame("EmptyFrameTest");
f.setUndecorated(true);
f.setBackground(Color.RED);
f.setVisible(true);
}
private static boolean chkImgBackgroundColor(BufferedImage img) {
for (int x = 1; x < img.getWidth() - 1; ++x) {
for (int y = 1; y < img.getHeight() - 1; ++y) {
Color c = new Color(img.getRGB(x, y));
if ((c.getRed() - Color.RED.getRed()) > TOLERANCE) {
return true;
}
}
}
return false;
}
}

View file

@ -0,0 +1,108 @@
/*
* Copyright (c) 2014, 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 8032078
* @summary Frame.setExtendedState throws RuntimeException, if
* windowState=ICONIFIED|MAXIMIZED_BOTH, on OS X
* @author Anton Litvinov
*/
import java.awt.*;
public class ExceptionOnSetExtendedStateTest {
private static final int[] frameStates = { Frame.NORMAL, Frame.ICONIFIED, Frame.MAXIMIZED_BOTH };
private static boolean validatePlatform() {
String osName = System.getProperty("os.name");
if (osName == null) {
throw new RuntimeException("Name of the current OS could not be retrieved.");
}
return osName.startsWith("Mac");
}
private static void testStateChange(int oldState, int newState, boolean decoratedFrame) {
System.out.println(String.format(
"testStateChange: oldState='%d', newState='%d', decoratedFrame='%b'",
oldState, newState, decoratedFrame));
Frame frame = new Frame("ExceptionOnSetExtendedStateTest");
frame.setSize(200, 200);
frame.setUndecorated(!decoratedFrame);
frame.setVisible(true);
try {
Robot robot = new Robot();
robot.waitForIdle();
}catch(Exception ex) {
ex.printStackTrace();
throw new RuntimeException("Unexpected failure");
}
frame.setExtendedState(oldState);
sleep(1000);
frame.setExtendedState(newState);
boolean stateWasNotChanged = true;
int currentState = 0;
for (int i = 0; (i < 3) && stateWasNotChanged; i++) {
sleep(1000);
currentState = frame.getExtendedState();
if ((currentState == newState) ||
(((newState & Frame.ICONIFIED) != 0) && ((currentState & Frame.ICONIFIED) != 0))) {
stateWasNotChanged = false;
}
}
frame.dispose();
if (stateWasNotChanged) {
throw new RuntimeException(String.format(
"Frame state was not changed. currentState='%d'", currentState));
}
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (!validatePlatform()) {
System.out.println("This test is only for OS X.");
return;
}
// Verify that changing states of decorated/undecorated frame to/from supported states
// and the state bit mask ICONIFIED | MAXIMIZED_BOTH does not raise RuntimeException.
for (int i = 0; i < frameStates.length; i++) {
testStateChange(frameStates[i], Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, true);
testStateChange(frameStates[i], Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, false);
testStateChange(Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, frameStates[i], true);
testStateChange(Frame.ICONIFIED | Frame.MAXIMIZED_BOTH, frameStates[i], false);
}
}
}

View file

@ -0,0 +1,151 @@
/*
* 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.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.Window;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
* @test
* @bug 4140293
* @summary Tests that focus is returned to the correct Component when a Frame
* is reactivated.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FocusTest
*/
public class FocusTest {
private static final String INSTRUCTIONS = """
Click on the bottom rectangle. Move the mouse slightly.
A focus rectangle should appear around the bottom rectangle.
Now, deactivate the window and then reactivate it.
(You would click on the caption bar of another window,
and then on the caption bar of the FocusTest Frame.)
If the focus rectangle appears again, the test passes.
If it does not appear, or appears around the top rectangle,
the test fails.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FocusTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.logArea(6)
.testUI(FocusTest::createAndShowUI)
.build()
.awaitAndCheck();
}
private static Window createAndShowUI() {
Frame frame = new Frame("FocusTest");
frame.add(new FocusTestPanel());
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
frame.validate();
return frame;
}
private static class FocusTestPanel extends Panel {
PassiveClient pc1 = new PassiveClient("pc1");
PassiveClient pc2 = new PassiveClient("pc2");
public FocusTestPanel() {
super();
setLayout(new GridLayout(2, 1, 10, 10));
add(pc1);
add(pc2);
}
}
private static class PassiveClient extends Canvas implements FocusListener {
boolean haveFocus = false;
final String name;
PassiveClient(String name) {
super();
this.name = name;
setSize(400, 100);
setBackground(Color.cyan);
setVisible(true);
setEnabled(true);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
requestFocus();
}
});
addFocusListener(this);
}
public void paint(Graphics g) {
g.setColor(getBackground());
Dimension size = getSize();
g.fillRect(0, 0, size.width, size.height);
if (haveFocus) {
g.setColor(Color.black);
g.drawRect(0, 0, size.width - 1, size.height - 1);
g.drawRect(1, 1, size.width - 3, size.height - 3);
}
g.setColor(getForeground());
}
public void focusGained(FocusEvent event) {
haveFocus = true;
paint(getGraphics());
PassFailJFrame.log("<<<< %s Got focus!! %s>>>>".formatted(this, event));
}
public void focusLost(FocusEvent event) {
haveFocus = false;
paint(getGraphics());
PassFailJFrame.log("<<<< %s Lost focus!! %s>>>>".formatted(this, event));
}
@Override
public String toString() {
return "PassiveClient " + name;
}
}
}

View file

@ -0,0 +1,82 @@
/*
* 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.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Point;
/*
* @test
* @bug 4340727
* @summary Tests that undecorated property is set correctly
* when Frames and Dialogs are mixed.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameDialogMixedTest
*/
public class FrameDialogMixedTest {
private static final int SIZE = 100;
private static final String INSTRUCTIONS = """
When the test starts, a RED UNDECORATED Frame is seen.
Click on "Create Dialog" button, you should see a GREEN UNDECORATED Dialog.
If both the frame and the dialog are undecorated press PASS otherwise FAIL.""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("Undecorated Frame & Dialog Test Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(40)
.testUI(FrameDialogMixedTest::createUI)
.build()
.awaitAndCheck();
}
private static Frame createUI() {
Frame frame = new Frame("Undecorated Frame");
frame.setSize(SIZE, SIZE);
frame.setBackground(Color.RED);
frame.setUndecorated(true);
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
Button button = new Button("Create Dialog");
button.addActionListener(e -> {
Dialog dialog = new Dialog(frame);
Point frameLoc = frame.getLocationOnScreen();
dialog.setBounds(frameLoc.x + frame.getSize().width + 5,
frameLoc.y,
SIZE, SIZE);
dialog.setBackground(Color.GREEN);
dialog.setUndecorated(true);
dialog.setVisible(true);
});
frame.add(button);
return frame;
}
}

View file

@ -0,0 +1,70 @@
/*
* 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.Button;
import java.awt.Frame;
/*
* @test
* @bug 4173503
* @library /java/awt/regtesthelpers
* @requires (os.family == "windows")
* @build PassFailJFrame
* @summary Tests that frame layout is performed when frame is maximized from taskbar
* @run main/manual FrameLayoutTest
*/
public class FrameLayoutTest {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
Right-click on the taskbar button for this test. In the menu appeared,
choose Maximize. The frame will be maximized. Check if buttons inside
the frame are laid out properly, i.e. they occupy the frame entirely.
If so, test passes. If buttons occupy small rectangle in the top left
corner, test fails.""";
PassFailJFrame.builder()
.title("Frame's Layout Test Instruction")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(40)
.testUI(FrameLayoutTest::createUI)
.build()
.awaitAndCheck();
}
private static Frame createUI() {
Frame f = new Frame("Maximize Test");
f.add(new Button("North"), BorderLayout.NORTH);
f.add(new Button("South"), BorderLayout.SOUTH);
f.add(new Button("East"), BorderLayout.EAST);
f.add(new Button("West"), BorderLayout.WEST);
f.add(new Button("Cent"), BorderLayout.CENTER);
f.pack();
f.setState(Frame.ICONIFIED);
return f;
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
@test
@key headful
@bug 6895647
@summary X11 Frame locations should be what we set them to
@author anthony.petrov@oracle.com: area=awt.toplevel
@run main FrameLocation
*/
import java.awt.*;
public class FrameLocation {
private static final int X = 250;
private static final int Y = 250;
public static void main(String[] args) {
Frame f = new Frame("test");
f.setBounds(X, Y, 250, 250); // the size doesn't matter
f.setVisible(true);
for (int i = 0; i < 10; i++) {
// 2 seconds must be enough for the WM to show the window
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
// Check the location
int x = f.getX();
int y = f.getY();
if (x != X || y != Y) {
throw new RuntimeException("The frame location is wrong! Current: " + x + ", " + y + "; expected: " + X + ", " + Y);
}
// Emulate what happens when setGraphicsConfiguration() is called
synchronized (f.getTreeLock()) {
f.removeNotify();
f.addNotify();
}
}
f.dispose();
}
}

View file

@ -0,0 +1,62 @@
/*
* 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.Frame;
import java.awt.Label;
/*
* @test
* @bug 4106068
* @summary Test to verify maximized window is not too big
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameMaximizedTest
*/
public class FrameMaximizedTest {
public static void main (String[] args) throws Exception {
String INSTRUCTIONS = """
Maximize the frame window. Check that the right and bottom edges of the
window are not off the edge of the screen. If they are not, the test
is successful and the bug is fixed.
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows(4)
.columns(40)
.testUI(new TestFrame())
.build()
.awaitAndCheck();
}
}
class TestFrame extends Frame {
public TestFrame() {
setTitle("FrameMaximizedTest");
setSize(500, 300);
add("North", new Label("Maximize me and check if my " +
"bottom and right edge are on screen."));
}
}

View file

@ -0,0 +1,99 @@
/*
* 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.Frame;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.ScrollPane;
import java.awt.Window;
import java.util.List;
/*
* @test
* @bug 4084766
* @summary Test for bug(s): 4084766
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameMenuPackTest
*/
public class FrameMenuPackTest {
private static final String INSTRUCTIONS = """
Check that both frames that appear are properly packed with
the scrollpane visible.
""";
public static void main(String[] argv) throws Exception {
PassFailJFrame.builder()
.title("FrameMenuPackTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(FrameMenuPackTest::createAndShowUI)
.positionTestUIRightRow()
.build()
.awaitAndCheck();
}
private static List<Window> createAndShowUI() {
// Frame without menu, packs correctly
PackedFrame f1 = new PackedFrame(false);
f1.pack();
// Frame with menu, doesn't pack right
PackedFrame f2 = new PackedFrame(true);
f2.pack();
return List.of(f1, f2);
}
private static class PackedFrame extends Frame {
public PackedFrame(boolean withMenu) {
super("PackedFrame");
MenuBar menubar;
Menu fileMenu;
MenuItem foo;
ScrollPane sp;
sp = new ScrollPane();
sp.add(new Label("Label in ScrollPane"));
System.out.println(sp.getMinimumSize());
this.setLayout(new BorderLayout());
this.add(sp, "Center");
this.add(new Label("Label in Frame"), "South");
if (withMenu) {
menubar = new MenuBar();
fileMenu = new Menu("File");
foo = new MenuItem("foo");
fileMenu.add(foo);
menubar.add(fileMenu);
this.setMenuBar(menubar);
}
}
}
}

View file

@ -0,0 +1,59 @@
/*
* 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.Frame;
/*
* @test
* @bug 4172782
* @summary Test if non-resizable frame is minimizable
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameMinimizeTest
*/
public class FrameMinimizeTest {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
When the blank FrameMinimizeTest frame is shown, verify that
1. It is not resizable;
2. It is minimizable.
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows(4)
.columns(35)
.testUI(FrameMinimizeTest::initialize)
.build()
.awaitAndCheck();
}
public static Frame initialize() {
Frame f = new Frame("FrameMinimizeTest");
f.setSize(200, 200);
f.setResizable(false);
return f;
}
}

View file

@ -0,0 +1,91 @@
/*
* 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.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
/*
* @test
* @bug 4023385
* @summary resizing a frame causes too many repaints
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FramePaintTest
*/
public class FramePaintTest {
private static final String INSTRUCTIONS = """
You should see a Frame titled "Repaint Test", filled with colored blocks.
Resize the frame several times, both inward as well as outward.
The blocks should move to fill the window without any flashes or
glitches which ensures that repaint is not done excessively
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FramePaintTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(ResizeLW::new)
.build()
.awaitAndCheck();
}
static class ResizeLW extends Frame {
public ResizeLW() {
super("Repaint Test");
setBackground(Color.red);
setLayout(new FlowLayout());
setSize(300, 300);
for (int i = 0; i < 10; i++) {
add(new ColorComp(Color.blue));
add(new ColorComp(Color.green));
}
}
private static class ColorComp extends Component {
public ColorComp(Color c) {
super();
setBackground(c);
}
public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}
}
}

View file

@ -0,0 +1,165 @@
/*
* 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.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
* @test
* @key headful
* @summary Test dynamically changing frame component visibility and repacking
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameRepackTest
*/
public class FrameRepackTest {
private static final String INSTRUCTIONS = """
There is a green frame with a menubar.
The menubar has one menu, labelled 'Flip'.
The menu has two items, labelled 'visible' and 'not visible'.
The frame also contains a red panel that contains two line labels,
'This panel is always displayed' and 'it is a test'.
If you select the menu item 'Flip->visible', then another panel is
added below the red panel.
The added panel is blue and has yellow horizontal and vertical scrollbars.
If you select menu item 'Flip->not visible', the second panel
is removed and the frame appears as it did originally.
You can repeatedly add and remove the second panel in this way.
After such an addition or removal, the frame's location on the screen
should not change, while the size changes to accommodate
either just the red panel or both the red and the blue panels.
If you resize the frame larger, the red panel remains at the
top of the frame with its height fixed and its width adjusted
to the width of the frame.
Similarly, if it is present, the blue panel and its yellow scroolbars
remain at the bottom of the frame with fixed height and width adjusted
to the size of the frame. But selecting 'visible' or 'not visible'
repacks the frame, thereby adjusting its size tightly to its panel(s).
Upon test completion, click Pass or Fail appropriately.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameRepackTest Instructions")
.instructions(INSTRUCTIONS)
.testTimeOut(5)
.rows(30)
.columns(45)
.testUI(FrameRepack::new)
.build()
.awaitAndCheck();
}
}
class FrameRepack extends Frame implements ActionListener {
Panel south;
public FrameRepack() {
super("FrameRepack");
// create the menubar
MenuBar menubar = new MenuBar();
this.setMenuBar(menubar);
// create the options
Menu flip = new Menu("Flip");
MenuItem mi;
mi = new MenuItem("visible");
mi.addActionListener(this);
flip.add(mi);
mi = new MenuItem("not visible");
mi.addActionListener(this);
flip.add(mi);
menubar.add(flip);
setLayout(new BorderLayout(2, 2));
setBackground(Color.green);
// north panel is always displayed
Panel north = new Panel();
north.setBackground(Color.red);
north.setLayout(new BorderLayout(2, 2));
north.add("North", new Label("This panel is always displayed"));
north.add("Center", new Label("it is a test"));
north.setSize(200, 200);
add("North", north);
// south panel can be visible or not...
// The problem seems to occur when I put this panel not visible
south = new Panel();
south.setBackground(Color.white);
south.setLayout(new BorderLayout());
ScrollPane scroller = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
scroller.setBackground(Color.yellow);
Panel pan1 = new Panel();
pan1.setBackground(Color.blue);
pan1.setLayout(new BorderLayout());
pan1.setSize(400, 150);
scroller.add("Center", pan1);
south.add("South", scroller);
add("South", south);
south.setVisible(false);
setSize(350, 300);
pack();
}
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof MenuItem) {
if (evt.getActionCommand().equals("visible")) {
south.setVisible(true);
pack();
} else if (evt.getActionCommand().equals("not visible")) {
south.setVisible(false);
pack();
}
}
}
}

View file

@ -0,0 +1,97 @@
/*
* 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.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionListener;
/*
* @test
* @bug 1231233
* @summary Tests whether the resizable property of a Frame is
* respected after it is set.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameResizableTest
*/
public class FrameResizableTest {
private static final String INSTRUCTIONS = """
There is a frame with two buttons and a label. The label
reads 'true' or 'false' to indicate whether the frame can be
resized or not.
When the first button, 'Set Resizable', is
clicked, you should be able to resize the frame.
When the second button, 'UnSet Resizable', is clicked, you should
not be able to resize the frame.
A frame is resized in a way which depends upon the window manager (WM) running.
You may resize the frame by dragging the corner resize handles or the borders,
or you may use the title bar's resize menu items and buttons.
Upon test completion, click Pass or Fail appropriately.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameResizableTest Instructions")
.instructions(INSTRUCTIONS)
.columns(50)
.testUI(FrameResizable::new)
.build()
.awaitAndCheck();
}
private static class FrameResizable extends Frame {
Label label;
Button buttonResizable;
Button buttonNotResizable;
public FrameResizable() {
super("FrameResizable");
setResizable(false);
Panel panel = new Panel();
add("North", panel);
ActionListener actionListener = (e) -> {
if (e.getSource() == buttonResizable) {
setResizable(true);
} else if (e.getSource() == buttonNotResizable) {
setResizable(false);
}
label.setText("Resizable: " + isResizable());
};
panel.add(buttonResizable = new Button("Set Resizable"));
panel.add(buttonNotResizable = new Button("UnSet Resizable"));
panel.add(label = new Label("Resizable: " + isResizable()));
buttonResizable.addActionListener(actionListener);
buttonNotResizable.addActionListener(actionListener);
setSize(400, 200);
}
}
}

View file

@ -0,0 +1,90 @@
/*
* 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
* @key headful
* @bug 8079595
* @summary Resizing dialog which is JWindow parent makes JVM crash
* @author Semyon Sadetsky
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
public class ShowChildWhileResizingTest {
private static Window dialog;
private static Timer timer;
private static Point point;
public static void main(String[] args) throws Exception {
dialog = new Frame();
dialog.add(new JPanel());
dialog.setVisible(true);
dialog.setBounds(100, 100, 200, 200);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
final Window dependentWindow = new JWindow(dialog);
JPanel panel = new JPanel();
panel.add(new JButton("button"));
dependentWindow.add(panel);
dependentWindow.setVisible(true);
dependentWindow.setBounds(0, 0, 50, 50);
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dependentWindow
.setVisible(!dependentWindow.isVisible());
}
});
timer.start();
}
});
Robot robot = new Robot();
robot.setAutoDelay(5);
robot.delay(300);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
point = dialog.getLocationOnScreen();
}
});
robot.mouseMove(point.x + 200 - dialog.getInsets().right/2,
point.y + 200 - dialog.getInsets().bottom/2);
robot.mousePress(InputEvent.BUTTON1_MASK);
for(int i = 0; i < 100; i++) {
robot.mouseMove(point.x + 200 + i, point.y + 200 + i);
}
robot.mouseRelease(InputEvent.BUTTON1_MASK);
timer.stop();
dialog.dispose();
System.out.println("ok");
}
}

View file

@ -0,0 +1,81 @@
/*
* 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.Canvas;
import java.awt.Color;
import java.awt.Frame;
/*
* @test
* @bug 4041442
* @key headful
* @summary Test resizing a frame containing a canvas
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameResizeTest_1
*/
public class FrameResizeTest_1 {
private static final String INSTRUCTIONS = """
To the right of this frame is an all-white 200x200 frame.
This is actually a white canvas component in the frame.
The frame itself is red.
The red should never show.
In particular, after you resize the frame, you should see all white and no red.
(During very fast window resizing, red color may appear briefly,
which is not a failure.)
Upon test completion, click Pass or Fail appropriately.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameResizeTest_1 Instructions")
.instructions(INSTRUCTIONS)
.testTimeOut(5)
.rows(12)
.columns(45)
.testUI(FrameResize_1::new)
.build()
.awaitAndCheck();
}
}
class FrameResize_1 extends Frame {
FrameResize_1() {
super("FrameResize_1");
// Create a white canvas
Canvas canvas = new Canvas();
canvas.setBackground(Color.white);
setLayout(new BorderLayout());
add("Center", canvas);
setBackground(Color.red);
setSize(200,200);
}
}

View file

@ -0,0 +1,133 @@
/*
* 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.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
/*
* @test
* @bug 4065568
* @key headful
* @summary Test resizing a frame containing a canvas
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameResizeTest_2
*/
public class FrameResizeTest_2 {
private static final String INSTRUCTIONS = """
There is a frame (size 300x300).
The left half is red and the right half is blue.
When you resize the frame, it should still have a red left half
and a blue right half.
In particular, no green should be visible after a resize.
Upon test completion, click Pass or Fail appropriately.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameResizeTest_2 Instructions")
.instructions(INSTRUCTIONS)
.testTimeOut(5)
.rows(10)
.columns(45)
.testUI(FrameResize_2::new)
.build()
.awaitAndCheck();
}
}
class FrameResize_2 extends Frame {
FrameResize_2() {
super("FrameResize_2");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
Container dumbContainer = new DumbContainer();
add(dumbContainer, c);
Panel dumbPanel = new DumbPanel();
add(dumbPanel, c);
setSize(300, 300);
}
}
class Fake extends Canvas {
public Fake(String name, Color what) {
setBackground(what);
setName(name);
}
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(getBackground());
g.fillRect(0, 0, d.width, d.height);
}
}
class DumbContainer extends Container {
public DumbContainer() {
setLayout(new BorderLayout());
add("Center", new Fake("dumbc", Color.red));
}
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.green);
g.fillRect(0, 0, d.width, d.height);
super.paint(g);
}
}
class DumbPanel extends Panel {
public DumbPanel() {
setLayout(new BorderLayout());
add("Center", new Fake("dumbp", Color.blue));
}
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.green);
g.fillRect(0, 0, d.width, d.height);
super.paint(g);
}
}

View file

@ -0,0 +1,86 @@
/*
* 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.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionListener;
/*
* @test
* @bug 4097207
* @summary setSize() on a Frame does not resize its content
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameResizeTest_3
*/
public class FrameResizeTest_3 {
private static final String INSTRUCTIONS = """
1. You would see a frame titled 'TestFrame' with 2 buttons
named 'setSize(500,500)' and 'setSize(400,400)'
2. Click any button and you would see the frame resized
3. If the buttons get resized along with the frame
(ie., to fit the frame), press Pass else press Fail.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameResizeTest_3 Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.logArea(6)
.testUI(FrameResizeTest_3::createTestUI)
.build()
.awaitAndCheck();
}
private static Window createTestUI() {
Frame frame = new Frame("TestFrame");
frame.setLayout(new GridLayout(2, 1));
Button butSize500 = new Button("setSize(500,500)");
Button butSize400 = new Button("setSize(400,400)");
ActionListener actionListener = e -> {
if (e.getSource() instanceof Button) {
if (e.getSource() == butSize500) {
frame.setSize(500, 500);
PassFailJFrame.log("New bounds: " + frame.getBounds());
} else if (e.getSource() == butSize400) {
frame.setSize(400, 400);
PassFailJFrame.log("New bounds: " + frame.getBounds());
}
}
};
butSize500.addActionListener(actionListener);
butSize400.addActionListener(actionListener);
frame.add(butSize500);
frame.add(butSize400);
frame.setSize(270, 200);
return frame;
}
}

View file

@ -0,0 +1,76 @@
/*
* 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.
*/
/* Note that although this test makes use of Swing classes, like JFrame and */
/* JButton, it is really an AWT test, because it tests mechanism of sending */
/* paint events. */
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
/*
* @test
* @bug 4174831
* @summary Tests that frame do not flicker on diagonal resize
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameResizeTest_4
*/
public class FrameResizeTest_4 {
private static final String INSTRUCTIONS = """
Try enlarging the frame diagonally.
If buttons inside frame excessively repaint themselves and flicker
while you enlarge frame, the test fails.
Otherwise, it passes.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameResizeTest_4 Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(FrameResizeTest_4::createTestUI)
.build()
.awaitAndCheck();
}
private static JFrame createTestUI() {
JFrame f = new JFrame("FrameResizeTest_4 Flickering Frame");
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JButton("West"), BorderLayout.WEST);
panel.add(new JButton("East"), BorderLayout.EAST);
panel.add(new JButton("North"), BorderLayout.NORTH);
panel.add(new JButton("South"), BorderLayout.SOUTH);
panel.add(new JButton("Center"), BorderLayout.CENTER);
f.setContentPane(panel);
f.pack();
f.setBounds(100, 50, 300, 200);
return f;
}
}

View file

@ -0,0 +1,105 @@
/*
* 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.Button;
import java.awt.Frame;
import java.awt.GridLayout;
/*
* @test
* @summary Test to make sure non-resizable Frames can be resized with the
* setSize() method.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameResizeTest_5
*/
public class FrameResizeTest_5 {
private static final String INSTRUCTIONS = """
This tests the programmatic resizability of non-resizable Frames.
Even when a Frame is set to be non-resizable, it should still be
programmatically resizable using the setSize() method.
Initially the Frame will be resizable. Try using the "Smaller"
and "Larger" buttons to verify that the Frame resizes correctly.
Then, click the "Toggle" button to make the Frame non-resizable.
Again, verify that clicking the "Larger" and "Smaller" buttons
causes the Frame to get larger and smaller. If the Frame does
not change size, or does not re-layout correctly, the test fails.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameResizeTest_5 Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.logArea(6)
.testUI(TestFrame::new)
.build()
.awaitAndCheck();
}
private static class TestFrame extends Frame {
Button bLarger, bSmaller, bCheck, bToggle;
public TestFrame() {
super("Frame Resize Test");
setSize(200, 200);
bLarger = new Button("Larger");
bLarger.addActionListener(e -> {
setSize(400, 400);
validate();
});
bSmaller = new Button("Smaller");
bSmaller.addActionListener(e -> {
setSize(200, 100);
validate();
});
bCheck = new Button("Resizable?");
bCheck.addActionListener(e -> {
if (isResizable()) {
PassFailJFrame.log("Frame is resizable");
setResizable(true);
} else {
PassFailJFrame.log("Frame is not resizable");
setResizable(false);
}
});
bToggle = new Button("Toggle");
bToggle.addActionListener(e -> {
if (isResizable()) {
PassFailJFrame.log("Frame is now not resizable");
setResizable(false);
} else {
PassFailJFrame.log("Frame is now resizable");
setResizable(true);
}
});
setLayout(new GridLayout(4, 1));
add(bSmaller);
add(bLarger);
add(bCheck);
add(bToggle);
}
}
}

View file

@ -0,0 +1,100 @@
/*
* 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.Button;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionListener;
import java.lang.Exception;
import java.lang.InterruptedException;
import java.lang.Object;
import java.lang.String;
import java.lang.Thread;
/*
* @test
* @bug 4097226
* @summary Frame.setCursor() sometimes doesn't update the cursor until user moves the mouse
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameSetCursorTest
*/
public class FrameSetCursorTest {
private static final String INSTRUCTIONS = """
1. Keep the instruction dialog and TestFrame side by side so that
you can read the instructions while doing the test
2. Click on the 'Start Busy' button on the frame titled 'TestFrame'
and DO NOT MOVE THE MOUSE ANYWHERE till you complete the steps below
3. The cursor on the TestFrame changes to busy cursor
4. If you don't see the busy cursor press 'Fail' after
the `done sleeping` message
5. If the busy cursor is seen, after 5 seconds the message
'done sleeping' is displayed in the message window
6. Check for the cursor type after the display of 'done sleeping'
7. If the cursor on the TestFrame has changed back to default cursor
(without you touching or moving the mouse), then press 'Pass'
else if the frame still shows the busy cursor press 'Fail'
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("FrameSetCursorTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(FrameSetCursorTest::createAndShowUI)
.logArea(5)
.build()
.awaitAndCheck();
}
static Frame createAndShowUI() {
Frame frame = new Frame("TestFrame");
Panel panel = new Panel();
Button busyButton = new Button("Start Busy");
ActionListener actionListener = event -> {
Object source = event.getSource();
if (source == busyButton) {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {}
PassFailJFrame.log("done sleeping");
frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
};
busyButton.addActionListener(actionListener);
panel.setLayout(new BorderLayout());
panel.add("North", busyButton);
frame.add(panel);
frame.pack();
frame.setSize(200, 200);
return frame;
}
}

View file

@ -0,0 +1,100 @@
/*
* 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.
*/
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Robot;
/*
* @test
* @bug 4320050
* @key headful
* @summary Minimum size for java.awt.Frame is not being enforced.
* @run main FrameSetMinimumSizeTest
*/
public class FrameSetMinimumSizeTest {
private static Frame f;
private static Robot robot;
public static void main(String[] args) throws Exception {
robot = new Robot();
try {
EventQueue.invokeAndWait(FrameSetMinimumSizeTest::createAndShowUI);
robot.waitForIdle();
robot.delay(500);
test(
new Dimension(200, 200),
new Dimension(300, 300)
);
test(
new Dimension(200, 400),
new Dimension(300, 400)
);
test(
new Dimension(400, 200),
new Dimension(400, 300)
);
EventQueue.invokeAndWait(() -> f.setMinimumSize(null));
test(
new Dimension(200, 200),
new Dimension(200, 200)
);
} finally {
EventQueue.invokeAndWait(() -> {
if (f != null) {
f.dispose();
}
});
}
}
private static void test(Dimension size, Dimension expected) throws Exception {
robot.waitForIdle();
robot.delay(250);
EventQueue.invokeAndWait(() -> f.setSize(size));
robot.waitForIdle();
EventQueue.invokeAndWait(() -> verifyFrameSize(expected));
}
private static void createAndShowUI() {
f = new Frame("Minimum Size Test");
f.setSize(300, 300);
f.setMinimumSize(new Dimension(300, 300));
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static void verifyFrameSize(Dimension expected) {
if (f.getSize().width != expected.width || f.getSize().height != expected.height) {
String message =
"Frame's setMinimumSize not honoured for the frame size: %s. Expected %s"
.formatted(f.getSize(), expected);
throw new RuntimeException(message);
}
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2012, 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.Frame;
/*
@test
@key headful
@bug 7177173
@summary setBounds can cause StackOverflow in case of the considerable loading
@author Sergey Bylokhov
*/
public final class FrameSetSizeStressTest {
public static void main(final String[] args) {
final Frame frame = new Frame();
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
for (int i = 0; i < 1000; ++i) {
frame.setSize(100, 100);
frame.setSize(200, 200);
frame.setSize(300, 300);
}
frame.dispose();
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright 2009 Red Hat, Inc. All Rights Reserved.
* Copyright (c) 2009, 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 6721088
@summary X11 Window sizes should be what we set them to
@author Omair Majid <omajid@redhat.com>: area=awt.toplevel
@run main TestFrameSize
*/
/**
* TestFrameSize.java
*
* Summary: test that X11 Awt windows are drawn with correct sizes
*
* Test fails if size of window is wrong
*/
import java.awt.*;
public class TestFrameSize {
static Dimension desiredDimensions = new Dimension(200, 200);
static Frame mainWindow;
private static Dimension getClientSize(Frame window) {
Dimension size = window.getSize();
Insets insets = window.getInsets();
System.out.println("getClientSize() for " + window);
System.out.println(" size: " + size);
System.out.println(" insets: " + insets);
return new Dimension(
size.width - insets.left - insets.right,
size.height - insets.top - insets.bottom);
}
public static void drawGui() {
mainWindow = new Frame("");
mainWindow.setPreferredSize(desiredDimensions);
mainWindow.pack();
Dimension actualDimensions = mainWindow.getSize();
System.out.println("Desired dimensions: " + desiredDimensions.toString());
System.out.println("Actual dimensions: " + actualDimensions.toString());
if (!actualDimensions.equals(desiredDimensions)) {
throw new RuntimeException("Incorrect widow size");
}
// pack() guarantees to preserve the size of the client area after
// showing the window.
Dimension clientSize1 = getClientSize(mainWindow);
System.out.println("Client size before showing: " + clientSize1);
mainWindow.setVisible(true);
try {
Robot robot = new Robot();
robot.waitForIdle();
}catch(Exception ex) {
ex.printStackTrace();
throw new RuntimeException("Unexpected failure.");
}
Dimension clientSize2 = getClientSize(mainWindow);
System.out.println("Client size after showing: " + clientSize2);
if (!clientSize2.equals(clientSize1)) {
throw new RuntimeException("Incorrect client area size.");
}
}
public static void main(String[] args) {
try {
drawGui();
} finally {
if (mainWindow != null) {
mainWindow.dispose();
}
}
}
}

View file

@ -0,0 +1,324 @@
/*
* 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.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import javax.swing.JPanel;
import javax.swing.Timer;
/*
* @test
* @bug 4157271
* @summary Checks that when a Frame is created it honors the state it
* was set to. The bug was that if setState(Frame.ICONIFIED) was
* called before setVisible(true) the Frame would be shown in NORMAL
* state instead of ICONIFIED.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FrameStateTest
*/
public class FrameStateTest implements ActionListener {
private static final String INSTRUCTIONS = """
<html><body><p>
This test checks that when setState(Frame.ICONIFIED) is called before
setVisible(true) the Frame is shown in the proper iconified state.
The problem was that it did not honor the initial iconic state, but
instead was shown in the NORMAL state.
</p><hr/>
Steps to try to reproduce this problem:
<p>
Select the different options for the Frame:
<ul>
<li><i>{Normal, Non-resizable}</i></li>
<li><i>{Normal, Resizable}</i></li>
<li><i>{Iconified, Resizable}</i></li>
<li><i>{Iconified, Non-resizable}</i></li>
</ul>
After choosing the Frame's state click the
Create Frame button.<br>
After the Frame (Frame State Test (Window2)) comes up make sure the
proper behavior occurred (Frame shown in proper state).<br>
Click the Dispose button to close the Frame.<br>
</p><hr/><p>
Do the above steps for all the different Frame state combinations
available.<br>
For "Hide, Iconify and Show" case, the frame is hidden then iconified
hence Window2 is not seen on-screen when shown as the frame is still
in the ICONIFIED state. Window2 is visible on-screen when it is restored
to NORMAL state as observed with "Hide, Iconify, Show and Restore" case.
<br><br>
If you observe the proper behavior for all the combinations,
press PASS else FAIL.<br>
</p><p>
Note: In Frame State Test (Window2) you can also chose the different
buttons to see different Frame behavior.<br>An example of a problem that
has been seen, with the Frame non-resizable you can not iconify the Frame.
</p>
</body>
</html>
""";
public static final int DELAY = 1000;
Button btnCreate = new Button("Create Frame");
Button btnDispose = new Button("Dispose Frame");
CheckboxGroup cbgState = new CheckboxGroup();
CheckboxGroup cbgResize = new CheckboxGroup();
Checkbox cbIconState = new Checkbox("Frame State ICONIFIED", cbgState, true);
Checkbox cbNormState = new Checkbox("Frame State NORMAL", cbgState, false);
Checkbox cbNonResize = new Checkbox("Frame Non-Resizable", cbgResize, false);
Checkbox cbResize = new Checkbox("Frame Resizable", cbgResize, true);
CreateFrame icontst;
public static void main(String[] args) throws Exception {
PassFailJFrame
.builder()
.title("Frame State and Size Test Instructions")
.instructions(INSTRUCTIONS)
.testTimeOut(10)
.rows(27)
.columns(70)
.logArea(6)
.splitUIBottom(() -> new FrameStateTest().createPanel())
.build()
.awaitAndCheck();
}
public JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 3));
btnDispose.setEnabled(false);
panel.add(cbIconState);
panel.add(cbResize);
panel.add(btnCreate);
panel.add(cbNormState);
panel.add(cbNonResize);
panel.add(btnDispose);
btnDispose.addActionListener(this);
btnCreate.addActionListener(this);
return panel;
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == btnCreate) {
btnCreate.setEnabled(false);
btnDispose.setEnabled(true);
icontst = new CreateFrame(cbIconState.getState(), cbResize.getState());
icontst.setVisible(true);
} else if (evt.getSource() == btnDispose) {
btnCreate.setEnabled(true);
btnDispose.setEnabled(false);
icontst.dispose();
}
}
static class CreateFrame extends Frame
implements ActionListener, WindowListener {
Button b1, b2, b3, b4, b5, b6, b7;
boolean isResizable;
String name = "Frame State Test";
CreateFrame(boolean iconified, boolean resizable) {
setTitle("Test Window (Window 2)");
isResizable = resizable;
PassFailJFrame.log("CREATING FRAME - Initially " +
((iconified) ? "ICONIFIED" : "NORMAL (NON-ICONIFIED)") + " and " +
((isResizable) ? "RESIZABLE" : "NON-RESIZABLE"));
setLayout(new FlowLayout());
add(b1 = new Button("Resizable"));
add(b2 = new Button("Resize"));
add(b3 = new Button("Iconify"));
add(b4 = new Button("Iconify and Restore"));
add(b5 = new Button("Hide and Show"));
add(b6 = new Button("Hide, Iconify and Show"));
add(b7 = new Button("Hide, Iconify, Show and Restore"));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
addWindowListener(this);
setBounds(100, 2, 300, 200);
setState(iconified ? Frame.ICONIFIED : Frame.NORMAL);
setResizable(isResizable);
setVisible(true);
}
/**
* Calls all runnables on EDT with a {@code DELAY} delay before each run.
* @param runnables to run
*/
private static void delayedActions(Runnable... runnables) {
setTimer(new ArrayDeque<>(Arrays.asList(runnables)));
}
private static void setTimer(Deque<Runnable> deque) {
if (deque == null || deque.isEmpty()) return;
Timer timer = new Timer(DELAY, e -> {
deque.pop().run();
setTimer(deque);
});
timer.setRepeats(false);
timer.start();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b2) {
Rectangle r = this.getBounds();
r.width += 10;
stateLog(" - button pressed - setting bounds on Frame to: " + r);
setBounds(r);
validate();
} else if (e.getSource() == b1) {
isResizable = !isResizable;
stateLog(" - button pressed - setting Resizable to: " + isResizable);
((Frame) (b1.getParent())).setResizable(isResizable);
} else if (e.getSource() == b3) {
stateLog(" - button pressed - setting Iconic: ");
((Frame) (b1.getParent())).setState(Frame.ICONIFIED);
stateLog();
} else if (e.getSource() == b4) {
stateLog(" - button pressed - setting Iconic: ");
((Frame) (b1.getParent())).setState(Frame.ICONIFIED);
stateLog();
delayedActions(() -> {
stateLog(" - now restoring: ");
((Frame) (b1.getParent())).setState(Frame.NORMAL);
stateLog();
});
} else if (e.getSource() == b5) {
stateLog(" - button pressed - hiding : ");
b1.getParent().setVisible(false);
stateLog();
delayedActions(() -> {
stateLog(" - now reshowing: ");
b1.getParent().setVisible(true);
stateLog();
});
} else if (e.getSource() == b6) {
stateLog(" - button pressed - hiding : ");
b1.getParent().setVisible(false);
stateLog();
delayedActions(
() -> {
stateLog(" - setting Iconic: ");
((Frame) (b1.getParent())).setState(Frame.ICONIFIED);
},
() -> {
stateLog(" - now reshowing: ");
b1.getParent().setVisible(true);
stateLog();
}
);
} else if (e.getSource() == b7) {
stateLog(" - button pressed - hiding : ");
b1.getParent().setVisible(false);
stateLog();
delayedActions(
() -> {
stateLog(" - setting Iconic: ");
((Frame) (b1.getParent())).setState(Frame.ICONIFIED);
},
() -> {
stateLog(" - now reshowing: ");
b1.getParent().setVisible(true);
stateLog();
},
() -> {
stateLog(" - now restoring: ");
((Frame) (b1.getParent())).setState(Frame.NORMAL);
stateLog();
}
);
}
}
public void windowActivated(WindowEvent e) {
stateLog("Activated");
}
public void windowClosed(WindowEvent e) {
stateLog("Closed");
}
public void windowClosing(WindowEvent e) {
((Window) (e.getSource())).dispose();
stateLog("Closing");
}
public void windowDeactivated(WindowEvent e) {
stateLog("Deactivated");
}
public void windowDeiconified(WindowEvent e) {
stateLog("Deiconified");
}
public void windowIconified(WindowEvent e) {
stateLog("Iconified");
}
public void windowOpened(WindowEvent e) {
stateLog("Opened");
}
public void stateLog(String message) {
PassFailJFrame
.log("[Current State = %d] %s %s".formatted(getState(), name, message));
}
public void stateLog() {
PassFailJFrame.log("[Current State = " + getState() + "]");
}
}
}

View file

@ -0,0 +1,126 @@
/*
* 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.
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
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 4328588
* @key headful
* @summary Non-default visual on top-level Frame should work
* @run main FrameVisualTest
*/
public class FrameVisualTest {
private static GraphicsConfiguration[] gcs;
private static volatile Frame[] frames;
private static Robot robot;
private static volatile int frameNum;
private static volatile Point p;
private static volatile Dimension d;
private static final int TOLERANCE = 5;
private static final int MAX_FRAME_COUNT = 30;
public static void main(String[] args) throws Exception {
gcs = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getConfigurations();
robot = new Robot();
robot.setAutoDelay(100);
// Limit the number of frames tested if needed
if (gcs.length > MAX_FRAME_COUNT) {
frames = new Frame[MAX_FRAME_COUNT];
} else {
frames = new Frame[gcs.length];
}
System.out.println(gcs.length + " gcs found. Testing "
+ frames.length + " frame(s).");
for (frameNum = 0; frameNum < frames.length; frameNum++) {
try {
EventQueue.invokeAndWait(() -> {
frames[frameNum] = new Frame("Frame w/ gc "
+ frameNum, gcs[frameNum]);
frames[frameNum].setSize(100, 100);
frames[frameNum].setUndecorated(true);
frames[frameNum].setBackground(Color.WHITE);
frames[frameNum].setVisible(true);
System.out.println("Frame " + frameNum + " created");
});
robot.delay(1000);
EventQueue.invokeAndWait(() -> {
p = frames[frameNum].getLocation();
d = frames[frameNum].getSize();
});
Rectangle rect = new Rectangle(p, d);
BufferedImage img = robot.createScreenCapture(rect);
if (chkImgBackgroundColor(img)) {
try {
ImageIO.write(img, "png",
new File("Frame_"
+ frameNum + ".png"));
} catch (IOException ignored) {}
throw new RuntimeException("Frame visual test " +
"failed with non-white background color");
}
} finally {
EventQueue.invokeAndWait(() -> {
if (frames[frameNum] != null) {
frames[frameNum].dispose();
System.out.println("Frame " + frameNum + " disposed");
}
});
}
}
}
private static boolean chkImgBackgroundColor(BufferedImage img) {
// scan for mid-line and if it is non-white color then return true.
for (int x = 1; x < img.getWidth() - 1; ++x) {
Color c = new Color(img.getRGB(x, img.getHeight() / 2));
if ((c.getRed() - Color.WHITE.getRed()) > TOLERANCE &&
(c.getGreen() - Color.WHITE.getGreen()) > TOLERANCE &&
(c.getBlue() - Color.WHITE.getBlue()) > TOLERANCE) {
return true;
}
}
return false;
}
}

View file

@ -0,0 +1,160 @@
/*
* Copyright (c) 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.BufferedImage;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.Vector;
/*
* @test
* @key headful
* @summary Verify that disposed frames are collected with GC
* @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com)
* @library /lib/client
* @build ExtendedRobot
* @run main/othervm -Xmx20m FramesGC
*/
public class FramesGC {
ExtendedRobot robot;
ArrayList<PhantomReference<Frame>> refs = new ArrayList<PhantomReference<Frame>>();
ReferenceQueue<Frame> que = new ReferenceQueue<Frame>();
public static void main(String []args) throws Exception {
new FramesGC().doTest();
}
FramesGC() throws Exception{
robot = new ExtendedRobot();
}
void doTest() throws Exception {
for( int i = 1; i <= 3; i++) {
final int j = i;
EventQueue.invokeAndWait(() -> {
createFrame(j);
});
}
robot.waitForIdle();
for (Frame f : Frame.getFrames())
f.dispose();
robot.waitForIdle();
Vector garbage = new Vector();
while (true) {
try {
garbage.add(new byte[1000]);
} catch (OutOfMemoryError er) {
break;
}
}
garbage = null;
int count = 1;
for(; count <= 3; count++)
if(que.remove(5000) == null)
break;
System.out.println("Total no of instances eligible for GC = " + count);
if(count < 3)
throw new RuntimeException("Count = "+count+". Test failed!");
}
void createFrame(int i){
Frame frame = new Frame("Frame " + i);
Button button=new Button("Press Me");
TextArea textArea=new TextArea(5,5);
TextField textField=new TextField(10);
Choice choice=new Choice();
choice.add("One");
choice.add("Two");
choice.add("Three");
choice.add("Four");
choice.add("Five");
List list = new List();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
Checkbox checkBox= new Checkbox("Hai");
Scrollbar scrollBar=new Scrollbar(Scrollbar.VERTICAL,0,1,0,200);
CheckboxGroup checkboxGroup=new CheckboxGroup();
Checkbox radioButton=new Checkbox("Hello" ,true, checkboxGroup);
Canvas canvas=new Canvas();
canvas.setSize(100, 100);
canvas.setBackground(java.awt.Color.red);
Label label=new Label("I am label.!");
Cursor customCursor=null;
frame.setLayout(new java.awt.FlowLayout());
button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
label.setCursor(new Cursor(Cursor.TEXT_CURSOR));
choice.setCursor(new Cursor(Cursor.WAIT_CURSOR));
list.setCursor(new Cursor(Cursor.HAND_CURSOR));
checkBox.setCursor(new Cursor(Cursor.MOVE_CURSOR));
radioButton.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR));
scrollBar.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
canvas.setCursor(new Cursor(Cursor.W_RESIZE_CURSOR));
textField.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
/* create a custom cursor */
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getBestCursorSize(32,32);
int color = toolkit.getMaximumCursorColors();
if(!d.equals(new Dimension(0,0)) && color != 0 )
customCursor = toolkit.createCustomCursor(new BufferedImage( 16, 16, BufferedImage.TYPE_INT_RGB ), new Point(10, 10), "custom cursor.");
else
System.err.println("Platform doesn't support to create a custom cursor.");
textArea.setCursor(customCursor);
frame.add(label);
frame.add(button);
frame.add(choice);
frame.add(list);
frame.add(checkBox);
frame.add(radioButton);
frame.add(scrollBar);
frame.add(canvas);
frame.add(textArea);
frame.add(textField);
frame.add(button);
frame.setLocation(20, 140 * i);
frame.pack();
frame.setVisible(true);
refs.add(new PhantomReference<Frame>(frame, que));
}
}

View file

@ -0,0 +1,97 @@
/*
* 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.Frame;
import java.awt.EventQueue;
import java.awt.Robot;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/*
* @test
* @bug 4103095
* @summary Test for getBounds() after a Frame resize.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual GetBoundsResizeTest
*/
public class GetBoundsResizeTest {
private static final String INSTRUCTIONS = """
0. There is a test window with a "Press" button,
Its original bounds should be printed in the text area below.
1. Resize the test window using the upper left corner.
2. Press the button to print the result of getBounds() to the text area.
3. Previously, a window could report an incorrect position on the
screen after resizing the window in this way.
If getBounds() prints the appropriate values for the window,
click Pass, otherwise click Fail.
""";
private static JTextArea textArea;
private static Frame frame;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
PassFailJFrame passFailJFrame = PassFailJFrame
.builder()
.title("GetBoundsResizeTest Instructions")
.instructions(INSTRUCTIONS)
.splitUIBottom(() -> {
textArea = new JTextArea("", 8, 55);
textArea.setEditable(false);
return new JScrollPane(textArea);
})
.testUI(GetBoundsResizeTest::getFrame)
.rows((int) (INSTRUCTIONS.lines().count() + 2))
.columns(40)
.build();
robot.waitForIdle();
robot.delay(500);
EventQueue.invokeAndWait(() ->
logFrameBounds("Original Frame.getBounds() = %s\n"));
passFailJFrame.awaitAndCheck();
}
private static Frame getFrame() {
frame = new Frame("GetBoundsResizeTest");
Button button = new Button("Press");
button.addActionListener((e) ->
logFrameBounds("Current Frame.getBounds() = %s\n"));
frame.add(button);
frame.setSize(200, 100);
return frame;
}
private static void logFrameBounds(String format) {
textArea.append(format.formatted(frame.getBounds()));
}
}

View file

@ -0,0 +1,111 @@
/*
* Copyright (c) 2019, 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.
*/
import java.awt.Frame;
import java.awt.Graphics;
import java.util.concurrent.TimeUnit;
/**
* @test
* @bug 8235638 8235739 8285094 8346952
* @key headful
*/
public final class GetGraphicsStressTest {
static volatile Throwable failed;
static volatile long endtime;
public static void main(final String[] args) throws Exception {
// Catch all uncaught exceptions and treat them as test failure
Thread.setDefaultUncaughtExceptionHandler((t, e) -> failed = e);
// Will run the test no more than 20 seconds
for (int i = 0; i < 4; i++) {
endtime = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
test();
}
/*
* This test needs to give the desktop time to recover to avoid
* destabilising other tests.
*/
Thread.sleep(10000);
}
private static void test() throws Exception {
Frame f = new Frame();
f.setSize(100, 100);
f.setLocationRelativeTo(null);
f.setVisible(true);
Thread thread1 = new Thread(() -> {
while (!isComplete()) {
f.removeNotify();
f.addNotify();
}
});
Thread thread2 = new Thread(() -> {
while (!isComplete()) {
Graphics g = f.getGraphics();
if (g != null) {
g.dispose();
}
}
});
Thread thread3 = new Thread(() -> {
while (!isComplete()) {
Graphics g = f.getGraphics();
if (g != null) {
g.dispose();
}
}
});
Thread thread4 = new Thread(() -> {
while (!isComplete()) {
Graphics g = f.getGraphics();
if (g != null) {
g.drawLine(0, 0, 4, 4); // just in case...
g.dispose();
}
}
});
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
f.dispose();
if (failed != null) {
System.err.println("Test failed");
failed.printStackTrace();
throw new RuntimeException(failed);
}
}
private static boolean isComplete() {
return endtime - System.nanoTime() < 0 || failed != null;
}
}

View file

@ -0,0 +1,71 @@
/*
* Copyright (c) 2012, 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 7177173
@summary The maximized state shouldn't be reset upon hiding a frame
@author anthony.petrov@oracle.com: area=awt.toplevel
@run main HideMaximized
*/
import java.awt.*;
public class HideMaximized {
public static void main(String[] args) {
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
// Nothing to test
return;
}
// First test a decorated frame
Frame frame = new Frame("test");
test(frame);
// Now test an undecorated frames
frame = new Frame("undecorated test");
frame.setUndecorated(true);
test(frame);
}
private static void test(Frame frame) {
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setVisible(true);
try { Thread.sleep(1000); } catch (Exception ex) {}
if (frame.getExtendedState() != Frame.MAXIMIZED_BOTH) {
throw new RuntimeException("The maximized state has not been applied");
}
// This will hide the frame, and also clean things up for safe exiting
frame.dispose();
try { Thread.sleep(1000); } catch (Exception ex) {}
if (frame.getExtendedState() != Frame.MAXIMIZED_BOTH) {
throw new RuntimeException("The maximized state has been reset");
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2012, 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 7160609
@summary A window with huge dimensions shouldn't crash JVM
@author anthony.petrov@oracle.com: area=awt.toplevel
@run main HugeFrame
*/
import java.awt.*;
public class HugeFrame {
public static void main(String[] args) throws Exception {
Frame f = new Frame("Huge");
// 8193+ should already produce a crash, but let's go extreme...
f.setBounds(10, 10, 30000, 500000);
f.setVisible(true);
// We would crash by now if the bug wasn't fixed
Thread.sleep(1000);
System.err.println(f.getBounds());
// Cleanup
f.dispose();
}
}

View file

@ -0,0 +1,65 @@
/*
* 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.BorderLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Window;
/*
* @test
* @bug 6269884 4929291
* @summary Tests that title which contains mix of non-English characters is displayed correctly
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual I18NTitle
*/
public class I18NTitle {
private static final String INSTRUCTIONS = """
You will see a frame with some title (S. Chinese, Cyrillic and German).
Please check if non-English characters are visible and compare
the visible title with the same string shown in the label
(it should not look worse than the label).
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("I18NTitle Instructions")
.instructions(INSTRUCTIONS)
.columns(50)
.testUI(I18NTitle::createAndShowGUI)
.build()
.awaitAndCheck();
}
private static Window createAndShowGUI() {
String s = "\u4e2d\u6587\u6d4b\u8bd5 \u0420\u0443\u0441\u0441\u043a\u0438\u0439 Zur\u00FCck";
Frame frame = new Frame(s);
frame.setLayout(new BorderLayout());
Label l = new Label(s);
frame.add(l);
frame.setSize(400, 100);
return frame;
}
}

View file

@ -0,0 +1,70 @@
/*
* 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.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
/*
* @test
* @bug 4113040
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @summary Checks that IMStatusBar does not affect Frame layout
* @run main/manual/othervm -Duser.language=ja -Duser.country=JP IMStatusBar
*/
public class IMStatusBar {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
If the window appears the right size, but then resizes so that the
status field overlaps the bottom label, press Fail; otherwise press Pass.
""";
PassFailJFrame.builder()
.title("IMStatusBar Instruction")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(40)
.testUI(IMStatusBar::createUI)
.build()
.awaitAndCheck();
}
private static Frame createUI() {
Frame f = new Frame();
Panel centerPanel = new Panel();
f.setSize(200, 200);
f.setLayout(new BorderLayout());
f.add(new Label("Top"), BorderLayout.NORTH);
f.add(centerPanel, BorderLayout.CENTER);
f.add(new Label("Bottom"), BorderLayout.SOUTH);
centerPanel.setLayout(new BorderLayout());
centerPanel.add(new TextField("Middle"), BorderLayout.CENTER);
centerPanel.validate();
return f;
}
}

View file

@ -0,0 +1,103 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2024, 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 8326497
* @summary Verifies that an iconified window is restored with Window.toFront()
* @library /test/lib
* @run main IconifiedToFront
*/
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Robot;
import java.awt.Toolkit;
public class IconifiedToFront {
private static final int PAUSE_MS = 500;
private static Robot robot;
public static void main(String[] args) throws Exception {
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.ICONIFIED)) {
return; // Nothing to test
}
robot = new Robot();
IconifiedToFront.test1();
IconifiedToFront.test2();
}
private static void test1() {
Frame frame1 = new Frame("IconifiedToFront Test 1");
try {
frame1.setLayout(new FlowLayout());
frame1.setSize(400, 300);
frame1.setBackground(Color.green);
frame1.add(new Label("test"));
frame1.setVisible(true);
pause();
frame1.setExtendedState(Frame.ICONIFIED);
pause();
frame1.toFront();
pause();
int state = frame1.getExtendedState();
if ((state & Frame.ICONIFIED) != 0) {
throw new RuntimeException("Test Failed: state is still ICONIFIED: " + state);
}
} finally {
frame1.dispose();
}
}
private static void test2() {
Frame frame1 = new Frame("IconifiedToFront Test 3");
try {
frame1.setLayout(new FlowLayout());
frame1.setSize(400, 300);
frame1.setBackground(Color.green);
frame1.add(new Label("test"));
frame1.setUndecorated(true);
frame1.setVisible(true);
pause();
frame1.setExtendedState(Frame.ICONIFIED);
pause();
frame1.toFront();
pause();
int state = frame1.getExtendedState();
if ((state & Frame.ICONIFIED) != 0) {
throw new RuntimeException("Test Failed: state is still ICONIFIED: " + state);
}
} finally {
frame1.dispose();
}
}
private static void pause() {
robot.delay(PAUSE_MS);
robot.waitForIdle();
}
}

View file

@ -0,0 +1,200 @@
/*
* Copyright (c) 1999, 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.
*/
import java.awt.AWTException;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
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.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.SwingUtilities;
/*
* @test
* @key headful
* @bug 8296934
* @summary Verifies whether Undecorated Frame can be iconified or not.
* @run main IconifyTest
*/
public class IconifyTest {
private static Robot robot;
private static Button button;
private static Frame frame;
private static volatile int windowStatusEventType;
private static volatile int windowIconifiedEventType;
private static volatile boolean focusGained = false;
public static void initializeGUI() {
frame = new Frame();
frame.setLayout(new FlowLayout());
frame.setSize(200, 200);
frame.setUndecorated(true);
frame.addWindowFocusListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent event) {
focusGained = true;
}
});
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
windowStatusEventType = WindowEvent.WINDOW_ACTIVATED;
System.out.println("Event encountered: " + e);
}
public void windowIconified(WindowEvent e) {
windowIconifiedEventType = WindowEvent.WINDOW_ICONIFIED;
System.out.println("Event encountered: " + e);
}
public void windowDeiconified(WindowEvent e) {
windowIconifiedEventType = WindowEvent.WINDOW_DEICONIFIED;
System.out.println("Event encountered: " + e);
}
public void windowDeactivated(WindowEvent e) {
windowStatusEventType = WindowEvent.WINDOW_DEACTIVATED;
System.out.println("Event encountered: " + e);
}
});
button = new Button("Minimize me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setExtendedState(Frame.ICONIFIED);
}
});
frame.setBackground(Color.green);
frame.add(button);
frame.setLocationRelativeTo(null);
frame.toFront();
frame.setVisible(true);
}
public static void main(String[] args) throws AWTException,
InvocationTargetException, InterruptedException {
robot = new Robot();
try {
robot.setAutoDelay(100);
robot.setAutoWaitForIdle(true);
SwingUtilities.invokeAndWait(IconifyTest::initializeGUI);
final AtomicReference<Point> frameloc = new AtomicReference<>();
final AtomicReference<Dimension> framesize = new AtomicReference<>();
SwingUtilities.invokeAndWait(() -> {
frameloc.set(frame.getLocationOnScreen());
framesize.set(frame.getSize());
});
Point locOnScreen = frameloc.get();
Dimension frameSizeOnScreen = framesize.get();
robot.mouseMove(locOnScreen.x + frameSizeOnScreen.width / 2,
locOnScreen.y + frameSizeOnScreen.height / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
if (windowStatusEventType != WindowEvent.WINDOW_ACTIVATED) {
throw new RuntimeException(
"FAIL: WINDOW_ACTIVATED event did not occur when the undecorated frame is activated!");
}
clearEventTypeValue();
final AtomicReference<Point> buttonloc = new AtomicReference<>();
final AtomicReference<Dimension> buttonsize = new AtomicReference<>();
SwingUtilities.invokeAndWait(() -> {
buttonloc.set(button.getLocationOnScreen());
buttonsize.set(button.getSize());
});
Point buttonLocOnScreen = buttonloc.get();
Dimension buttonSizeOnScreen = buttonsize.get();
robot.mouseMove(buttonLocOnScreen.x + buttonSizeOnScreen.width / 2,
buttonLocOnScreen.y + buttonSizeOnScreen.height / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
if (windowIconifiedEventType != WindowEvent.WINDOW_ICONIFIED) {
throw new RuntimeException(
"FAIL: WINDOW_ICONIFIED event did not occur when the undecorated frame is iconified!");
}
if (windowStatusEventType != WindowEvent.WINDOW_DEACTIVATED) {
throw new RuntimeException(
"FAIL: WINDOW_DEACTIVATED event did not occur when the undecorated frame is iconified!");
}
final AtomicReference<Boolean> frameHasFocus = new AtomicReference<>();
SwingUtilities
.invokeAndWait(() -> frameHasFocus.set(frame.hasFocus()));
final boolean hasFocus = frameHasFocus.get();
if (hasFocus) {
throw new RuntimeException(
"FAIL: The undecorated frame has focus even when it is iconified!");
}
clearEventTypeValue();
SwingUtilities
.invokeAndWait(() -> frame.setExtendedState(Frame.NORMAL));
robot.waitForIdle();
if (windowIconifiedEventType != WindowEvent.WINDOW_DEICONIFIED) {
throw new RuntimeException(
"FAIL: WINDOW_DEICONIFIED event did not occur when the state is set to NORMAL!");
}
if (windowStatusEventType != WindowEvent.WINDOW_ACTIVATED) {
throw new RuntimeException(
"FAIL: WINDOW_ACTIVATED event did not occur when the state is set to NORMAL!");
}
if (!focusGained) {
throw new RuntimeException(
"FAIL: The undecorated frame does not have focus when it is deiconified!");
}
System.out.println("Test passed");
}
finally {
SwingUtilities.invokeAndWait(IconifyTest::disposeFrame);
}
}
public static void disposeFrame() {
if (frame != null) {
frame.dispose();
frame = null;
}
}
public static void clearEventTypeValue() {
windowIconifiedEventType = -1;
windowStatusEventType = -1;
focusGained = false;
}
}

View file

@ -0,0 +1,138 @@
/*
* 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 javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/*
* @test
* @key headful
* @bug 4851435
* @summary Frame is not shown initially iconified after pack
*/
public class InitialIconifiedTest {
private static Frame backgroundFrame;
private static Frame testedFrame;
private static final Rectangle backgroundFrameBounds =
new Rectangle(100, 100, 200, 200);
private static final Rectangle testedFrameBounds =
new Rectangle(150, 150, 100, 100);
private static Robot robot;
private static final StringBuilder FAILURES = new StringBuilder();
public static void main(String[] args) throws Exception {
robot = new Robot();
try {
EventQueue.invokeAndWait(InitialIconifiedTest::initAndShowBackground);
robot.waitForIdle();
robot.delay(500);
test(false);
test(true);
} finally {
EventQueue.invokeAndWait(() -> {
backgroundFrame.dispose();
testedFrame.dispose();
});
}
if (!FAILURES.isEmpty()) {
throw new RuntimeException(FAILURES.toString());
}
}
private static void test(boolean isUndecorated) throws Exception {
String prefix = isUndecorated ? "undecorated" : "decorated";
EventQueue.invokeAndWait(() -> initAndShowTestedFrame(isUndecorated));
// On macos, we can observe the animation of the window from the initial
// NORMAL state to the ICONIFIED state,
// even if the window was created in the ICONIFIED state.
// The following delay is commented out to capture this animation
// robot.waitForIdle();
// robot.delay(500);
if (!testIfIconified(prefix + "_no_extra_delay")) {
FAILURES.append("Case %s frame with no extra delay failed\n"
.formatted(isUndecorated ? "undecorated" : "decorated"));
}
EventQueue.invokeAndWait(() -> initAndShowTestedFrame(isUndecorated));
robot.waitForIdle();
robot.delay(500);
if (!testIfIconified(prefix + "_with_extra_delay")) {
FAILURES.append("Case %s frame with extra delay failed\n"
.formatted(isUndecorated ? "undecorated" : "decorated"));
}
}
private static void initAndShowBackground() {
backgroundFrame = new Frame("DisposeTest background");
backgroundFrame.setUndecorated(true);
backgroundFrame.setBackground(Color.RED);
backgroundFrame.setBounds(backgroundFrameBounds);
backgroundFrame.setVisible(true);
}
private static void initAndShowTestedFrame(boolean isUndecorated) {
if (testedFrame != null) {
testedFrame.dispose();
}
testedFrame = new Frame("Should have started ICONIC");
if (isUndecorated) {
testedFrame.setUndecorated(true);
}
testedFrame.setExtendedState(Frame.ICONIFIED);
testedFrame.setBounds(testedFrameBounds);
testedFrame.setVisible(true);
}
private static boolean testIfIconified(String prefix) {
BufferedImage bi = robot.createScreenCapture(backgroundFrameBounds);
int redPix = Color.RED.getRGB();
for (int x = 0; x < bi.getWidth(); x++) {
for (int y = 0; y < bi.getHeight(); y++) {
if (bi.getRGB(x, y) != redPix) {
try {
ImageIO.write(bi, "png",
new File(prefix + "_failure.png"));
} catch (IOException ignored) {}
return false;
}
}
}
return true;
}
}

View file

@ -0,0 +1,102 @@
/*
* 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.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
* @test
* @bug 4464714 6365898
* @key headful
* @summary Frames cannot be shown initially maximized
*/
public class InitialMaximizedTest {
static Frame frame;
public static void main(String[] args) throws Exception {
if (!Toolkit.getDefaultToolkit()
.isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
return;
}
Robot robot = new Robot();
try {
EventQueue.invokeAndWait(InitialMaximizedTest::createAndShowFrame);
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(InitialMaximizedTest::checkMaximized);
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
private static void checkMaximized() {
Rectangle frameBounds = frame.getBounds();
GraphicsConfiguration gc = frame.getGraphicsConfiguration();
Rectangle workArea = gc.getBounds();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
workArea.x += screenInsets.left;
workArea.y += screenInsets.top;
workArea.width -= screenInsets.left + screenInsets.right;
workArea.height -= screenInsets.top + screenInsets.bottom;
System.out.println("Frame bounds " + frameBounds);
System.out.println("GraphicsConfiguration bounds " + gc.getBounds());
System.out.println("Screen insets: " + screenInsets);
System.out.println("Work area: " + workArea);
//frame bounds can exceed screen size on Windows, see 8231043
if (!frameBounds.contains(workArea)) {
throw new RuntimeException("Frame is not maximized");
}
}
private static void createAndShowFrame() {
frame = new Frame("The frame SHOULD be shown MAXIMIZED");
frame.setSize(300, 300);
frame.setLocation(50, 50);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
frame.setVisible(true);
}
}

View file

@ -0,0 +1,102 @@
/*
* 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.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
* @test
* @bug 4091426
* @key headful
* @summary Test inset correction when setVisible(true) BEFORE setSize(), setLocation()
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual InsetCorrectionTest
*/
public class InsetCorrectionTest {
private static final String INSTRUCTIONS = """
There is a frame of size 300x300 at location (100,100).
It has a menubar with one menu, 'File', but the frame
is otherwise empty. In particular, there should be no
part of the frame that is not shown in the background color.
Upon test completion, click Pass or Fail appropriately.
""";
private static InsetCorrection testFrame;
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> testFrame = new InsetCorrection());
try {
PassFailJFrame passFailJFrame = PassFailJFrame.builder()
.title("InsetCorrectionTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.logArea(3)
.build();
EventQueue.invokeAndWait(() ->
PassFailJFrame.log("frame location: " + testFrame.getBounds()));
passFailJFrame.awaitAndCheck();
} finally {
EventQueue.invokeAndWait(testFrame::dispose);
}
}
static class InsetCorrection extends Frame
implements ActionListener {
MenuBar mb;
Menu file;
MenuItem cause_bug_b;
public InsetCorrection() {
super("InsetCorrection");
mb = new MenuBar();
file = new Menu("File");
mb.add(file);
cause_bug_b = new MenuItem("cause bug");
file.add(cause_bug_b);
setMenuBar(mb);
cause_bug_b.addActionListener(this);
// Making the frame visible before setSize and setLocation()
// are being called causes sometimes strange behaviour with
// JDK1.1.5G. The frame is then sometimes to large and the
// excess areas are drawn in black. This only happens
// sometimes.
setVisible(true);
setSize(300, 300);
setLocation(100, 100);
}
public void actionPerformed(ActionEvent e) {
setVisible(false);
setVisible(true);
}
}
}

View file

@ -0,0 +1,181 @@
/*
* Copyright (c) 2012, 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
@key headful
@bug 7154177 8285094
@summary An invisible owner frame should never become visible
@run main InvisibleOwner
*/
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class InvisibleOwner {
private static volatile boolean invisibleOwnerClicked = false;
private static volatile boolean backgroundClicked = false;
private static final int F_X = 200, F_Y = 200, F_W = 200, F_H = 200;
private static final int H_X = F_X - 10, H_Y = F_Y - 10, H_W = F_W + 20, H_H = F_H + 20;
private static final int C_X = F_X + F_W / 2, C_Y = F_Y + F_H / 2;
static final Color helperFrameBgColor = Color.blue;
static final Color invisibleFrameBgColor = Color.green;
static Frame invisibleFrame;
static Frame helperFrame;
static Window ownedWindow;
static Robot robot;
static void createUI() {
/* A background frame to compare a pixel color against
* It should be centered in the same location as the invisible
* frame but extend beyond its bounds.
*/
helperFrame = new Frame("Background frame");
helperFrame.setBackground(helperFrameBgColor);
helperFrame.setLocation(H_X, H_Y);
helperFrame.setSize(H_W, H_H);
System.out.println("Helper requested bounds : x=" +
H_X + " y="+ H_Y +" w="+ H_W +" h="+ H_H);
helperFrame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent ev) {
System.out.println("Background helper frame clicked");
backgroundClicked = true;
}
});
helperFrame.setVisible(true);
/* An owner frame that should stay invisible but theoretical
* bounds are within the helper frame.
*/
invisibleFrame = new Frame("Invisible Frame");
invisibleFrame.setBackground(invisibleFrameBgColor);
invisibleFrame.setLocation(F_X, F_Y);
invisibleFrame.setSize(F_W, F_H);
invisibleFrame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent ev) {
System.out.println("Invisible owner clicked");
invisibleOwnerClicked = true;
}
});
/* An owned window of the invisible frame that is located
* such that it does not overlap either the helper or
* the invisisible frame.
*/
ownedWindow = new Window(invisibleFrame);
ownedWindow.setBackground(Color.RED);
ownedWindow.setLocation(H_X+H_W+100, H_Y+H_W+100);
ownedWindow.setSize(100, 100);
ownedWindow.setVisible(true);
Toolkit.getDefaultToolkit().sync();
}
static void captureScreen() throws Exception {
System.out.println("Writing screen capture");
Rectangle screenRect = helperFrame.getGraphicsConfiguration().getBounds();
java.awt.image.BufferedImage bi = robot.createScreenCapture(screenRect);
javax.imageio.ImageIO.write(bi, "png", new java.io.File("screen_IO.png"));
}
public static void main(String[] args) throws Exception {
try {
EventQueue.invokeAndWait(() -> createUI());
robot = new Robot();
robot.waitForIdle();
robot.setAutoDelay(100);
robot.setAutoWaitForIdle(true);
Rectangle helperBounds = helperFrame.getBounds();
System.out.println("helperFrame bounds = " + helperBounds);
if (!helperBounds.contains(C_X, C_Y)) {
System.out.println("Helper not positioned where it needs to be");
return;
}
// Clicking the owned window shouldn't make its owner visible
Rectangle ownedWindowBounds = ownedWindow.getBounds();
robot.mouseMove(ownedWindowBounds.x + ownedWindowBounds.width / 2,
ownedWindowBounds.y + ownedWindowBounds.height / 2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
// 1. Check the color at the center of the invisible & helper frame location
Color c = robot.getPixelColor(C_X, C_Y);
System.out.println("Sampled pixel at " + C_X +"," + C_Y);
System.out.println("Pixel color: " + c);
if (c == null) {
captureScreen();
throw new RuntimeException("Robot.getPixelColor() failed");
}
if (c.equals(invisibleFrameBgColor)) {
captureScreen();
throw new RuntimeException("The invisible frame has become visible");
}
if (!c.equals(helperFrameBgColor)) {
captureScreen();
throw new RuntimeException(
"Background frame was covered by something unexpected");
}
// 2. Try to click it - event should be delivered to the
// helper frame, not the invisible frame.
robot.mouseMove(C_X, C_Y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
if (invisibleOwnerClicked) {
captureScreen();
throw new RuntimeException(
"The invisible owner frame got clicked. Looks like it became visible.");
}
if (!backgroundClicked) {
captureScreen();
throw new RuntimeException(
"The background helper frame hasn't been clicked");
}
} finally {
EventQueue.invokeAndWait(() -> {
if (ownedWindow != null) ownedWindow.dispose();
if (invisibleFrame != null) invisibleFrame.dispose();
if (helperFrame != null) helperFrame.dispose();
});
}
}
}

View file

@ -0,0 +1,276 @@
/*
* 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 6355340
@summary Test correctness of laying out the contents of a frame on maximize
@author anthony.petrov@...: area=awt.toplevel
@library ../../regtesthelpers
@build Util
@run main LayoutOnMaximizeTest
*/
/**
* LayoutOnMaximizeTest.java
*
* summary: tests the correctness of laying out the contents of a frame on maximize
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import test.java.awt.regtesthelpers.Util;
//*** global search and replace LayoutOnMaximizeTest with name of the test ***
public class LayoutOnMaximizeTest
{
//*** test-writer defined static variables go here ***
private static void init() {
// We must be sure that the Size system command is exactly the 3rd one in the System menu.
System.out.println("NOTE: The test is known to work correctly with English MS Windows only.");
String s = Toolkit.getDefaultToolkit().getClass().getName();
// This is Windows-only test
if (!s.contains("WToolkit")) {
pass();
}
// MAXIMIZED_BOTH is known to be supported on MS Windows.
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
fail("Toolkit doesn't support the Frame.MAXIMIZED_BOTH extended state.");
}
final Frame frame = new Frame("Test Frame");
// Add some components to check their position later
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
JTextField jf = new JTextField (10);
JTextField jf1 = new JTextField (10);
JButton jb = new JButton("Test");
panel.add(jf);
panel.add(jf1);
panel.add(jb);
frame.add(panel);
frame.setSize(400, 400);
frame.setVisible(true);
Robot robot = Util.createRobot();
robot.setAutoDelay(20);
// To be sure the window is shown and packed
Util.waitForIdle(robot);
// The initial JTextField position. After maximization it's supposed to be changed.
Point loc1 = jf1.getLocation();
System.out.println("The initial position of the JTextField is: " + loc1);
// The point to move mouse pointer inside the frame
Point pt = frame.getLocation();
// Alt-Space opens System menu
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_ALT);
// Two "down arrow" presses move the menu selection to the Size menu item.
for (int i = 0; i < 2; i++) {
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
}
// And finally select the Size command
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Util.waitForIdle(robot);
// Now move the mouse pointer somewhere inside the frame.
robot.mouseMove(pt.x + 95, pt.y + 70);
// And click once we are inside to imitate the canceling of the size operation.
robot.mousePress( InputEvent.BUTTON1_MASK );
robot.mouseRelease( InputEvent.BUTTON1_MASK );
Util.waitForIdle(robot);
// Now we maximize the frame
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
Util.waitForIdle(robot);
// And check whether the location of the JTextField has changed.
Point loc2 = jf1.getLocation();
System.out.println("Position of the JTextField after maximization is: " + loc2);
// Location of the component changed if relayouting has happened.
if (loc2.equals(loc1)) {
fail("Location of a component has not been changed.");
return;
}
LayoutOnMaximizeTest.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 LayoutOnMaximizeTest
//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,129 @@
/*
* 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.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import jtreg.SkippedException;
/*
* @test
* @key headful
* @bug 4862945
* @summary Undecorated frames miss certain mwm functions in the mwm hints.
* @library /test/lib
* @build jtreg.SkippedException
* @run main MaximizeUndecoratedTest
*/
public class MaximizeUndecoratedTest {
private static final int SIZE = 300;
private static final int OFFSET = 5;
private static Frame frame;
private static Robot robot;
private static volatile Dimension screenSize;
private static volatile Rectangle maxBounds;
public static void main(String[] args) throws Exception {
if (!Toolkit.getDefaultToolkit()
.isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
throw new SkippedException("Test is not applicable as"
+ " the Window manager does not support MAXIMIZATION");
}
try {
robot = new Robot();
EventQueue.invokeAndWait(MaximizeUndecoratedTest::createUI);
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(() -> {
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getMaximumWindowBounds();
System.out.println("Maximum Window Bounds: " + maxBounds);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
});
robot.waitForIdle();
robot.delay(500);
// Colors sampled at top-left, top-right, bottom-right & bottom-left
// corners of maximized frame.
Point[] points = new Point[] {
new Point(maxBounds.x + OFFSET, maxBounds.y + OFFSET),
new Point(maxBounds.width - OFFSET, maxBounds.y + OFFSET),
new Point(maxBounds.width - OFFSET, maxBounds.height - OFFSET),
new Point(maxBounds.x + OFFSET, maxBounds.height - OFFSET)
};
if (!Stream.of(points)
.map(p -> robot.getPixelColor(p.x, p.y))
.allMatch(c -> c.equals(Color.GREEN))) {
saveScreenCapture();
throw new RuntimeException("Test Failed !! Frame not maximized.");
}
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.setExtendedState(Frame.NORMAL);
frame.dispose();
}
});
}
}
private static void createUI() {
frame = new Frame("Test Maximization of Frame");
frame.setSize(SIZE, SIZE);
frame.setBackground(Color.GREEN);
frame.setResizable(true);
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void saveScreenCapture() {
BufferedImage image = robot.createScreenCapture(new Rectangle(new Point(),
screenSize));
try {
ImageIO.write(image, "png", new File("MaximizedFrame.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2013, 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 8026143
* @summary [macosx] Maximized state could be inconsistent between peer and frame
* @author Petr Pchelko
* @library /test/lib
* @build jdk.test.lib.Platform
* @run main MaximizedByPlatform
*/
import jdk.test.lib.Platform;
import java.awt.*;
public class MaximizedByPlatform {
private static Frame frame;
private static Rectangle availableScreenBounds;
public static void main(String[] args) {
if (!Platform.isOSX()) {
// Test only for macosx. Pass
return;
}
Robot robot;
try {
robot = new Robot();
}catch(Exception ex) {
ex.printStackTrace();
throw new RuntimeException("Unexpected failure");
}
availableScreenBounds = getAvailableScreenBounds();
// Test 1. The maximized state is set in setBounds
try {
frame = new Frame();
frame.setBounds(100, 100, 100, 100);
frame.setVisible(true);
robot.waitForIdle();
frame.setBounds(availableScreenBounds.x, availableScreenBounds.y,
availableScreenBounds.width, availableScreenBounds.height);
robot.waitForIdle();
if (frame.getExtendedState() != Frame.MAXIMIZED_BOTH) {
throw new RuntimeException("Maximized state was not set for frame in setBounds");
}
} finally {
if (frame != null) frame.dispose();
}
// Test 2. The maximized state is set in setVisible
try {
frame = new Frame();
frame.setBounds(availableScreenBounds.x, availableScreenBounds.y,
availableScreenBounds.width + 100, availableScreenBounds.height);
frame.setVisible(true);
robot.waitForIdle();
if (frame.getExtendedState() != Frame.MAXIMIZED_BOTH) {
throw new RuntimeException("Maximized state was not set for frame in setVisible");
}
} finally {
if (frame != null) frame.dispose();
}
}
private static Rectangle getAvailableScreenBounds() {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final GraphicsEnvironment graphicsEnvironment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice graphicsDevice =
graphicsEnvironment.getDefaultScreenDevice();
final Dimension screenSize = toolkit.getScreenSize();
final Insets screenInsets = toolkit.getScreenInsets(
graphicsDevice.getDefaultConfiguration());
final Rectangle availableScreenBounds = new Rectangle(screenSize);
availableScreenBounds.x += screenInsets.left;
availableScreenBounds.y += screenInsets.top;
availableScreenBounds.width -= (screenInsets.left + screenInsets.right);
availableScreenBounds.height -= (screenInsets.top + screenInsets.bottom);
return availableScreenBounds;
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.Dimension;
/*
* @test
* @key headful
* @bug 8066436
* @summary Set the size of frame. Set extendedState Frame.MAXIMIZED_BOTH and Frame.NORMAL
* sequentially for undecorated Frame and .
* Check if resulted size is equal to original frame size.
* @run main MaximizedNormalBoundsUndecoratedTest
*/
public class MaximizedNormalBoundsUndecoratedTest {
private Frame frame;
public static void main(String args[]) {
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)
&& !Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.NORMAL)) {
return;
}
MaximizedNormalBoundsUndecoratedTest test = new MaximizedNormalBoundsUndecoratedTest();
boolean doPass = true;
if( !test.doTest() ) {
System.out.println("Maximizing frame not saving correct normal bounds");
doPass = false;
}
if(!doPass) {
throw new RuntimeException("Maximizing frame not saving correct normal bounds");
}
}
boolean doTest() {
Dimension beforeMaximizeCalled = new Dimension(300,300);
frame = new Frame("Test Frame");
frame.setUndecorated(true);
frame.setFocusable(true);
frame.setSize(beforeMaximizeCalled);
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setExtendedState(Frame.NORMAL);
Dimension afterMaximizedCalled= frame.getBounds().getSize();
frame.dispose();
if (beforeMaximizeCalled.equals(afterMaximizedCalled)) {
return true;
}
return false;
}
}

View file

@ -0,0 +1,135 @@
/*
* 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 4977491 8160767
* @summary State changes should always be reported as events
* @run main MaximizedToIconified
*/
/*
* MaximizedToIconified.java
*
* summary: Invoking setExtendedState(ICONIFIED) on a maximized
* frame should not combine the maximized and iconified
* states in the newState of the state change event.
*/
import java.awt.Frame;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
public class MaximizedToIconified
{
static volatile int lastFrameState;
static volatile boolean failed = false;
static volatile Toolkit myKit;
private static Robot robot;
private static void checkState(Frame frame, int state) {
frame.setExtendedState(state);
robot.waitForIdle();
robot.delay(100);
System.out.println("state = " + state + "; getExtendedState() = " + frame.getExtendedState());
if (failed) {
frame.dispose();
throw new RuntimeException("getOldState() != previous getNewState() in WINDOW_STATE_CHANGED event.");
}
if (lastFrameState != frame.getExtendedState()) {
frame.dispose();
throw new RuntimeException("getExtendedState() != last getNewState() in WINDOW_STATE_CHANGED event.");
}
if (frame.getExtendedState() != state) {
frame.dispose();
throw new RuntimeException("getExtendedState() != " + state + " as expected.");
}
}
private static void examineStates(int states[]) {
Frame frame = new Frame("test");
frame.setSize(200, 200);
frame.setVisible(true);
lastFrameState = Frame.NORMAL;
robot.waitForIdle();
frame.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
System.out.println("last = " + lastFrameState + "; getOldState() = " + e.getOldState() +
"; getNewState() = " + e.getNewState());
if (e.getOldState() == lastFrameState) {
lastFrameState = e.getNewState();
} else {
System.out.println("Wrong getOldState(): expected = " + lastFrameState + "; received = " +
e.getOldState());
failed = true;
}
}
});
for (int state : states) {
if (myKit.isFrameStateSupported(state)) {
checkState(frame, state);
} else {
System.out.println("Frame state = " + state + " is NOT supported by the native system. The state is skipped.");
}
}
if (frame != null) {
frame.dispose();
}
}
private static void doTest() {
myKit = Toolkit.getDefaultToolkit();
// NOTE! Compound states (like MAXIMIZED_BOTH | ICONIFIED) CANNOT be used,
// because Toolkit.isFrameStateSupported() method reports these states
// as not supported. And such states will simply be skipped.
examineStates(new int[] {Frame.MAXIMIZED_BOTH, Frame.ICONIFIED, Frame.NORMAL});
System.out.println("------");
examineStates(new int[] {Frame.ICONIFIED, Frame.MAXIMIZED_BOTH, Frame.NORMAL});
System.out.println("------");
examineStates(new int[] {Frame.NORMAL, Frame.MAXIMIZED_BOTH, Frame.ICONIFIED});
System.out.println("------");
examineStates(new int[] {Frame.NORMAL, Frame.ICONIFIED, Frame.MAXIMIZED_BOTH});
}
public static void main( String args[] ) throws Exception
{
robot = new Robot();
doTest();
}
}

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2013, 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.Dimension;
import java.awt.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Robot;
/**
* @test
* @key headful
* @bug 8007219 8146168
* @author Alexander Scherbatiy
* @summary Frame size reverts meaning of maximized attribute
* @run main MaximizedToMaximized
*/
public class MaximizedToMaximized {
public static void main(String[] args) throws Exception {
Frame frame = new Frame();
Robot robot = new Robot();
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final GraphicsEnvironment graphicsEnvironment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice graphicsDevice =
graphicsEnvironment.getDefaultScreenDevice();
final Dimension screenSize = toolkit.getScreenSize();
final Insets screenInsets = toolkit.getScreenInsets(
graphicsDevice.getDefaultConfiguration());
final Rectangle availableScreenBounds = new Rectangle(screenSize);
availableScreenBounds.x += screenInsets.left;
availableScreenBounds.y += screenInsets.top;
availableScreenBounds.width -= (screenInsets.left + screenInsets.right);
availableScreenBounds.height -= (screenInsets.top + screenInsets.bottom);
frame.setBounds(availableScreenBounds.x, availableScreenBounds.y,
availableScreenBounds.width, availableScreenBounds.height);
frame.setVisible(true);
robot.waitForIdle();
Rectangle frameBounds = frame.getBounds();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
Rectangle maximizedFrameBounds = frame.getBounds();
frame.dispose();
if (maximizedFrameBounds.width < frameBounds.width
|| maximizedFrameBounds.height < frameBounds.height) {
throw new RuntimeException("Maximized frame is smaller than non maximized");
}
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 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.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
/**
* @test
* @bug 8176359 8231564
* @key headful
* @requires (os.family == "windows" | os.family == "mac")
* @summary setMaximizedBounds() should work if set to the screen other than
* current screen of the Frame, the size of the frame is intentionally
* big
* @run main/othervm MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=1 MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=1.2 MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=1.25 MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=1.5 MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=1.75 MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=2 MaximizedToOppositeScreenBig
* @run main/othervm -Dsun.java2d.uiScale=2.25 MaximizedToOppositeScreenBig
*/
public final class MaximizedToOppositeScreenBig {
public static void main(String[] args) throws Exception {
//Supported platforms are Windows and OS X.
String os = System.getProperty("os.name").toLowerCase();
if (!os.contains("windows") && !os.contains("os x")) {
return;
}
if (!Toolkit.getDefaultToolkit().
isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
return;
}
var ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
Robot robot = new Robot();
for (GraphicsDevice gd1 : gds) {
Rectangle framAt = gd1.getDefaultConfiguration().getBounds();
framAt.grow(-200, -200);
for (GraphicsDevice gd2 : gds) {
Rectangle maxTo = gd2.getDefaultConfiguration().getBounds();
maxTo.grow(-150, -150);
Frame frame = new Frame(gd1.getDefaultConfiguration());
try {
frame.setBounds(framAt);
frame.setVisible(true);
robot.waitForIdle();
robot.delay(1000);
frame.setMaximizedBounds(maxTo);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
robot.delay(1000);
Rectangle actual = frame.getBounds();
if (!actual.equals(maxTo)) {
System.err.println("Actual: " + actual);
System.err.println("Expected: " + maxTo);
throw new RuntimeException("Wrong bounds");
}
} finally {
frame.dispose();
}
}
}
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 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.Dimension;
import java.awt.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
/**
* @test
* @bug 8176359 8231564 8211999
* @key headful
* @requires (os.family == "windows" | os.family == "mac")
* @summary setMaximizedBounds() should work if set to the screen other than
* current screen of the Frame, the size of the frame is intentionally
* small
*/
public final class MaximizedToOppositeScreenSmall {
public static void main(String[] args) throws Exception {
//Supported platforms are Windows and OS X.
String os = System.getProperty("os.name").toLowerCase();
if (!os.contains("windows") && !os.contains("os x")) {
return;
}
if (!Toolkit.getDefaultToolkit().
isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
return;
}
var ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
Robot robot = new Robot();
for (GraphicsDevice gd1 : gds) {
Rectangle framAt = gd1.getDefaultConfiguration().getBounds();
framAt.grow(-framAt.width / 2 + 100, -framAt.height / 2 + 100);
for (GraphicsDevice gd2 : gds) {
Frame frame = new Frame(gd1.getDefaultConfiguration());
try {
frame.setLayout(null); // trigger use the minimum size of
// the peer
frame.setBounds(framAt);
frame.setVisible(true);
robot.waitForIdle();
robot.delay(1000);
Dimension minimumSize = frame.getMinimumSize();
minimumSize.width = Math.max(minimumSize.width, 120);
minimumSize.height = Math.max(minimumSize.height, 120);
Rectangle maxTo = gd2.getDefaultConfiguration().getBounds();
maxTo.grow(-maxTo.width / 2 + minimumSize.width,
-maxTo.height / 2 + minimumSize.height);
frame.setMaximizedBounds(maxTo);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
robot.delay(1000);
Rectangle actual = frame.getBounds();
if (!actual.equals(maxTo)) {
System.err.println("Actual: " + actual);
System.err.println("Expected: " + maxTo);
throw new RuntimeException("Wrong bounds");
}
} finally {
frame.dispose();
}
}
}
}
}

View file

@ -0,0 +1,82 @@
/*
* Copyright (c) 2015, 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.
*/
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
/**
* @test
* @key headful
* @bug 8065739 8129569
* @requires (os.family == "mac")
* @summary [macosx] Frame warps to lower left of screen when displayed
* @author Alexandr Scherbatiy
* @run main MaximizedToUnmaximized
*/
public class MaximizedToUnmaximized {
public static void main(String[] args) throws Exception {
testFrame(false);
testFrame(true);
}
static void testFrame(boolean isUndecorated) throws Exception {
Frame frame = new Frame();
try {
Robot robot = new Robot();
robot.setAutoDelay(100);
frame.setUndecorated(isUndecorated);
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);
frame.pack();
frame.setBounds(rect);
frame.setVisible(true);
robot.waitForIdle();
robot.delay(500);
if (frame.getWidth() <= width / 2
|| frame.getHeight() <= height / 2) {
throw new RuntimeException("Frame size is small!");
}
if (!isUndecorated && frame.getExtendedState() != Frame.MAXIMIZED_BOTH) {
throw new RuntimeException("Frame state does not equal"
+ " MAXIMIZED_BOTH!");
}
} finally {
frame.dispose();
}
}
}

View file

@ -0,0 +1,101 @@
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.Frame;
import javax.swing.JFrame;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.lang.reflect.InvocationTargetException;
/*
* @test
* @key headful
* @bug 8022302
* @summary Set extendedState Frame.MAXIMIZED_BOTH for undecorated Frame and JFrame.
* Check if resulted size is equal to GraphicsEnvironment.getMaximumWindowBounds().
*
* @library /lib/client
* @build ExtendedRobot
* @run main MaximizedUndecorated
*/
public class MaximizedUndecorated {
private Frame frame;
private ExtendedRobot robot;
public static void main(String args[]) {
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
return;
}
MaximizedUndecorated test = new MaximizedUndecorated();
boolean doPass = true;
try{
if( !test.doTest(true) ) {
System.out.println("Actual bounds differ from Maximum Window Bounds for JFrame");
doPass = false;
}
if( !test.doTest(false) ) {
System.out.println("Actual bounds differ from Maximum Window Bounds for Frame");
doPass = false;
}
}catch(Exception ie) {
ie.printStackTrace();
throw new RuntimeException("Interrupted or InvocationTargetException occured");
}
if(!doPass) {
throw new RuntimeException("Actual bounds of undecorated frame differ from Maximum Windows Bounds for this platform");
}
}
MaximizedUndecorated() {
try {
robot = new ExtendedRobot();
}catch(Exception ex) {
ex.printStackTrace();
throw new RuntimeException("Cannot create robot");
}
}
boolean doTest(boolean swingFrame) throws InterruptedException, InvocationTargetException {
EventQueue.invokeAndWait( () -> {
frame = swingFrame? new JFrame("Test Frame") : new Frame("Test Frame");
frame.setLayout(new FlowLayout());
frame.setBounds(50,50,300,300);
frame.setUndecorated(true);
frame.setVisible(true);
});
robot.waitForIdle(2000);
EventQueue.invokeAndWait( () -> {
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
});
robot.waitForIdle(2000);
Rectangle actualBounds = frame.getBounds();
Rectangle expectedBounds = GraphicsEnvironment.
getLocalGraphicsEnvironment().getMaximumWindowBounds();
EventQueue.invokeAndWait( () -> {
frame.dispose();
});
return actualBounds.equals(expectedBounds);
}
}

View file

@ -0,0 +1,273 @@
/*
* 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.Button;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.MediaTracker;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.ImageProducer;
import java.net.URL;
/*
* @test
* @bug 4175560
* @summary Test use of user-defined icons
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MegaIconTest
*/
public class MegaIconTest {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
Each of the buttons in the main window represents a test
of certain icon functionality - background transparency/opacity
of the icon, scaling etc.
Clicking on each button brings up a window displaying the graphic
that should appear in the corresponding icon.
Click on each button, minimize the resulting window, and check that
the icon is displayed as the test name indicates.
On Win32, icons should also be displayed correctly in the title bar.
If all the test pass, then this test passes, else fail.
""";
PassFailJFrame.builder()
.title("Test Instructions")
.instructions(INSTRUCTIONS)
.rows(10)
.columns(35)
.testUI(MegaIconTest::initialize)
.build()
.awaitAndCheck();
}
public static Frame initialize() {
//Create the iconTestFrames and add to IconTestButtons
IconTestButtons itb = new IconTestButtons(new IconTestFrame[]{
new IconTestFrame("Opaque, Scaled Icon Test",
"duke_404.gif"),
new IconTestFrame("Transparent Icon",
"dukeWave.gif"),
new IconTestFrameBG("Transparent, Scaled Icon with bg",
"fight.gif", Color.red),
new IconTestFrameDlg("Transparent icon w/ Dialog",
"dukeWave.gif")
});
itb.pack();
return itb;
}
}
class IconTestButtons extends Frame {
public IconTestButtons(IconTestFrame[] iconTests) {
IconTestFrame tempTest;
Button newBtn;
Panel newPnl;
DoneLabel newLbl;
setTitle("MegaIconTest");
setLayout(new GridLayout(iconTests.length, 1));
//For each icon test frame
//Get name, add button with name and action to
//display the window, and add label "done" after
for (int i = 0; i < iconTests.length; i++) {
tempTest = iconTests[i];
newBtn = new Button(tempTest.getTestName());
newLbl = new DoneLabel();
newBtn.addActionListener(new IconTestActionListener(tempTest,
newLbl));
newPnl = new Panel();
newPnl.add(newBtn);
newPnl.add(newLbl);
add(newPnl);
}
}
protected class DoneLabel extends Label {
public DoneLabel() {
super("Done");
setVisible(false);
}
}
protected class IconTestActionListener implements ActionListener {
IconTestFrame f;
DoneLabel l;
public IconTestActionListener(IconTestFrame frame, DoneLabel label) {
this.f = frame;
this.l = label;
}
public void actionPerformed(ActionEvent e) {
f.pack();
f.setVisible(true);
l.setVisible(true);
IconTestButtons.this.pack();
}
}
}
class IconTestFrame extends Frame {
private String testName;
int width, height;
Image iconImage;
MediaTracker tracker;
public IconTestFrame(String testName, String iconFileName) {
super(testName);
this.testName = testName;
tracker = new MediaTracker(this);
//Set icon image
URL url = MegaIconTest.class.getResource(iconFileName);
Toolkit tk = Toolkit.getDefaultToolkit();
if (tk == null) {
System.out.println("Toolkit is null!");
}
if (url == null) {
System.out.println("Can't load icon is null!");
return;
}
try {
iconImage = tk.createImage((ImageProducer) url.getContent());
} catch (java.io.IOException e) {
System.out.println("Unable to load icon image from url: " + url);
}
tracker.addImage(iconImage, 0);
try {
tracker.waitForAll();
} catch (java.lang.InterruptedException e) {
System.err.println(e);
}
width = iconImage.getWidth(this);
height = iconImage.getHeight(this);
setIconImage(iconImage);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
}
});
setLayout(new BorderLayout());
setBackground(Color.YELLOW);
//Add the icon graphic and instructions to the Frame
add(new IconCanvas(), "Center");
pack();
}
class IconCanvas extends Canvas {
public void paint(Graphics g) {
if (IconTestFrame.this.iconImage == null) {
throw new NullPointerException();
}
g.drawImage(IconTestFrame.this.iconImage, 0, 0, this);
}
public Dimension getPreferredSize() {
return new Dimension(IconTestFrame.this.width,
IconTestFrame.this.height);
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
public Dimension getMaximumSize() {
return getPreferredSize();
}
}
public String getTestName() {
return testName;
}
}
class IconTestFrameBG extends IconTestFrame {
public IconTestFrameBG(String testName, String iconFileName, Color bg) {
super(testName, iconFileName);
setBackground(bg);
Panel p = new Panel();
p.setLayout(new GridLayout(3, 1));
p.add(new Label("The background of this window has been set."));
p.add(new Label("Unless the default icon background is the same color,"));
p.add(new Label("the icon background should NOT be this color."));
add(p, "North");
pack();
}
}
class IconTestFrameDlg extends IconTestFrame implements ActionListener {
Dialog dlg;
Button dlgBtn;
public IconTestFrameDlg(String testName, String iconFilename) {
super(testName, iconFilename);
Panel p = new Panel();
p.setLayout(new GridLayout(4, 1));
p.add(new Label("Click on the button below to display a child dialog."));
p.add(new Label("On Win32, the Dialog's titlebar icon should match"));
p.add(new Label("the titlebar icon of this window."));
p.add(new Label("Minimizing this Frame should yield only one icon."));
add(p, "North");
dlg = new Dialog(this);
dlg.setSize(200, 200);
dlg.add(new Label("Dialog stuff."));
dlg.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
}
});
dlgBtn = new Button("Display Dialog");
dlgBtn.addActionListener(this);
add(dlgBtn, "South");
}
public void actionPerformed(ActionEvent e) {
dlg.setVisible(true);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

View file

@ -0,0 +1,81 @@
/*
* 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.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Menu;
import java.awt.MenuBar;
/*
* @test
* @bug 4180577
* @summary offset problems with menus in frames: (2 * 1) should be (2 * menuBarBorderSize)
* @requires (os.family == "linux" | os.family == "windows")
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MenuBarOffsetTest
*/
public class MenuBarOffsetTest {
private static final String INSTRUCTIONS = """
If a menubar containing a menubar item labeled Test appears.
in a frame, and fits within the frame, press Pass, else press Fail.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("MenuBarOffsetTest Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(FrameTest::new)
.build()
.awaitAndCheck();
}
private static class FrameTest extends Frame {
public FrameTest() {
super("MenuBarOffsetTest FrameTest");
MenuBar m = new MenuBar();
setMenuBar(m);
Menu test = m.add(new Menu("Test"));
test.add("1");
test.add("2");
setSize(100, 100);
}
public void paint(Graphics g) {
setForeground(Color.red);
Insets i = getInsets();
Dimension d = getSize();
System.err.println(getBounds());
System.err.println("" + i);
g.drawRect(i.left, i.top,
d.width - i.left - i.right - 1,
d.height - i.top - i.bottom - 1);
}
}
}

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.Button;
import java.awt.CheckboxMenuItem;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextField;
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
/*
* @test
* @bug 4133279
* @summary Clicking in menu in inactive frame crashes application
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MenuCrash
*/
public class MenuCrash {
private static final String INSTRUCTIONS = """
Two frames will appear, alternate between frames by clicking on the
menubar of the currently deactivated frame and verify no crash occurs.
Try mousing around the menus and choosing various items to see the menu
item name reflected in the text field. Note that CheckBoxMenuItems do
not fire action events so the check menu item (Item 03) will not change
the field.
""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("MenuCrash Instructions")
.instructions(INSTRUCTIONS)
.columns(45)
.testUI(MenuCrash::createAndShowUI)
.positionTestUIRightRow()
.build()
.awaitAndCheck();
}
private static List<Window> createAndShowUI() {
Frame frame1 = new MenuFrame("Frame 1 MenuCrash");
Frame frame2 = new MenuFrame("Frame 2 MenuCrash");
frame1.setSize(300, 200);
frame2.setSize(300, 200);
frame1.validate();
frame2.validate();
return List.of(frame1, frame2);
}
static class MenuFrame extends Frame {
private final TextField field;
MenuFrame(String name) {
super(name);
setLayout(new FlowLayout());
Button removeMenus = new Button("Remove Menus");
removeMenus.addActionListener(ev -> remove(getMenuBar()));
Button addMenus = new Button("Add Menus");
addMenus.addActionListener(ev -> setupMenus());
add(removeMenus);
add(addMenus);
field = new TextField(20);
add(field);
addWindowListener(
new WindowAdapter() {
public void windowActivated(WindowEvent e) {
setupMenus();
}
}
);
addComponentListener(
new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
System.out.println(MenuFrame.this);
}
}
);
pack();
}
private void addMenuListeners() {
MenuBar menuBar = getMenuBar();
for (int nMenu = 0; nMenu < menuBar.getMenuCount(); nMenu++) {
Menu menu = menuBar.getMenu(nMenu);
for (int nMenuItem = 0; nMenuItem < menu.getItemCount(); nMenuItem++) {
MenuItem item = menu.getItem(nMenuItem);
item.addActionListener(ev -> field.setText(ev.getActionCommand()));
}
}
}
private void setupMenus() {
MenuItem miSetLabel = new MenuItem("Item 01");
MenuItem miSetEnabled = new MenuItem("Item 02");
CheckboxMenuItem miSetState = new CheckboxMenuItem("Item 03");
MenuItem miAdded = new MenuItem("Item 04 Added");
MenuBar menuBar = new MenuBar();
Menu menu1 = new Menu("Menu 01");
menu1.add(miSetLabel);
menu1.add(miSetEnabled);
menu1.add(miSetState);
menuBar.add(menu1);
setMenuBar(menuBar);
// now that the peers are created, screw
// around with the menu items
miSetLabel.setLabel("Menu 01 - SetLabel");
miSetEnabled.setEnabled(false);
miSetState.setState(true);
menu1.add(miAdded);
menu1.remove(miAdded);
menu1.addSeparator();
menu1.add(miAdded);
Menu menu2 = new Menu("Menu 02");
menuBar.add(menu2);
menuBar.remove(menu2);
menuBar.add(menu2);
menu2.add(new MenuItem("Foo"));
menu1.setLabel("Menu Number 1");
menu2.setLabel("Menu Number 2");
addMenuListeners();
}
}
}

View file

@ -0,0 +1,139 @@
/*
* 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.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import jtreg.SkippedException;
/*
* @test
* @key headful
* @bug 6251941
* @summary Undecorated frames should be minimizable.
* @library /test/lib
* @build jtreg.SkippedException
* @run main MinimizeUndecoratedTest
*/
public class MinimizeUndecoratedTest {
private static final int SIZE = 300;
private static final CountDownLatch isMinimized = new CountDownLatch(1);
private static Frame frame;
private static Robot robot;
private static volatile Point frameLoc;
public static void main(String[] args) throws Exception {
if (!Toolkit.getDefaultToolkit()
.isFrameStateSupported(Frame.ICONIFIED)) {
throw new SkippedException("Test is not applicable as"
+ " the Window manager does not support MINIMIZATION");
}
try {
robot = new Robot();
EventQueue.invokeAndWait(MinimizeUndecoratedTest::createUI);
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(() -> frameLoc = frame.getLocationOnScreen());
Color beforeColor = robot.getPixelColor(frameLoc.x + SIZE / 2,
frameLoc.y + SIZE / 2);
EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.ICONIFIED));
robot.waitForIdle();
robot.delay(500);
if (!isMinimized.await(8, TimeUnit.SECONDS)) {
throw new RuntimeException("Window iconified event not received.");
}
EventQueue.invokeAndWait(() -> System.out.println("Frame state: "
+ frame.getExtendedState()));
Color afterColor = robot.getPixelColor(frameLoc.x + SIZE / 2,
frameLoc.y + SIZE / 2);
if (beforeColor.equals(afterColor)) {
saveScreenCapture();
throw new RuntimeException("Color before & after minimization : "
+ beforeColor + " vs " + afterColor + "\n"
+ "Test Failed !! Frame not minimized.");
}
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.setExtendedState(Frame.NORMAL);
frame.dispose();
}
});
}
}
private static void createUI() {
frame = new Frame("Test Minimization of Frame");
frame.setSize(SIZE, SIZE);
frame.setBackground(Color.GREEN);
frame.setResizable(true);
frame.setUndecorated(true);
frame.addWindowStateListener(new WindowAdapter() {
@Override
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == Frame.ICONIFIED) {
System.out.println("Window iconified event received.");
isMinimized.countDown();
}
}
});
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void saveScreenCapture() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage image = robot.createScreenCapture(new Rectangle(new Point(),
screenSize));
try {
ImageIO.write(image, "png", new File("MinimizedFrame.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,114 @@
/*
* 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 javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/*
* @test
* @key headful
* @bug 1256759
* @summary Checks that Frames with a very small size don't cause Motif
* to generate VendorShells which consume the entire desktop.
*/
public class MinimumSizeTest {
private static final Color BG_COLOR = Color.RED;
private static Frame backgroundFrame;
private static Frame testedFrame;
private static Robot robot;
private static final Point location = new Point(200, 200);
private static final Point[] testPointLocations = {
new Point(100, 200),
new Point(200, 100),
new Point(450, 210),
new Point(210, 350),
};
public static void main(String[] args) throws Exception {
robot = new Robot();
try {
EventQueue.invokeAndWait(MinimumSizeTest::initAndShowGui);
robot.waitForIdle();
robot.delay(500);
test();
System.out.println("Test passed.");
} finally {
EventQueue.invokeAndWait(() -> {
backgroundFrame.dispose();
testedFrame.dispose();
});
}
}
private static void test() {
for (Point testLocation : testPointLocations) {
Color pixelColor = robot.getPixelColor(testLocation.x, testLocation.y);
if (!pixelColor.equals(BG_COLOR)) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage screenCapture = robot.createScreenCapture(new Rectangle(screenSize));
try {
ImageIO.write(screenCapture, "png", new File("failure.png"));
} catch (IOException ignored) {}
throw new RuntimeException("Pixel color does not match expected color %s at %s"
.formatted(pixelColor, testLocation));
}
}
}
private static void initAndShowGui() {
backgroundFrame = new Frame("MinimumSizeTest background");
backgroundFrame.setUndecorated(true);
backgroundFrame.setBackground(BG_COLOR);
backgroundFrame.setBounds(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
backgroundFrame.setVisible(true);
testedFrame = new MinimumSizeTestFrame();
testedFrame.setVisible(true);
}
private static class MinimumSizeTestFrame extends Frame {
public MinimumSizeTestFrame() {
super("MinimumSizeTest");
setVisible(true);
setBackground(Color.BLUE);
setSize(0, 0);
setLocation(location);
}
}
}

View file

@ -0,0 +1,171 @@
/*
* Copyright (c) 1999, 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
* @summary To check proper WINDOW_EVENTS are triggered when Frame gains
* or loses the focus
* @run main ActiveAWTWindowTest
*/
import java.awt.AWTException;
import java.awt.BorderLayout;
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.Point;
import java.awt.Robot;
import java.awt.TextField;
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.WindowFocusListener;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
import javax.swing.JComponent;
public class ActiveAWTWindowTest {
private static Frame frame, frame2;
private static Button button, button2;
private static TextField textField, textField2;
private static CountDownLatch windowActivatedLatch = new CountDownLatch(1);
private static CountDownLatch windowDeactivatedLatch = new CountDownLatch(1);
private static CountDownLatch windowFocusGainedLatch = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> {
initializeGUI();
});
doTest();
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
if (frame2 != null) {
frame2.dispose();
}
});
}
private static void initializeGUI() {
frame = new Frame();
frame.setLayout(new FlowLayout());
frame.setLocation(5, 20);
frame.setSize(200, 200);
frame.setUndecorated(true);
frame.addWindowFocusListener(new WindowFocusListener() {
@Override
public void windowGainedFocus(WindowEvent event) {
System.out.println("Frame Focus gained");
windowFocusGainedLatch.countDown();
}
@Override
public void windowLostFocus(WindowEvent event) {
System.out.println("Frame Focus lost");
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
System.out.println("Undecorated Frame is activated");
windowActivatedLatch.countDown();
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("Undecorated Frame got Deactivated");
windowDeactivatedLatch.countDown();
}
});
textField = new TextField("TextField");
button = new Button("Click me");
button.addActionListener(e -> textField.setText("Focus gained"));
frame.setBackground(Color.green);
frame.add(button);
frame.add(textField);
frame.setVisible(true);
frame2 = new Frame();
frame2.setLayout(new FlowLayout());
frame2.setLocation(5, 250);
frame2.setSize(200, 200);
frame2.setBackground(Color.green);
button2 = new Button("Click me");
textField2 = new TextField("TextField");
button2.addActionListener(e -> textField2.setText("Got the focus"));
frame2.add(button2, BorderLayout.SOUTH);
frame2.add(textField2, BorderLayout.NORTH);
frame2.setVisible(true);
}
private static void doTest() throws AWTException, InterruptedException {
Robot robot = new Robot();
robot.setAutoDelay(150);
robot.setAutoWaitForIdle(true);
if (!windowFocusGainedLatch.await(1000, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Frame did not gain focus");
}
clickButtonCenter(robot, button);
if (!windowActivatedLatch.await(1000, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Frame was not activated");
}
clickButtonCenter(robot, button2);
if (!windowDeactivatedLatch.await(2000, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Frame was not deactivated");
}
if (frame.hasFocus()) {
throw new RuntimeException("Frame did not lose focus");
}
}
private static void clickButtonCenter(Robot robot, Component button) {
Point location = button.getLocationOnScreen();
Dimension size = button.getSize();
int x = location.x + size.width / 2;
int y = location.y + size.height / 2;
robot.mouseMove(x, y);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
}

View file

@ -0,0 +1,220 @@
/*
* Copyright (c) 1999, 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.
*/
/*
* @test
* @key headful
* @summary To check proper WINDOW_EVENTS are triggered when JFrame gains or losses the focus
* @author Jitender(jitender.singh@eng.sun.com) area=AWT
* @author yan
* @library /lib/client
* @build ExtendedRobot
* @run main ActiveSwingWindowTest
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class ActiveSwingWindowTest {
private JFrame frame, frame2;
private JButton button, button2;
private JTextField textField, textField2;
private int eventType, eventType1;
private ExtendedRobot robot;
private Object lock1 = new Object();
private Object lock2 = new Object();
private Object lock3 = new Object();
private boolean passed = true;
private int delay = 150;
public static void main(String[] args) {
ActiveSwingWindowTest test = new ActiveSwingWindowTest();
test.doTest();
}
public ActiveSwingWindowTest() {
try{
EventQueue.invokeAndWait( () -> {
initializeGUI();
});
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Interrupted or unexpected Exception occured");
}
}
private void initializeGUI() {
frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setLocation(5, 20);
frame.setSize(200, 200);
frame.setUndecorated(true);
frame.addWindowFocusListener(new WindowFocusListener() {
public void windowGainedFocus(WindowEvent event) {
System.out.println("Frame Focus gained");
synchronized (lock3) {
try {
lock3.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void windowLostFocus(WindowEvent event) {
System.out.println("Frame Focus lost");
}
});
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
eventType = WindowEvent.WINDOW_ACTIVATED;
System.out.println("Undecorated Frame is activated\n");
synchronized (lock1) {
try {
lock1.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void windowDeactivated(WindowEvent e) {
eventType = WindowEvent.WINDOW_DEACTIVATED;
System.out.println("Undecorated Frame got Deactivated\n");
synchronized (lock2) {
try {
lock2.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
textField = new JTextField("TextField");
button = new JButton("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("Focus gained");
}
});
frame.setBackground(Color.green);
frame.add(button);
frame.add(textField);
frame.setVisible(true);
frame2 = new JFrame();
frame2.setLayout(new FlowLayout());
frame2.setLocation(5, 250);
frame2.setSize(200, 200);
frame2.setBackground(Color.green);
button2 = new JButton("Click me");
textField2 = new JTextField("TextField");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField2.setText("Got the focus");
}
});
frame2.add(button2, BorderLayout.SOUTH);
frame2.add(textField2, BorderLayout.NORTH);
frame2.setVisible(true);
frame.toFront();
}
public void doTest() {
try {
robot = new ExtendedRobot();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Cannot create robot");
}
robot.waitForIdle(5*delay);
robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2,
button.getLocationOnScreen().y + button.getSize().height / 2);
robot.waitForIdle(delay);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle(delay);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
if (eventType != WindowEvent.WINDOW_ACTIVATED) {
synchronized (lock1) {
try {
lock1.wait(delay * 10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (eventType != WindowEvent.WINDOW_ACTIVATED) {
passed = false;
System.err.println("WINDOW_ACTIVATED event did not occur when the " +
"undecorated frame is activated!");
}
eventType1 = -1;
eventType = -1;
robot.mouseMove(button2.getLocationOnScreen().x + button2.getSize().width / 2,
button2.getLocationOnScreen().y + button2.getSize().height / 2);
robot.waitForIdle(delay);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle(delay);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
if (eventType != WindowEvent.WINDOW_DEACTIVATED) {
synchronized (lock2) {
try {
lock2.wait(delay * 10);
} catch (Exception e) {
}
}
}
if (eventType != WindowEvent.WINDOW_DEACTIVATED) {
passed = false;
System.err.println("FAIL: WINDOW_DEACTIVATED event did not occur for the " +
"undecorated frame when another frame gains focus!");
}
if (frame.hasFocus()) {
passed = false;
System.err.println("FAIL: The undecorated frame has focus even when " +
"another frame is clicked!");
}
if (!passed) {
//captureScreenAndSave();
System.err.println("Test failed!");
throw new RuntimeException("Test failed.");
} else {
System.out.println("Test passed");
}
}
}

View file

@ -0,0 +1,213 @@
/*
* Copyright (c) 1999, 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.
*/
/*
* @test
* @key headful
* @summary To make sure Undecorated Frame triggers correct windows events while closing
* @author Jitender(jitender.singh@eng.sun.com) area=AWT*
* @author yan
* @library /lib/client
* @build ExtendedRobot
* @run main FrameCloseTest
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JButton;
public class FrameCloseTest {
private static int delay = 150;
private Frame frame, frame2;
private Component button, dummyButton;
private int eventType, eventType1, eventType2;
private ExtendedRobot robot;
private Object lock1 = new Object();
private Object lock2 = new Object();
private Object lock3 = new Object();
private Object lock4 = new Object();
private boolean passed = true;
public static void main(String[] args) {
FrameCloseTest test = new FrameCloseTest();
test.doTest(false);
test.doTest(true);
}
private void initializeGUI(boolean swingFrame) {
frame = swingFrame? new Frame() : new JFrame();
frame.setLayout(new FlowLayout());
frame.setLocation(5, 20);
frame.setSize(200, 200);
frame.setUndecorated(true);
frame.addWindowFocusListener(new WindowFocusListener() {
public void windowGainedFocus(WindowEvent event) {
System.out.println("Frame Focus gained");
synchronized (lock4) {
try {
lock4.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void windowLostFocus(WindowEvent event) {
System.out.println("Frame Focus lost");
}
});
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
eventType = WindowEvent.WINDOW_ACTIVATED;
System.out.println("Undecorated Frame is activated");
synchronized (lock1) {
try {
lock1.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void windowDeactivated(WindowEvent e) {
eventType1 = WindowEvent.WINDOW_DEACTIVATED;
System.out.println("Undecorated Frame got Deactivated");
synchronized (lock2) {
try {
lock2.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void windowClosed(WindowEvent e) {
eventType2 = WindowEvent.WINDOW_CLOSED;
System.out.println("Undecorated Frame got closed");
synchronized (lock3) {
try {
lock3.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
dummyButton = swingFrame? new JButton("Click me") : new Button("Click me");
frame.setBackground(Color.green);
frame.add((button = createButton(swingFrame, "Close me")));
frame.add(dummyButton);
frame.setVisible(true);
frame.toFront();
}
private Component createButton(boolean swingControl, String txt) {
if(swingControl) {
JButton jbtn = new JButton(txt);
jbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
return jbtn;
}else {
Button btn = new Button(txt);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
return btn;
}
}
public void doTest(boolean swingControl) {
try {
Toolkit.getDefaultToolkit().getSystemEventQueue().invokeAndWait(new Runnable() {
public void run() {
initializeGUI(swingControl);
}
});
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Interrupted or unexpected Exception occured");
}
try {
robot = new ExtendedRobot();
robot.waitForIdle(1000);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Cannot create robot");
}
robot.mouseMove(dummyButton.getLocationOnScreen().x + dummyButton.getSize().width / 2,
dummyButton.getLocationOnScreen().y + dummyButton.getSize().height / 2);
robot.waitForIdle(delay);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle(delay);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.waitForIdle(delay);
eventType1 = -1;
eventType = -1;
eventType2 = -1;
robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2,
button.getLocationOnScreen().y + button.getSize().height / 2);
robot.waitForIdle(delay);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.waitForIdle(delay);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.waitForIdle(delay * 10);
if (eventType2 != WindowEvent.WINDOW_CLOSED) {
synchronized (lock3) {
try {
lock3.wait(delay * 10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (eventType2 != WindowEvent.WINDOW_CLOSED) {
passed = false;
System.err.println("WINDOW_CLOSED event did not occur when the " +
"undecorated frame is closed!");
}
if (eventType == WindowEvent.WINDOW_ACTIVATED) {
passed = false;
System.err.println("WINDOW_ACTIVATED event occured when the " +
"undecorated frame is closed!");
}
if (!passed) {
System.err.println("Test failed!");
throw new RuntimeException("Test failed");
} else {
System.out.println("Test passed");
}
}
}

View file

@ -0,0 +1,270 @@
/*
* 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
* @key headful
* @summary Make sure that on changing state of Undecorated Frame,
* all the components on it are repainted correctly
* @author Jitender(jitender.singh@eng.sun.com) area=AWT
* @author yan
* @library /lib/client /test/lib
* @build ExtendedRobot jdk.test.lib.Platform
* @run main RepaintTest
*/
import jdk.test.lib.Platform;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.TextField;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
public class RepaintTest {
private static final int delay = 150;
private Frame frame;
private Component button;
private Component textField;
private ExtendedRobot robot;
private final Object buttonLock = new Object();
private volatile boolean buttonClicked = false;
private final int MAX_TOLERANCE_LEVEL = 10;
public static void main(String[] args) throws Exception {
RepaintTest test = new RepaintTest();
try {
test.doTest(false);
} finally {
EventQueue.invokeAndWait(test::dispose);
}
try {
test.doTest(true);
} finally {
EventQueue.invokeAndWait(test::dispose);
}
}
private void initializeGUI(boolean swingControl) {
frame = swingControl ? new JFrame() : new Frame();
frame.setLayout(new BorderLayout());
frame.setSize(300, 300);
frame.setUndecorated(true);
button = createButton(swingControl, (swingControl ? "Swing Button" : "AWT Button"));
textField = swingControl ? new JTextField("TextField") : new TextField("TextField");
Container panel1 = swingControl ? new JPanel() : new Panel();
Container panel2 = swingControl ? new JPanel() : new Panel();
panel1.add(button);
panel2.add(textField);
frame.add(panel2, BorderLayout.SOUTH);
frame.add(panel1, BorderLayout.NORTH);
frame.setLocationRelativeTo(null);
frame.setBackground(Color.green);
frame.setVisible(true);
}
private void dispose() {
if (frame != null) {
frame.dispose();
}
}
private Component createButton(boolean swingControl, String txt) {
ActionListener actionListener = e -> {
buttonClicked = true;
System.out.println("Clicked!!");
synchronized (buttonLock) {
try {
buttonLock.notifyAll();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
if(swingControl) {
JButton jbtn = new JButton(txt);
jbtn.addActionListener(actionListener);
return jbtn;
} else {
Button btn = new Button(txt);
btn.addActionListener(actionListener);
return btn;
}
}
public void doTest(boolean swingControl) throws Exception {
robot = new ExtendedRobot();
robot.setAutoDelay(50);
EventQueue.invokeAndWait(() -> initializeGUI(swingControl));
robot.waitForIdle(1000);
robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2,
button.getLocationOnScreen().y + button.getSize().height / 2);
robot.click();
robot.waitForIdle(delay);
if (! buttonClicked) {
synchronized (buttonLock) {
try {
buttonLock.wait(delay * 10);
} catch (Exception e) {
}
}
}
if (! buttonClicked) {
System.err.println("ActionEvent not triggered when " +
"button is clicked!");
throw new RuntimeException("ActionEvent not triggered");
}
robot.waitForIdle(1000); // Need to wait until look of the button
// returns to normal undepressed
if (!paintAndRepaint(button, (swingControl ? "J" : "") + "Button")
|| !paintAndRepaint(textField, (swingControl ? "J" : "") + "TextField")) {
throw new RuntimeException("Test failed");
}
}
private boolean paintAndRepaint(Component comp, String prefix) throws Exception {
boolean passed = true;
//Capture the component & compare it's dimensions
//before iconifying & after frame comes back from
//iconified to normal state
System.out.printf("paintAndRepaint %s %s\n", prefix, comp);
Point p = comp.getLocationOnScreen();
Rectangle bRect = new Rectangle((int)p.getX(), (int)p.getY(),
comp.getWidth(), comp.getHeight());
BufferedImage capturedImage = robot.createScreenCapture(bRect);
BufferedImage frameImage = robot.createScreenCapture(frame.getBounds());
EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.ICONIFIED));
robot.waitForIdle(1500);
EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.NORMAL));
robot.waitForIdle(1500);
if (Platform.isOnWayland()) {
// Robot.mouseMove does not move the actual mouse cursor on the
// screen in X11 compatibility mode on Wayland, but only within
// the XWayland server.
// This can cause the test to fail if the actual mouse cursor on
// the screen is somewhere over the test window, so that when the
// test window is restored from the iconified state, it's detected
// that the mouse cursor has moved to the mouse cursor position on
// the screen, and is no longer hovering over the button, so the
// button is painted differently.
robot.mouseMove(button.getLocationOnScreen().x + button.getSize().width / 2,
button.getLocationOnScreen().y + button.getSize().height / 2);
robot.waitForIdle();
}
if (! p.equals(comp.getLocationOnScreen())) {
passed = false;
System.err.println("FAIL: Frame or component did not get positioned in the same place");
}
p = comp.getLocationOnScreen();
bRect = new Rectangle((int)p.getX(), (int)p.getY(),
comp.getWidth(), comp.getHeight());
BufferedImage capturedImage2 = robot.createScreenCapture(bRect);
BufferedImage frameImage2 = robot.createScreenCapture(frame.getBounds());
if (!compareImages(capturedImage, capturedImage2)) {
passed = false;
try {
javax.imageio.ImageIO.write(capturedImage, "png",
new File(prefix + "BeforeMinimize.png"));
javax.imageio.ImageIO.write(capturedImage2, "png",
new File(prefix + "AfterMinimize.png"));
javax.imageio.ImageIO.write(frameImage, "png",
new File("Frame" + prefix + "BeforeMinimize.png"));
javax.imageio.ImageIO.write(frameImage2, "png",
new File("Frame" + prefix + "AfterMinimize.png"));
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("FAIL: The frame or component did not get repainted correctly");
}
return passed;
}
//method for comparing two images
public boolean compareImages(BufferedImage capturedImg, BufferedImage realImg) {
int capturedPixels[], realPixels[];
int imgWidth, imgHeight;
boolean comparison = true;
int toleranceLevel = 0;
imgWidth = capturedImg.getWidth(null);
imgHeight = capturedImg.getHeight(null);
capturedPixels = new int[imgWidth * imgHeight];
realPixels = new int[imgWidth * imgHeight];
try {
PixelGrabber pgCapturedImg = new PixelGrabber(capturedImg, 0, 0,
imgWidth, imgHeight, capturedPixels, 0, imgWidth);
pgCapturedImg.grabPixels();
PixelGrabber pgRealImg = new PixelGrabber(realImg, 0, 0,
imgWidth, imgHeight, realPixels, 0, imgWidth);
pgRealImg.grabPixels();
for(int i=0; i<(imgWidth * imgHeight); i++) {
if(capturedPixels[i] != realPixels[i]) {
toleranceLevel++;
}
}
if (toleranceLevel > MAX_TOLERANCE_LEVEL) {
comparison = false;
}
} catch(Exception ie) {
ie.printStackTrace();
comparison = false;
}
return comparison;
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2002, 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.Frame;
import java.awt.Toolkit;
import javax.swing.JFrame;
import java.awt.EventQueue;
import java.awt.FlowLayout;
/*
* @test
* @key headful
* @bug 4464710 7102299
* @summary Recurring bug is, an undecorated JFrame cannot be set iconified
* before setVisible(true)
*
* @run main UndecoratedInitiallyIconified
*/
public class UndecoratedInitiallyIconified {
private static JFrame frame;
public static void main(String args[]) throws Exception {
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.ICONIFIED)) {
return;
}
EventQueue.invokeAndWait( () -> {
frame = new JFrame("Test Frame");
frame.setLayout(new FlowLayout());
frame.setBounds(50,50,300,300);
frame.setUndecorated(true);
frame.setExtendedState(Frame.ICONIFIED);
if(frame.getExtendedState() != Frame.ICONIFIED) {
throw new RuntimeException("getExtendedState is not Frame.ICONIFIED as expected");
}
});
}
}

View file

@ -0,0 +1,498 @@
/*
* 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.
*/
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.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
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.Rectangle;
import java.awt.RenderingHints;
import java.awt.TextField;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import jtreg.SkippedException;
/*
* @test
* @bug 4312921
* @key multimon
* @library /java/awt/regtesthelpers /test/lib
* @build PassFailJFrame
* @summary Tests that no garbage is painted on primary screen with DGA
* @run main/manual MultiScreenTest
*/
public class MultiScreenTest {
static GraphicsEnvironment ge;
static GraphicsDevice[] gs;
public static void main(String[] args) throws Exception {
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gs = ge.getScreenDevices();
if (gs.length < 2) {
throw new SkippedException("You have only one monitor in your system");
}
MultiScreenTest obj = new MultiScreenTest();
String INSTRUCTIONS =
"This test is to be run only on multiscreen machine. " +
"You have " + gs.length + " monitors in your system.\n" +
"Actively drag the DitherTest frames on the secondary screen and " +
"if you see garbage appearing on your primary screen " +
"test failed otherwise it passed.";
PassFailJFrame.builder()
.instructions(INSTRUCTIONS)
.columns(40)
.testUI(obj::init)
.positionTestUI(MultiScreenTest::positionTestWindows)
.build()
.awaitAndCheck();
}
private static void positionTestWindows(List<Window> windows, PassFailJFrame.InstructionUI instructionUI) {
// Do nothing - the location of each window is set when they're created
}
public List<JFrame> init() {
List<JFrame> list = new ArrayList<>();
for (int j = 0; j < gs.length; j++) {
GraphicsConfiguration[] gc = gs[j].getConfigurations();
if (gc.length > 0) {
for (int i = 0; i < gc.length && i < 10; i++) {
JFrame f = new JFrame(gc[i]);
GCCanvas c = new GCCanvas(gc[i]);
Rectangle gcBounds = gc[i].getBounds();
int xoffs = gcBounds.x;
int yoffs = gcBounds.y;
f.getContentPane().add(c);
f.setTitle("Screen# " + j + ", GC#" + i);
f.setSize(300, 200);
// test displaying in right location
f.setLocation(400 + xoffs, (i * 150) + yoffs);
list.add(f);
Frame ditherfs = new Frame("DitherTest GC#" + i, gc[i]);
ditherfs.setLayout(new BorderLayout());
DitherTest ditherTest = new DitherTest(gc[i]);
ditherfs.add("Center", ditherTest);
ditherfs.setBounds(300, 200, 300, 200);
ditherfs.setLocation(750 + xoffs, (i * 50) + yoffs);
ditherfs.pack();
ditherfs.show();
ditherTest.start();
}
}
}
return list;
}
static class GCCanvas extends Canvas {
GraphicsConfiguration gc;
Rectangle bounds;
Dimension size = getSize();
public GCCanvas(GraphicsConfiguration gc) {
super(gc);
this.gc = gc;
bounds = gc.getBounds();
}
@Override
public void paint( Graphics _g ) {
Graphics2D g = (Graphics2D) _g;
g.drawRect(0, 0, size.width-1, size.height-1);
g.setColor(Color.lightGray);
g.draw3DRect(1, 1, size.width-3, size.height-3, true);
g.setColor(Color.red);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawString("HELLO!", 110, 10);
g.setColor(Color.blue);
g.drawString("ScreenSize="+Integer.toString(bounds.width)+"X"+
Integer.toString(bounds.height), 10, 20);
g.setColor(Color.green);
g.drawString(gc.toString(), 10, 30);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(Color.orange);
g.fillRect(40, 20, 50, 50);
g.setColor(Color.red);
g.drawRect(100, 20, 30, 30);
g.setColor(Color.gray);
g.drawLine(220, 20, 280, 40);
g.setColor(Color.cyan);
g.fillArc(150, 30, 30, 30, 0, 200);
}
@Override
public Dimension getPreferredSize(){
return new Dimension(300, 200);
}
}
static class DitherCanvas extends Canvas {
Image img;
static String calcString = "Calculating...";
GraphicsConfiguration mGC;
public DitherCanvas(GraphicsConfiguration gc) {
super(gc);
mGC = gc;
}
public GraphicsConfiguration getGraphicsConfig() {
return mGC;
}
@Override
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);
}
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(20, 20);
}
@Override
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 DitherTest 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;
Thread runner;
DitherControls XControls;
DitherControls YControls;
DitherCanvas canvas;
public DitherTest(GraphicsConfiguration gc) {
String xspec, yspec;
int xvals[] = new int[2];
int yvals[] = new int[2];
xspec = "red";
yspec = "blue";
int xmethod = colormethod(xspec, xvals);
int ymethod = colormethod(yspec, yvals);
setLayout(new BorderLayout());
XControls = new DitherControls(this, xvals[0], xvals[1],
xmethod, false);
YControls = new DitherControls(this, yvals[0], yvals[1],
ymethod, true);
YControls.addRenderButton();
add("North", XControls);
add("South", YControls);
add("Center", canvas = new DitherCanvas(gc));
}
public void start() {
runner = new Thread(this);
runner.start();
}
int colormethod(String s, int vals[]) {
int method = NOOP;
if (s == null) {
s = "";
}
String lower = s.toLowerCase();
int len = 0;
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) {
vals[0] = 0;
vals[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;
}
vals[0] = begval;
vals[1] = endval;
return method;
}
void applymethod(int c[], int method, int step, int total, int vals[]) {
if (method == NOOP)
return;
int val = ((total < 2)
? vals[0]
: vals[0] + ((vals[1] - vals[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;
}
}
@Override
public void run() {
canvas.setImage(null); // Wipe previous image
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 stopped during the calculation.
*/
Image calculateImage() {
Thread me = Thread.currentThread();
int width = canvas.getSize().width;
int height = canvas.getSize().height;
int xvals[] = new int[2];
int yvals[] = new int[2];
int xmethod = XControls.getParams(xvals);
int ymethod = YControls.getParams(yvals);
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, xvals);
applymethod(c, ymethod, j, height, yvals);
} else {
applymethod(c, ymethod, j, height, yvals);
applymethod(c, xmethod, i, width, xvals);
}
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));
}
public String getInfo() {
return "An interactive demonstration of dithering.";
}
public String[][] getParameterInfo() {
String[][] info = {
{"xaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}",
"The color of the Y axis. Default is RED."},
{"yaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}",
"The color of the X axis. Default is BLUE."}
};
return info;
}
}
static class DitherControls extends Panel implements ActionListener {
TextField start;
TextField end;
Button button;
Choice choice;
DitherTest dt;
static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER, 10, 5);
public DitherControls(DitherTest app, int s, int e, int type,
boolean vertical) {
dt = 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 int getParams(int vals[]) {
vals[0] = Integer.parseInt(start.getText());
vals[1] = Integer.parseInt(end.getText());
return choice.getSelectedIndex();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
dt.start();
}
}
}
}

View file

@ -0,0 +1,123 @@
/*
* Copyright (c) 2003, 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 4828019
@summary Frame/Window deadlock
@run main/timeout=9999 NonEDT_GUI_Deadlock
*/
import java.awt.*;
public class NonEDT_GUI_Deadlock {
boolean bOK = false;
Thread badThread = null;
public void start ()
{
final Frame theFrame = new Frame("Window test");
theFrame.setSize(240, 200);
Thread thKiller = new Thread() {
public void run() {
try {
Thread.sleep( 9000 );
}catch( Exception ex ) {
}
if( !bOK ) {
// oops,
//System.out.println("Deadlock!");
Runtime.getRuntime().halt(0);
}else{
//System.out.println("Passed ok.");
}
}
};
thKiller.setName("Killer thread");
thKiller.start();
Window w = new TestWindow(theFrame);
theFrame.toBack();
theFrame.setVisible(true);
theFrame.setLayout(new FlowLayout(FlowLayout.CENTER));
EventQueue.invokeLater(new Runnable() {
public void run() {
bOK = true;
}
});
}// start()
class TestWindow extends Window implements Runnable {
TestWindow(Frame f) {
super(f);
//setSize(240, 75);
setLocation(0, 75);
show();
toFront();
badThread = new Thread(this);
badThread.setName("Bad Thread");
badThread.start();
}
public void paint(Graphics g) {
g.drawString("Deadlock or no deadlock?",20,80);
}
public void run() {
long ts = System.currentTimeMillis();
while (true) {
if ((System.currentTimeMillis()-ts)>3000) {
this.setVisible( false );
dispose();
break;
}
toFront();
try {
Thread.sleep(80);
} catch (Exception e) {
}
}
}
}
public static void main(String args[]) {
NonEDT_GUI_Deadlock imt = new NonEDT_GUI_Deadlock();
imt.start();
}
}// class NonEDT_GUI_Deadlock

View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 2016, 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 8171949 8214046
* @summary Tests that bitwise mask is set and state listener is notified during state transition.
* @author Dmitry Markov
* @library ../../regtesthelpers
* @build Util
* @run main NormalToIconifiedTest
*/
import java.awt.Frame;
import java.awt.Robot;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.util.concurrent.atomic.AtomicBoolean;
import test.java.awt.regtesthelpers.Util;
public class NormalToIconifiedTest {
public static void main(String[] args) {
test(false);
test(true);
}
private static void test(final boolean undecorated) {
AtomicBoolean listenerNotified = new AtomicBoolean(false);
Robot robot = Util.createRobot();
Frame testFrame = new Frame("Test Frame");
testFrame.setUndecorated(undecorated);
testFrame.setSize(200, 200);
testFrame.addWindowStateListener(new WindowStateListener() {
@Override
public void windowStateChanged(WindowEvent e) {
listenerNotified.set(true);
synchronized (listenerNotified) {
listenerNotified.notifyAll();
}
}
});
testFrame.setVisible(true);
Frame mainFrame = new Frame("Main Frame");
mainFrame.setSize(200, 200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
Util.waitForIdle(robot);
try {
Util.clickOnComp(mainFrame, robot);
Util.waitForIdle(robot);
// NORMAL -> ICONIFIED
listenerNotified.set(false);
testFrame.setExtendedState(Frame.ICONIFIED);
Util.waitForIdle(robot);
Util.waitForCondition(listenerNotified, 2000);
if (!listenerNotified.get()) {
throw new RuntimeException("Test FAILED! Window state listener was not notified during NORMAL to" +
"ICONIFIED transition");
}
if (testFrame.getExtendedState() != Frame.ICONIFIED) {
throw new RuntimeException("Test FAILED! Frame is not in ICONIFIED state");
}
// ICONIFIED -> NORMAL
listenerNotified.set(false);
testFrame.setExtendedState(Frame.NORMAL);
Util.waitForIdle(robot);
Util.waitForCondition(listenerNotified, 2000);
if (!listenerNotified.get()) {
throw new RuntimeException("Test FAILED! Window state listener was not notified during ICONIFIED to" +
"NORMAL transition");
}
if (testFrame.getExtendedState() != Frame.NORMAL) {
throw new RuntimeException("Test FAILED! Frame is not in NORMAL state");
}
} finally {
testFrame.dispose();
mainFrame.dispose();
}
}
}

View file

@ -0,0 +1,71 @@
/*
* 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 8171952
* @summary Tests that getMousePosition() returns null for obscured component.
* @author Dmitry Markov
* @library ../../regtesthelpers
* @build Util
* @run main ObscuredFrameTest
*/
import java.awt.*;
import test.java.awt.regtesthelpers.Util;
public class ObscuredFrameTest {
public static void main(String[] args) {
Robot robot = Util.createRobot();
Frame frame = new Frame("Obscured Frame");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
Button button = new Button("Button");
frame.add(button);
Dialog dialog = new Dialog(frame, "Visible Dialog", false);
dialog.setSize(200, 200);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
frame.setVisible(true);
Util.waitForIdle(robot);
Util.pointOnComp(button, robot);
Util.waitForIdle(robot);
try {
if (button.getMousePosition() != null) {
throw new RuntimeException("Test Failed! Mouse position is not null for obscured component.");
}
} finally {
frame.dispose();
dialog.dispose();
}
}
}

View file

@ -0,0 +1,67 @@
/*
* 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.Frame;
import java.awt.TextField;
/*
* @test
* @bug 4097744
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @summary packing a frame twice stops it resizing
* @run main/manual PackTwiceTest
*/
public class PackTwiceTest {
public static void main(String[] args) throws Exception {
String INSTRUCTIONS = """
1. You would see a Frame titled 'TestFrame'
2. The Frame displays a text as below:
'I am a lengthy sentence...can you see me?'
3. If you can see the full text without resizing the frame
using mouse, press 'Pass' else press 'Fail'.""";
PassFailJFrame.builder()
.title("PackTwiceTest Instruction")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(40)
.testUI(PackTwiceTest::createUI)
.build()
.awaitAndCheck();
}
private static Frame createUI() {
Frame f = new Frame("PackTwiceTest TestFrame");
TextField tf = new TextField();
f.add(tf, "Center");
tf.setText("I am a short sentence");
f.pack();
f.pack();
tf.setText("I am a lengthy sentence...can you see me?");
f.pack();
f.requestFocus();
return f;
}
}

View file

@ -0,0 +1,70 @@
/*
* 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 4154099
@summary Tests that calling removeNotify() on a Frame and then reshowing
the Frame does not crash or lockup
@key headful
@run main RemoveNotifyTest
*/
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
public class RemoveNotifyTest {
static Frame f;
public static void main(String[] args) throws Exception {
EventQueue.invokeAndWait(() -> {
for (int i = 0; i < 100; i++) {
try {
f = new Frame();
f.setBounds(10, 10, 100, 100);
MenuBar bar = new MenuBar();
Menu menu = new Menu();
menu.add(new MenuItem("foo"));
bar.add(menu);
f.setMenuBar(bar);
for (int j = 0; j < 5; j++) {
f.setVisible(true);
f.removeNotify();
}
} finally {
if (f != null) {
f.dispose();
}
}
}
});
System.out.println("done");
}
}// class RemoveNotifyTest

View file

@ -0,0 +1,76 @@
/*
* Copyright (c) 2012, 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.
*/
/*
* Portions Copyright (c) 2012 IBM Corporation
*/
/*
@test
@key headful
@bug 7170655
@summary Frame size does not change after changing font
@author Jonathan Lu
@library ../../regtesthelpers
@build Util
@run main ResizeAfterSetFont
*/
import java.awt.*;
import test.java.awt.regtesthelpers.Util;
public class ResizeAfterSetFont {
public static void main(String[] args) throws Exception {
Frame frame = new Frame("bug7170655");
frame.setLayout(new BorderLayout());
frame.setBackground(Color.LIGHT_GRAY);
Panel panel = new Panel();
panel.setLayout(new GridLayout(0, 1, 1, 1));
Label label = new Label("Test Label");
label.setBackground(Color.white);
label.setForeground(Color.RED);
label.setFont(new Font("Dialog", Font.PLAIN, 12));
panel.add(label);
frame.add(panel, "South");
frame.pack();
frame.setVisible(true);
Util.waitForIdle(null);
Dimension dimBefore = frame.getSize();
label.setFont(new Font("Dialog", Font.PLAIN, 24));
frame.validate();
frame.pack();
Dimension dimAfter = frame.getSize();
if (dimBefore.equals(dimAfter)) {
throw new Exception(
"Frame size does not change after Label.setFont()!");
}
}
}

View file

@ -0,0 +1,91 @@
/*
* Copyright (c) 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.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Toolkit;
/**
* @test
* @bug 8256373
* @key headful
* @summary setBounds() should work if the frame is minimized
*/
public final class RestoreToOppositeScreen {
public static void main(String[] args) throws Exception {
Toolkit toolkit = Toolkit.getDefaultToolkit();
if (!toolkit.isFrameStateSupported(Frame.ICONIFIED)) {
return;
}
var ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
for (GraphicsDevice gd1 : gds) {
Rectangle screen1 = gd1.getDefaultConfiguration().getBounds();
int x1 = (int) screen1.getCenterX();
int y1 = (int) screen1.getCenterY();
for (GraphicsDevice gd2 : gds) {
Rectangle screen2 = gd2.getDefaultConfiguration().getBounds();
// tweak the (x2, y2) point so even if the screen1 and screen2
// are the same, we will use different bounds, otherwise
// setBounds() will be ignored
int x2 = (int) screen2.getCenterX() - 50;
int y2 = (int) screen2.getCenterY() - 50;
Frame frame = new Frame();
try {
// show the frame on one monitor, and then move it to
// another while the frame minimized
frame.setBounds(x1, y1, 400, 400);
frame.setVisible(true);
Thread.sleep(2000);
frame.setExtendedState(Frame.ICONIFIED);
Thread.sleep(2000);
Rectangle before = new Rectangle(x2, y2, 380, 380);
frame.setBounds(before);
Thread.sleep(2000);
frame.setExtendedState(Frame.NORMAL);
Thread.sleep(2000);
Rectangle after = frame.getBounds();
checkSize(after.x, before.x, "x");
checkSize(after.y, before.y, "y");
checkSize(after.width, before.width, "width");
checkSize(after.height, before.height, "height");
} finally {
frame.dispose();
}
}
}
}
private static void checkSize(int actual, int expected, String prop) {
if (Math.abs(actual - expected) > 10) { // let's allow size variation,
// the bug is reproduced anyway
System.err.println("Expected: " + expected);
System.err.println("Actual: " + actual);
throw new RuntimeException(prop + " is wrong");
}
}
}

View file

@ -0,0 +1,92 @@
/*
* 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
* @key headful
* @bug 8166980
* @summary Test to check Window.setIconImages() does not result in crash when
* a frame is shown
* @run main/othervm SetIconImagesCrashTest
* @run main/othervm -Dsun.java2d.uiScale=2 SetIconImagesCrashTest
*/
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Window;
import java.awt.Frame;
import java.util.List;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
public class SetIconImagesCrashTest {
public static void main(String[] args) throws Exception {
List<BufferedImage> imageList = new ArrayList<BufferedImage>();
imageList.add(new BufferedImage(200, 200,
BufferedImage.TYPE_BYTE_BINARY));
for (int i = 0; i < 10; i++) {
Frame f = new Frame();
test(f, imageList);
}
}
public static void test(final Window window,
final List<BufferedImage> imageList) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
for (BufferedImage image : imageList) {
Graphics graphics = image.getGraphics();
graphics.setColor(Color.RED);
graphics.fillRect(
0, 0, image.getWidth(), image.getHeight());
graphics.dispose();
}
window.setIconImages(imageList);
window.setSize(200, 200);
window.setVisible(true);
}
});
while (!window.isVisible()) {
Thread.sleep((long) (20));
}
Thread.sleep((long) (50));
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
window.setVisible(false);
window.dispose();
}
});
}
}

View file

@ -0,0 +1,129 @@
/*
* Copyright (c) 2015, 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.
*/
import java.awt.*;
/**
* @test
* @key headful
* @bug 8065739
* @summary Moved window is maximazed to new screen
* @author Alexandr Scherbatiy
*
* @run main MaximizedMovedWindow
*/
public class MaximizedMovedWindow {
public static void main(String[] args) throws Exception {
//Supported platforms are Windows and OS X.
String os = System.getProperty("os.name").toLowerCase();
if (!os.contains("os x")) {
return;
}
if (!Toolkit.getDefaultToolkit().
isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
return;
}
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
if (ge.isHeadlessInstance()) {
return;
}
GraphicsDevice[] devices = ge.getScreenDevices();
if (devices.length < 2) {
return;
}
Frame frame = null;
try {
GraphicsConfiguration gc1 = devices[0].getDefaultConfiguration();
GraphicsConfiguration gc2 = devices[1].getDefaultConfiguration();
Robot robot = new Robot();
robot.setAutoDelay(50);
frame = new Frame();
Rectangle maxArea1 = getMaximizedScreenArea(gc1);
frame.setBounds(getSmallerRectangle(maxArea1));
frame.setVisible(true);
robot.waitForIdle();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
robot.delay(1000);
Rectangle bounds = frame.getBounds();
if (!bounds.equals(maxArea1)) {
throw new RuntimeException("The bounds of the Frame do not equal"
+ " to screen 1 size");
}
frame.setExtendedState(Frame.NORMAL);
robot.waitForIdle();
robot.delay(1000);
Rectangle maxArea2 = getMaximizedScreenArea(gc2);
frame.setBounds(getSmallerRectangle(maxArea2));
robot.waitForIdle();
robot.delay(1000);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
robot.delay(1000);
bounds = frame.getBounds();
if (!bounds.equals(maxArea2)) {
throw new RuntimeException("The bounds of the Frame do not equal"
+ " to screen 2 size");
}
} finally {
if (frame != null) {
frame.dispose();
}
}
}
static Rectangle getSmallerRectangle(Rectangle rect) {
return new Rectangle(
rect.x + rect.width / 6,
rect.y + rect.height / 6,
rect.width / 3,
rect.height / 3);
}
static Rectangle getMaximizedScreenArea(GraphicsConfiguration gc) {
Rectangle bounds = gc.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
return new Rectangle(
bounds.x + insets.left,
bounds.y + insets.top,
bounds.width - insets.left - insets.right,
bounds.height - insets.top - insets.bottom);
}
}

View file

@ -0,0 +1,139 @@
/*
* 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.
*/
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
/**
* @test
* @key headful
* @bug 8065739 8131339 8231564
* @requires (os.family == "windows" | os.family == "mac")
* @summary When Frame.setExtendedState(Frame.MAXIMIZED_BOTH)
* is called for a Frame after been called setMaximizedBounds() with
* certain value, Frame bounds must equal to this value.
*/
public class SetMaximizedBounds {
public static void main(String[] args) throws Exception {
//Supported platforms are Windows and OS X.
String os = System.getProperty("os.name").toLowerCase();
if (!os.contains("windows") && !os.contains("os x")) {
return;
}
if (!Toolkit.getDefaultToolkit().
isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
return;
}
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
for (GraphicsDevice gd : ge.getScreenDevices()) {
for (GraphicsConfiguration gc : gd.getConfigurations()) {
testMaximizedBounds(gc, false);
testMaximizedBounds(gc, true);
}
}
}
static void testMaximizedBounds(GraphicsConfiguration gc, boolean undecorated)
throws Exception {
Frame frame = null;
try {
Rectangle maxArea = getMaximizedScreenArea(gc);
Robot robot = new Robot();
robot.setAutoDelay(50);
frame = new Frame();
frame.setUndecorated(undecorated);
Rectangle maximizedBounds = new Rectangle(
maxArea.x + maxArea.width / 5,
maxArea.y + maxArea.height / 5,
maxArea.width / 2,
maxArea.height / 2);
frame.setMaximizedBounds(maximizedBounds);
frame.setSize(maxArea.width / 8, maxArea.height / 8);
frame.setVisible(true);
robot.waitForIdle();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
robot.delay(1000);
Rectangle bounds = frame.getBounds();
if (!bounds.equals(maximizedBounds)) {
System.err.println("Expected: " + maximizedBounds);
System.err.println("Actual: " + bounds);
throw new RuntimeException("The bounds of the Frame do not equal to what"
+ " is specified when the frame is in Frame.MAXIMIZED_BOTH state");
}
frame.setExtendedState(Frame.NORMAL);
robot.waitForIdle();
robot.delay(1000);
maximizedBounds = new Rectangle(
maxArea.x + maxArea.width / 6,
maxArea.y + maxArea.height / 6,
maxArea.width / 3,
maxArea.height / 3);
frame.setMaximizedBounds(maximizedBounds);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
robot.waitForIdle();
robot.delay(1000);
bounds = frame.getBounds();
if (!bounds.equals(maximizedBounds)) {
System.err.println("Expected: " + maximizedBounds);
System.err.println("Actual: " + bounds);
throw new RuntimeException("The bounds of the Frame do not equal to what"
+ " is specified when the frame is in Frame.MAXIMIZED_BOTH state");
}
} finally {
if (frame != null) {
frame.dispose();
}
}
}
static Rectangle getMaximizedScreenArea(GraphicsConfiguration gc) {
Rectangle bounds = gc.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
return new Rectangle(
bounds.x + insets.left,
bounds.y + insets.top,
bounds.width - insets.left - insets.right,
bounds.height - insets.top - insets.bottom);
}
}

View file

@ -0,0 +1,88 @@
/*
* Copyright (c) 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
* @key headful
* @summary Verify that increase in Frame's minimumSize gets reflected in the subsequent getSize call
* @run main SetMinimumSizeTest1
*/
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Robot;
public class SetMinimumSizeTest1 {
private static Frame frame;
private static volatile Dimension dimension;
private static volatile Dimension actualDimension;
public static void createGUI() {
frame = new Frame();
frame.add(new Button("Button"));
frame.setSize(140, 140);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void doTest() throws Exception {
try {
EventQueue.invokeAndWait(() -> createGUI());
Robot robot = new Robot();
robot.setAutoDelay(100);
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
dimension = frame.getSize();
dimension.width += 20;
dimension.height += 20;
frame.setMinimumSize(dimension);
frame.invalidate();
frame.validate();
});
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
actualDimension = frame.getSize();
});
if (!actualDimension.equals(dimension)) {
throw new RuntimeException("Test Failed\n"
+ "expected dimension:(" + dimension.width + "," + dimension.height +")\n"
+ "actual dimension:(" + actualDimension.width + "," + actualDimension.height + ")");
}
} finally {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
public static void main(String[] args) throws Exception {
doTest();
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 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
* @key headful
* @summary Verify frame resizes back to minimumSize on calling pack
* @run main SetMinimumSizeTest2
*/
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Robot;
public class SetMinimumSizeTest2 {
private static Frame frame;
private static volatile Dimension dimension;
private static volatile Dimension actualDimension;
public static void createGUI() {
frame = new Frame();
frame.add(new Button("Button"));
frame.setMinimumSize(new Dimension(140, 140));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void doTest() throws Exception {
try {
EventQueue.invokeAndWait(() -> createGUI());
Robot robot = new Robot();
robot.setAutoDelay(100);
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
dimension = frame.getSize();
});
EventQueue.invokeAndWait(() -> {
frame.setSize(dimension.width + 20, dimension.height + 20);
frame.invalidate();
frame.validate();
});
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
frame.pack();
frame.invalidate();
frame.validate();
});
robot.waitForIdle();
EventQueue.invokeAndWait(() -> {
actualDimension = frame.getSize();
});
if (!actualDimension.equals(dimension)) {
throw new RuntimeException("Test Failed\n"
+ "expected dimension:(" + dimension.width + "," + dimension.height +")\n"
+ "actual dimension:(" + actualDimension.width + "," + actualDimension.height + ")");
}
} finally {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
public static void main(String[] args) throws Exception {
doTest();
}
}

View file

@ -0,0 +1,229 @@
/*
* Copyright (c) 2010, 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.
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/*
* @test
* @key headful
* @bug 6988428
* @summary Tests whether shape is always set
* @run main/othervm/timeout=300 -Dsun.java2d.uiScale=1 ShapeNotSetSometimes
*/
public class ShapeNotSetSometimes {
private Frame backgroundFrame;
private Frame window;
private Point[] pointsOutsideToCheck;
private Point[] shadedPointsToCheck;
private Point innerPoint;
private static Robot robot;
private static final Color BACKGROUND_COLOR = Color.GREEN;
private static final Color SHAPE_COLOR = Color.WHITE;
private static final int DIM = 300;
private static final int DELTA = 2;
public ShapeNotSetSometimes() throws Exception {
EventQueue.invokeAndWait(this::initializeGUI);
robot.waitForIdle();
robot.delay(500);
}
private void initializeGUI() {
backgroundFrame = new BackgroundFrame();
backgroundFrame.setUndecorated(true);
backgroundFrame.setSize(DIM, DIM);
backgroundFrame.setLocationRelativeTo(null);
backgroundFrame.setVisible(true);
Area area = new Area();
area.add(new Area(new Rectangle2D.Float(100, 50, 100, 150)));
area.add(new Area(new Rectangle2D.Float(50, 100, 200, 50)));
area.add(new Area(new Ellipse2D.Float(50, 50, 100, 100)));
area.add(new Area(new Ellipse2D.Float(50, 100, 100, 100)));
area.add(new Area(new Ellipse2D.Float(150, 50, 100, 100)));
area.add(new Area(new Ellipse2D.Float(150, 100, 100, 100)));
// point at the center of white ellipse
innerPoint = new Point(150, 130);
// mid points on the 4 sides - on the green background frame
pointsOutsideToCheck = new Point[] {
new Point(150, 20),
new Point(280, 120),
new Point(150, 250),
new Point(20, 120)
};
// points just outside the ellipse (opposite side of diagonal)
shadedPointsToCheck = new Point[] {
new Point(62, 62),
new Point(240, 185)
};
window = new TestFrame();
window.setUndecorated(true);
window.setSize(DIM, DIM);
window.setLocationRelativeTo(null);
window.setShape(area);
window.setVisible(true);
}
static class BackgroundFrame extends Frame {
@Override
public void paint(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0, 0, DIM, DIM);
super.paint(g);
}
}
class TestFrame extends Frame {
@Override
public void paint(Graphics g) {
g.setColor(SHAPE_COLOR);
g.fillRect(0, 0, DIM, DIM);
super.paint(g);
}
}
public static void main(String[] args) throws Exception {
robot = new Robot();
for (int i = 1; i <= 50; i++) {
System.out.println("Attempt " + i);
new ShapeNotSetSometimes().doTest();
}
}
private void doTest() throws Exception {
EventQueue.invokeAndWait(backgroundFrame::toFront);
robot.waitForIdle();
EventQueue.invokeAndWait(window::toFront);
robot.waitForIdle();
robot.delay(500);
Rectangle screenBounds = window.getGraphicsConfiguration().getBounds();
BufferedImage screenCapture = robot.createScreenCapture(screenBounds);
try {
colorCheck(innerPoint.x, innerPoint.y, SHAPE_COLOR,
true, screenCapture);
for (Point point : pointsOutsideToCheck) {
colorCheck(point.x, point.y, BACKGROUND_COLOR,
true, screenCapture);
}
for (Point point : shadedPointsToCheck) {
colorCheck(point.x, point.y, SHAPE_COLOR,
false, screenCapture);
}
} finally {
EventQueue.invokeAndWait(() -> {
if (backgroundFrame != null) {
backgroundFrame.dispose();
}
if (window != null) {
window.dispose();
}
});
}
}
private void colorCheck(int x, int y, Color expectedColor,
boolean mustBeExpectedColor, BufferedImage screenCapture) {
int screenX = window.getX() + x;
int screenY = window.getY() + y;
Color actualColor = new Color(screenCapture.getRGB(screenX, screenY));
System.out.printf(
"Checking %3d, %3d, %35s should %sbe %35s\n",
x, y,
actualColor,
(mustBeExpectedColor) ? "" : "not ",
expectedColor
);
if (mustBeExpectedColor != colorCompare(expectedColor, actualColor)) {
captureScreen();
System.out.printf("window.getX() = %3d, window.getY() = %3d\n", window.getX(), window.getY());
System.err.printf(
"Checking for transparency failed: point: %3d, %3d\n\tactual %s\n\texpected %s%s\n",
screenX,
screenY,
actualColor,
mustBeExpectedColor ? "" : "not ",
expectedColor);
throw new RuntimeException("Test failed. The shape has not been applied.");
}
}
private static boolean colorCompare(Color expected, Color actual) {
if (Math.abs(expected.getRed() - actual.getRed()) <= DELTA
&& Math.abs(expected.getGreen() - actual.getGreen()) <= DELTA
&& Math.abs(expected.getBlue() - actual.getBlue()) <= DELTA) {
return true;
}
return false;
}
private static void captureScreen() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenBounds = new Rectangle(0, 0, screenSize.width, screenSize.height);
try {
ImageIO.write(
robot.createScreenCapture(screenBounds),
"png",
new File("Screenshot.png")
);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,214 @@
/*
* 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 6477497
@summary Windows drawn off-screen on Win98 if locationByPlatform is true
@author anthony.petrov@...: area=awt.toplevel
@library ../../regtesthelpers
@build Util
@run main ShownOffScreenOnWin98Test
*/
/**
* ShownOffScreenOnWin98Test.java
*
* summary: Tests whether a frame is located inside the screen boundaries
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import test.java.awt.regtesthelpers.Util;
public class ShownOffScreenOnWin98Test
{
//*** test-writer defined static variables go here ***
private static void init()
{
boolean passed = false;
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame();
frame.setLocationByPlatform(true);
frame.setVisible(true);
Util.waitForIdle(null);
GraphicsConfiguration gc = frame.getGraphicsConfiguration();
Point loc = frame.getLocation();
Rectangle scrBnd = gc.getBounds();
Insets scrIns = Toolkit.getDefaultToolkit().getScreenInsets(gc);
System.out.println("The frame location: " + loc);
System.out.println("The screen bound: " + scrBnd);
System.out.println("The screen insets: " + scrIns);
passed = (loc.x >= scrBnd.x + scrIns.left
&& loc.x <= scrBnd.x + scrBnd.getWidth() - scrIns.right
&& loc.y >= scrBnd.y + scrIns.top
&& loc.y <= scrBnd.y + scrBnd.getHeight() - scrIns.bottom);
} catch (Exception e) {
e.printStackTrace();
ShownOffScreenOnWin98Test.fail("Unexpected exception caught: " + e);
}
if (passed)
{
ShownOffScreenOnWin98Test.pass();
} else {
ShownOffScreenOnWin98Test.fail("The frame is located off screen");
}
}//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 ShownOffScreenOnWin98Test
//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,68 @@
/*
* 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.
*/
import java.awt.EventQueue;
import java.awt.Frame;
/*
* @test
* @bug 6525850
* @summary Iconified frame gets shown after pack()
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual ShownOnPack
*/
public class ShownOnPack {
private static final String INSTRUCTIONS = """
This test creates an invisible and iconified frame that should not become visible.
If you observe the window titled 'Should NOT BE SHOWN' in the taskbar,
press FAIL, otherwise press PASS
""";
static Frame frame;
public static void main(String[] args) throws Exception {
PassFailJFrame shownOnPackInstructions = PassFailJFrame
.builder()
.title("ShownOnPack Instructions")
.instructions(INSTRUCTIONS)
.rows(5)
.columns(50)
.build();
EventQueue.invokeAndWait(() -> {
frame = new Frame("Should NOT BE SHOWN");
frame.setExtendedState(Frame.ICONIFIED);
frame.pack();
});
try {
shownOnPackInstructions.awaitAndCheck();
} finally {
EventQueue.invokeAndWait(() -> frame.dispose());
}
}
}

View file

@ -0,0 +1,140 @@
/*
* 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.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
* @test
* @key headful
* @bug 4065534
* @summary Frame.setSize() doesn't change size if window is in an iconified state
* @run main SizeMinimizedTest
*/
public class SizeMinimizedTest {
private static Frame frame;
private static final int INITIAL_SIZE = 100;
private static final int INITIAL_X = 150;
private static final int INITIAL_Y = 50;
private static final int RESET_SIZE = 200;
private static final int OFFSET = 10;
private static int iterationCnt = 0;
private static Dimension expectedSize;
private static Dimension frameSize;
private static Point expectedLoc;
private static Point frameLoc;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
try {
EventQueue.invokeAndWait(() -> {
createUI();
});
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(() -> {
frame.setState(Frame.ICONIFIED);
});
robot.waitForIdle();
robot.delay(100);
EventQueue.invokeAndWait(() -> {
frame.setSize(RESET_SIZE, RESET_SIZE);
});
robot.waitForIdle();
robot.delay(100);
for (int i = 0; i < 5; i++) {
EventQueue.invokeAndWait(() -> {
Point pt = frame.getLocation();
frame.setLocation(pt.x + OFFSET, pt.y);
});
iterationCnt++;
robot.waitForIdle();
robot.delay(100);
}
EventQueue.invokeAndWait(() -> {
frame.setState(Frame.NORMAL);
});
robot.waitForIdle();
robot.delay(100);
System.out.println("Test Passed!");
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
public static void createUI() {
frame = new Frame("Frame size test");
frame.setSize(INITIAL_SIZE, INITIAL_SIZE);
frame.setLocation(INITIAL_X, INITIAL_Y);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("Initial Frame Size: " + frame.getSize());
System.out.println("Initial Frame Location: " +
frame.getLocationOnScreen());
}
});
frame.addWindowStateListener(new WindowAdapter() {
@Override
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == Frame.NORMAL) {
System.out.println("Frame Size: " + frame.getSize());
System.out.println("Frame Location: " +
frame.getLocationOnScreen());
expectedSize = new Dimension(RESET_SIZE, RESET_SIZE);
frameSize = frame.getSize();
if (!expectedSize.equals(frameSize)) {
throw new RuntimeException("Test Failed due to size mismatch.");
}
expectedLoc = new Point(INITIAL_X + OFFSET * iterationCnt,
INITIAL_Y);
frameLoc = frame.getLocationOnScreen();
if (!expectedLoc.equals(frameLoc)) {
throw new RuntimeException("Test Failed due to " +
"location mismatch.");
}
}
}
});
frame.setVisible(true);
}
}

View file

@ -0,0 +1,69 @@
/*
* 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.*;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.InputEvent;
/**
* @test
* @key headful
* @bug 8032595
* @summary setResizable(false) makes a frame slide down
* @author Petr Pchelko
*/
public class SlideNotResizableTest {
private static volatile boolean passed = false;
private static final Dimension FRAME_SIZE = new Dimension(100, 100);
private static final Point FRAME_LOCATION = new Point(200, 200);
public static void main(String[] args) throws Throwable {
Frame aFrame = null;
try {
aFrame = new Frame();
aFrame.setSize(FRAME_SIZE);
aFrame.setLocation(FRAME_LOCATION);
aFrame.setResizable(false);
aFrame.setVisible(true);
sync();
if (!aFrame.getLocation().equals(FRAME_LOCATION)) {
throw new RuntimeException("FAILED: Wrong frame position");
}
} finally {
if (aFrame != null) {
aFrame.dispose();
}
}
}
private static void sync() throws Exception {
Robot robot = new Robot();
robot.waitForIdle();
Thread.sleep(1000);
}
}

View file

@ -0,0 +1,129 @@
/*
* Copyright (c) 2007, 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 4980161 7158623 8204860 8208125 8215280
@summary Setting focusable window state to false makes the maximized frame resizable
@compile UnfocusableMaximizedFrameResizablity.java
@run main UnfocusableMaximizedFrameResizablity
*/
import java.awt.Toolkit;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.AWTException;
import java.awt.event.InputEvent;
import java.awt.Robot;
public class UnfocusableMaximizedFrameResizablity {
private static Frame frame;
private static Robot robot;
private static boolean isProgInterruption = false;
private static Thread mainThread = null;
private static int sleepTime = 300000;
private static void createAndShowFrame() throws Exception {
//MAXIMIZED_BOTH frame is resizable on Mac OS by default. Nothing to test.
if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
cleanup();
return;
}
//The MAXIMIZED_BOTH state is not supported by the toolkit. Nothing to test.
if (!Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) {
cleanup();
return;
}
frame = new Frame("Unfocusable frame");
frame.setMaximizedBounds(new Rectangle(0, 0, 300, 300));
frame.setSize(200, 200);
frame.setVisible(true);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setFocusableWindowState(false);
try {
robot = new Robot();
} catch (AWTException e) {
throw new RuntimeException("Robot creation failed");
}
robot.delay(2000);
// The initial bounds of the frame
final Rectangle bounds = frame.getBounds();
// Let's move the mouse pointer to the bottom-right coner of the frame (the "size-grip")
robot.mouseMove(bounds.x + bounds.width - 2, bounds.y + bounds.height - 2);
robot.waitForIdle();
// ... and start resizing
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
robot.mouseMove(bounds.x + bounds.width + 20, bounds.y + bounds.height + 15);
robot.waitForIdle();
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
// The bounds of the frame after the attempt of resizing is made
final Rectangle finalBounds = frame.getBounds();
if (!finalBounds.equals(bounds)) {
cleanup();
throw new RuntimeException("The maximized unfocusable frame can be resized.");
}
cleanup();
}
private static void cleanup() {
if (frame != null) {
frame.dispose();
}
isProgInterruption = true;
mainThread.interrupt();
}
public static void main(String args[]) throws Exception {
mainThread = Thread.currentThread();
try {
createAndShowFrame();
mainThread.sleep(sleepTime);
} catch (InterruptedException e) {
if (!isProgInterruption) {
throw e;
}
}
if (!isProgInterruption) {
throw new RuntimeException("Timed out after " + sleepTime / 1000
+ " seconds");
}
}
}

View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 2012, 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 7128738 7161759
* @summary dragged dialog freezes system on dispose
* @author Oleg Pekhovskiy: area=awt.toplevel
* @library ../../regtesthelpers
* @build Util
* @run main WindowDragTest
*/
import java.awt.Frame;
import java.awt.event.InputEvent;
import java.awt.AWTException;
import test.java.awt.regtesthelpers.Util;
import java.awt.Robot;
import java.awt.Point;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class WindowDragTest {
static boolean passed = false;
public static void main(String[] args) {
try {
Robot robot = new Robot();
robot.setAutoDelay(1000);
Frame frame1 = new Frame();
frame1.setBounds(50, 50, 300, 200);
frame1.setVisible(true);
frame1.toFront();
frame1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// Clicking frame1 succeeded - mouse is not captured
passed = true;
}
});
robot.delay(1000);
Frame frame2 = new Frame();
frame2.setBounds(100, 100, 300, 200);
frame2.setVisible(true);
frame2.toFront();
robot.delay(1000);
Point p = frame2.getLocationOnScreen();
Dimension d = frame2.getSize();
// Move cursor to frame2 title bar to drag
robot.mouseMove(p.x + (int)(d.getWidth() / 2), p.y + (int)frame2.getInsets().top / 2);
Util.waitForIdle(robot);
// Start window dragging
robot.mousePress(InputEvent.BUTTON1_MASK);
Util.waitForIdle(robot);
// Dispose window being dragged
frame2.dispose();
Util.waitForIdle(robot);
// Release mouse button to be able to get MOUSE_CLICKED event on Util.clickOnComp()
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Util.waitForIdle(robot);
// Click frame1 to check whether mouse is not captured by frame2
Util.clickOnComp(frame1, robot);
Util.waitForIdle(robot);
frame1.dispose();
if (passed) {
System.out.println("Test passed.");
}
else {
System.out.println("Test failed.");
throw new RuntimeException("Test failed.");
}
}
catch (AWTException e) {
throw new RuntimeException("AWTException occurred - problem creating robot!");
}
}
}

View file

@ -0,0 +1,166 @@
/*
* 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.Color;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/*
* @test
* @bug 4077874
* @key headful
* @summary Test window position at opening, closing, and closed for consistency
*/
public class WindowMoveTest {
static WindowMove frame;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(50);
robot.setAutoWaitForIdle(true);
EventQueue.invokeAndWait(() -> frame = new WindowMove());
robot.waitForIdle();
robot.delay(1000);
EventQueue.invokeAndWait(() ->
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)));
if (!WindowMove.latch.await(2, TimeUnit.SECONDS)) {
throw new RuntimeException("Test timeout.");
}
if (WindowMove.failMessage != null) {
throw new RuntimeException(WindowMove.failMessage);
}
}
}
class WindowMove extends Frame implements WindowListener {
static final Rectangle expectedBounds =
new Rectangle(100, 100, 300, 300);
static CountDownLatch latch = new CountDownLatch(1);
static String failMessage = null;
private boolean layoutCheck;
private boolean visibleCheck;
private boolean openedCheck;
private boolean closingCheck;
private boolean closedCheck;
public WindowMove() {
super("WindowMove");
addWindowListener(this);
setSize(300, 300);
setLocation(100, 100);
setBackground(Color.white);
setLayout(null);
if (checkBounds()) {
layoutCheck = true;
}
System.out.println("setLayout bounds: " + getBounds());
setVisible(true);
if (checkBounds()) {
visibleCheck = true;
}
System.out.println("setVisible bounds: " + getBounds());
}
private boolean checkBounds() {
return getBounds().equals(expectedBounds);
}
public void checkResult() {
if (layoutCheck
&& visibleCheck
&& openedCheck
&& closingCheck
&& closedCheck) {
System.out.println("Test passed.");
} else {
failMessage = """
Some of the checks failed:
layoutCheck %s
visibleCheck %s
openedCheck %s
closingCheck %s
closedCheck %s
"""
.formatted(
layoutCheck,
visibleCheck,
openedCheck,
closingCheck,
closedCheck
);
}
latch.countDown();
}
public void windowClosing(WindowEvent evt) {
if (checkBounds()) {
closingCheck = true;
}
System.out.println("Closing bounds: " + getBounds());
setVisible(false);
dispose();
}
public void windowClosed(WindowEvent evt) {
if (checkBounds()) {
closedCheck = true;
}
System.out.println("Closed bounds: " + getBounds());
checkResult();
}
public void windowOpened(WindowEvent evt) {
if (checkBounds()) {
openedCheck = true;
}
System.out.println("Opening bounds: " + getBounds());
}
public void windowActivated(WindowEvent evt) {}
public void windowIconified(WindowEvent evt) {}
public void windowDeactivated(WindowEvent evt) {}
public void windowDeiconified(WindowEvent evt) {}
}