提交 5e852cbc 编写于 作者: A ant

6680135: A number of test/closed/java/awt/Focus/* tests should be opened

Summary: The tests moved from the closed repository.
Reviewed-by: son
上级 af619506
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 6314575
@summary Tests that previosly focused owned window doesn't steal focus when an owner's component requests focus.
@author Anton Tarasov: area=awt-focus
@run applet ActualFocusedWindowBlockingTest.html
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.lang.reflect.InvocationTargetException;
import sun.awt.SunToolkit;
public class ActualFocusedWindowBlockingTest extends Applet {
Robot robot;
Frame owner = new Frame("Owner Frame");
Window win = new Window(owner);
Frame frame = new Frame("Auxiliary Frame");
Button fButton = new Button("frame button") {public String toString() {return "Frame_Button";}};
Button wButton = new Button("window button") {public String toString() {return "Window_Button";}};
Button aButton = new Button("auxiliary button") {public String toString() {return "Auxiliary_Button";}};
public static void main(String[] args) {
ActualFocusedWindowBlockingTest app = new ActualFocusedWindowBlockingTest();
app.init();
app.start();
}
public void init() {
// Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout (new BorderLayout ());
Sysout.createDialogWithInstructions(new String[]
{"Automatic test. Simply wait until it's done."});
if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) {
return;
}
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent e) {
Sysout.println("--> " + e);
}
}, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK);
try {
robot = new Robot();
} catch (AWTException e) {
throw new RuntimeException("Error: unable to create robot", e);
}
owner.add(fButton);
win.add(wButton);
frame.add(aButton);
owner.setName("OWNER_FRAME");
win.setName("OWNED_WINDOW");
frame.setName("AUX_FRAME");
tuneAndShowWindows(new Window[] {owner, win, frame});
}
public void start() {
if ("sun.awt.motif.MToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName())) {
Sysout.println("No testing on Motif. Test passed.");
return;
}
Sysout.println("\nTest started:\n");
// Test 1.
clickOnCheckFocus(wButton);
clickOnCheckFocus(aButton);
clickOn(fButton);
if (!testFocused(fButton)) {
throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused by click");
}
// Test 2.
clickOnCheckFocus(wButton);
clickOnCheckFocus(aButton);
fButton.requestFocus();
realSync();
if (!testFocused(fButton)) {
throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused by request");
}
// Test 3.
clickOnCheckFocus(wButton);
clickOnCheckFocus(aButton);
clickOnCheckFocus(fButton);
clickOnCheckFocus(aButton);
clickOn(owner);
if (!testFocused(fButton)) {
throw new TestFailedException("The owner's component [" + fButton + "] couldn't be focused as the most recent focus owner");
}
Sysout.println("Test passed.");
}
void tuneAndShowWindows(Window[] arr) {
int y = 0;
for (Window w: arr) {
w.setLayout(new FlowLayout());
w.setBounds(100, y, 400, 150);
w.setBackground(Color.blue);
w.setVisible(true);
y += 200;
realSync();
}
}
void clickOn(Component c) {
Sysout.println("Test: clicking " + c);
Point p = c.getLocationOnScreen();
Dimension d = c.getSize();
if (c instanceof Frame) {
robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2);
Sysout.println((p.x + (int)(d.getWidth()/2)) + " " + (p.y + ((Frame)c).getInsets().top/2));
} else {
robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2));
}
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(100);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
realSync();
}
void clickOnCheckFocus(Component c) {
clickOn(c);
if (!testFocused(c)) {
throw new RuntimeException("Error: [" + c + "] couldn't get focus by click.");
}
}
boolean testFocused(Component c) {
for (int i=0; i<10; i++) {
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == c) {
return true;
}
realSync();
}
return false;
}
void realSync() {
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
}
class TestFailedException extends RuntimeException {
public TestFailedException(String cause) {
super("Test failed. " + cause);
Sysout.println(cause);
}
}
}
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setLocation(500,0);
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 4823903
@summary Tests actual focused window retaining.
@author Anton Tarasov: area=awt.focus
@run applet ActualFocusedWindowRetaining.html
*/
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.applet.*;
public class ActualFocusedWindowRetaining extends Applet {
public static Frame frame = new Frame("Other Frame");
public static Frame owner = new Frame("Test Frame");
public static Button otherButton1 = new Button("Other Button 1");
public static Button otherButton2 = new Button("Other Button 2");
public static Button otherButton3 = new Button("Other Button 3");
public static Button testButton1 = new Button("Test Button 1");
public static Button testButton2 = new Button("Test Button 2");
public static Button testButton3 = new Button("Test Button 3");
public static Window window1 = new TestWindow(owner, otherButton2, testButton2, 800, 200);
public static Window window2 = new TestWindow(owner, otherButton3, testButton3, 800, 300);
public static int step;
public static Robot robot;
public static void main(String[] args) {
ActualFocusedWindowRetaining a = new ActualFocusedWindowRetaining();
a.init();
a.start();
}
public void init()
{
//Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout (new BorderLayout ());
String[] instructions =
{
"This is an AUTOMATIC test",
"simply wait until it is done"
};
Sysout.createDialogWithInstructions( instructions );
}
public void start ()
{
if (Toolkit.getDefaultToolkit().getClass()
.getName().equals("sun.awt.motif.MToolkit")) {
Sysout.println("No testing on Motif.");
return;
}
try {
robot = new Robot();
} catch (AWTException e) {
throw new RuntimeException("Error: unable to create robot", e);
}
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent e) {
Object src = e.getSource();
Class cls = src.getClass();
if (cls == TestWindow.class) {
Sysout.println(e.paramString() + " on <" + (src == window1 ? "Window 1" : "Window 2") + ">");
} else if (cls == Frame.class) {
Sysout.println(e.paramString() + " on <" + ((Frame)src).getTitle() + ">");
} else if (cls == Button.class) {
Sysout.println(e.paramString() + " on <" + ((Button)src).getLabel() + ">");
} else {
Sysout.println(e.paramString() + " on <Non-testing component>");
}
}
}, AWTEvent.WINDOW_EVENT_MASK | AWTEvent.WINDOW_FOCUS_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
setSize (200,200);
setVisible(true);
validate();
frame.setSize(new Dimension(400, 100));
frame.setLocation(800, 400);
frame.setVisible(true);
frame.toFront();
owner.setLayout(new FlowLayout());
owner.add(testButton1);
owner.add(otherButton1);
owner.pack();
owner.setLocation(800, 100);
owner.setSize(new Dimension(400, 100));
owner.setVisible(true);
owner.toFront();
waitTillShown(owner);
window1.setVisible(true);
window2.setVisible(true);
window1.toFront();
window2.toFront();
// Wait longer...
waitTillShown(window1);
waitTillShown(window2);
test();
frame.dispose();
owner.dispose();
}
public void test() {
Button[] butArr = new Button[] {testButton3, testButton2, testButton1};
Window[] winArr = new Window[] {window2, window1, owner};
step = 1;
for (int i = 0; i < 3; i++) {
clickOnCheckFocusOwner(butArr[i]);
clickOnCheckFocusedWindow(frame);
clickOn(owner);
if (!checkFocusedWindow(winArr[i])) {
stopTest("Test failed: actual focused window didn't get a focus");
}
if (!checkFocusOwner(butArr[i])) {
stopTest("Test failed: actual focus owner didn't get a focus");
}
step++;
}
step = 4;
clickOnCheckFocusOwner(testButton3);
clickOnCheckFocusOwner(testButton1);
clickOnCheckFocusedWindow(frame);
clickOn(owner);
if (!checkFocusedWindow(owner)) {
stopTest("Test failed: actual focused window didn't get a focus");
}
if (!checkFocusOwner(testButton1)) {
stopTest("Test failed: actual focus owner didn't get a focus");
}
step = 5;
clickOnCheckFocusOwner(testButton3);
clickOnCheckFocusOwner(testButton2);
clickOnCheckFocusedWindow(frame);
clickOn(owner);
if (!checkFocusedWindow(window1)) {
stopTest("Test failed: actual focused window didn't get a focus");
}
if (!checkFocusOwner(testButton2)) {
stopTest("Test failed: actual focus owner didn't get a focus");
}
step = 6;
clickOnCheckFocusOwner(testButton1);
clickOnCheckFocusOwner(testButton2);
clickOnCheckFocusedWindow(frame);
clickOn(owner);
if (!checkFocusedWindow(window1)) {
stopTest("Test failed: actual focused window didn't get a focus");
}
if (!checkFocusOwner(testButton2)) {
stopTest("Test failed: actual focus owner didn't get a focus");
}
step = 7;
clickOnCheckFocusOwner(testButton1);
clickOnCheckFocusOwner(testButton2);
clickOnCheckFocusedWindow(frame);
window1.setVisible(false);
clickOn(owner);
if (!checkFocusedWindow(owner)) {
stopTest("Test failed: actual focused window didn't get a focus");
}
if (!checkFocusOwner(testButton1)) {
stopTest("Test failed: actual focus owner didn't get a focus");
}
step = 8;
window1.setVisible(true);
waitTillShown(window1);
clickOnCheckFocusOwner(testButton2);
clickOnCheckFocusedWindow(frame);
clickOn(owner);
if (!checkFocusedWindow(window1)) {
stopTest("Test failed: actual focused window didn't get a focus");
}
if (!checkFocusOwner(testButton2)) {
stopTest("Test failed: actual focus owner didn't get a focus");
}
}
boolean checkFocusOwner(Component comp) {
return (comp == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
boolean checkFocusedWindow(Window win) {
return (win == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow());
}
void waitTillShown(Component c) {
((sun.awt.SunToolkit) Toolkit.getDefaultToolkit()).realSync();
}
void clickOnCheckFocusOwner(Component c) {
clickOn(c);
if (!checkFocusOwner(c)) {
stopTest("Error: can't bring a focus on Component by clicking on it");
}
}
void clickOnCheckFocusedWindow(Frame f) {
clickOn(f);
if (!checkFocusedWindow(f)) {
stopTest("Error: can't bring a focus on Frame by clicking on it");
}
}
void clickOn(Component c)
{
Point p = c.getLocationOnScreen();
Dimension d = c.getSize();
if (c instanceof Frame) {
robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2);
} else {
robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2));
}
pause(100);
robot.mousePress(InputEvent.BUTTON1_MASK);
pause(100);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
waitForIdle();
}
void waitForIdle() {
((sun.awt.SunToolkit) Toolkit.getDefaultToolkit()).realSync();
}
void pause(int msec) {
try {
Thread.sleep(msec);
} catch (InterruptedException e) {
Sysout.println("pause: non-fatal exception caught:");
e.printStackTrace();
}
}
void stopTest(String msg) {
throw new RuntimeException(new String("Step " + step + ": " + msg));
}
}
class TestWindow extends Window {
TestWindow(Frame owner, Button otherButton, Button testButton, int x, int y) {
super(owner);
setLayout(new FlowLayout());
setLocation(x, y);
add(testButton);
add(otherButton);
pack();
setBackground(Color.green);
}
}
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
<html>
<!--
test
@bug 4041703 4096228 4025223 4260929
@summary Ensures that appletviewer sets a reasonable default focus
for an Applet on start
@author das area=appletviewer
@run shell AppletInitialFocusTest.sh
-->
<head>
<title> AppletInitialFocusTest </title>
</head>
<body>
<h1>AppletInitialFocusTest<br>Bug ID: 4041703</h1>
<p> See the dialog box (usually in upper left corner) for instructions</p>
<APPLET CODE="AppletInitialFocusTest.class" WIDTH=200 HEIGHT=200></APPLET>
</body>
</html>
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
test
@bug 4041703 4096228 4025223 4260929
@summary Ensures that appletviewer sets a reasonable default focus
for an Applet on start
@author das area=appletviewer
@run shell AppletInitialFocusTest.sh
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
class MyKeyboardFocusManager extends DefaultKeyboardFocusManager {
public Window getGlobalFocusedWindow() {
return super.getGlobalFocusedWindow();
}
}
public class AppletInitialFocusTest extends Applet {
Window window;
Button button = new Button("Button");
MyKeyboardFocusManager manager = new MyKeyboardFocusManager();
Object lock = new Object();
public void init() {
KeyboardFocusManager.setCurrentKeyboardFocusManager(manager);
Component parent = this;
while (parent != null && !(parent instanceof Window)) {
parent = parent.getParent();
}
/*
* This applet is designed to be run only with appletviewer,
* so there always should be a toplevel frame.
*/
if (parent == null) {
synchronized (lock) {
System.err.println("appletviewer not running");
System.exit(3);
}
}
window = (Window)parent;
button.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
synchronized (lock) {
System.err.println("passed");
System.exit(0);
}
}
});
add(button);
}
public void start() {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
synchronized (lock) {
Window focused = manager.getGlobalFocusedWindow();
if (window == focused) {
System.err.println("failed");
System.exit(2);
} else {
System.err.println("window never activated");
System.err.println(focused);
System.exit(0);
}
}
} catch(InterruptedException e) {
}
}
});
thread.start();
}
}
<html>
<!--
test
@bug 4411534 4517274
@summary ensures that user's requestFocus() during applet initialization
is not ignored
@author prs area=appletviewer
@run shell AppletInitialFocusTest1.sh
-->
<head>
<title> AppletInitialFocusTest1 </title>
</head>
<body>
<h1>AppletInitialFocusTest1<br>Bug ID: 4517274</h1>
<p> See the dialog box (usually in upper left corner) for instructions</p>
<APPLET CODE="AppletInitialFocusTest1.class" WIDTH=200 HEIGHT=200></APPLET>
</body>
</html>
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
test
@bug 4411534 4517274
@summary ensures that user's requestFocus() during applet initialization
is not ignored.
@author prs area=appletviewer
@run shell AppletInitialFocusTest1.sh
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class AppletInitialFocusTest1 extends Applet implements FocusListener {
Button button1 = new Button("Button1");
Button button2 = new Button("Button2");
Object lock = new Object();
public void init() {
Component parent = this;
while (parent != null && !(parent instanceof Window)) {
parent = parent.getParent();
}
/*
* This applet is designed to be run only with appletviewer,
* so there always should be a toplevel frame.
*/
if (parent == null) {
synchronized (lock) {
System.err.println("appletviewer not running");
System.exit(3);
}
}
button1.addFocusListener(this);
button2.addFocusListener(this);
add(button1);
add(button2);
button2.requestFocus();
}
public void focusGained(FocusEvent e) {
if (e.getSource() == button1) {
synchronized (lock) {
System.err.println("failed: focus on the wrong button");
System.exit(2);
}
}
}
public void focusLost(FocusEvent e) {
}
public void start() {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
synchronized (lock) {
System.err.println("passed");
System.exit(0);
}
} catch(InterruptedException e) {
}
}
});
thread.start();
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
test
@bug 4752312
@summary Tests that after moving non-focusable window it ungrabs mouse pointer
@author dom@sparc.spb.su: area=awt.focus
@run applet FrameJumpingToMouse.html
*/
// Note there is no @ in front of test above. This is so that the
// harness will not mistake this file as a test file. It should
// only see the html file as a test file. (the harness runs all
// valid test files, so it would run this test twice if this file
// were valid as well as the html file.)
// Also, note the area= after Your Name in the author tag. Here, you
// should put which functional area the test falls in. See the
// AWT-core home page -> test areas and/or -> AWT team for a list of
// areas.
// Note also the 'FrameJumpingToMouse.html' in the run tag. This should
// be changed to the name of the test.
/**
* FrameJumpingToMouse.java
*
* summary:
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
//Automated tests should run as applet tests if possible because they
// get their environments cleaned up, including AWT threads, any
// test created threads, and any system resources used by the test
// such as file descriptors. (This is normally not a problem as
// main tests usually run in a separate VM, however on some platforms
// such as the Mac, separate VMs are not possible and non-applet
// tests will cause problems). Also, you don't have to worry about
// synchronisation stuff in Applet tests they way you do in main
// tests...
public class FrameJumpingToMouse extends Applet
{
//Declare things used in the test, like buttons and labels here
JFrame frame = new JFrame("Test jumping frame");
Robot robot = null;
public void init()
{
//Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout (new BorderLayout ());
frame.setFocusableWindowState(false);
frame.setBounds(100, 100, 100, 100);
}//End init()
public void start ()
{
//Get things going. Request focus, set size, et cetera
setSize (200,200);
setVisible(true);
validate();
try {
robot = new Robot();
} catch (Exception e) {
throw new RuntimeException("Can't create robot");
}
frame.setVisible(true);
robot.delay(1000);
Point frameLoc = frame.getLocationOnScreen();
robot.mouseMove(frameLoc.x+frame.getWidth()/4, frameLoc.y+frame.getInsets().top/2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseMove(frameLoc.x+100, frameLoc.y+50);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Toolkit.getDefaultToolkit().sync();
robot.waitForIdle();
frameLoc = frame.getLocation();
robot.mouseMove(frameLoc.x+frame.getWidth()/2, frameLoc.y+frame.getHeight()/2);
Toolkit.getDefaultToolkit().sync();
robot.waitForIdle();
if (!(frame.getLocation().equals(frameLoc))) {
throw new RuntimeException("Frame is moving to mouse with grab");
}
}// start()
}// class FrameJumpingToMouse
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
show();
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 6182359
@summary Tests that Window having non-focusable owner can't be a focus owner.
@author Anton Tarasov: area=awt.focus
@run applet NonfocusableOwnerTest.html
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.lang.reflect.*;
import java.io.*;
public class NonfocusableOwnerTest extends Applet {
Robot robot;
Frame frame;
Dialog dialog;
Window window1;
Window window2;
Button button = new Button("button");
// PrintStream Sysout = System.out;
public static void main(String[] args) {
NonfocusableOwnerTest test = new NonfocusableOwnerTest();
test.init();
test.start();
}
public void init() {
try {
robot = new Robot();
} catch (AWTException e) {
throw new RuntimeException("Error: unable to create robot", e);
}
// Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout (new BorderLayout ());
}
public void start() {
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent e) {
Sysout.println(e.toString());
}
}, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK | WindowEvent.WINDOW_EVENT_MASK);
frame = new Frame("Frame");
frame.setName("Frame-owner");
dialog = new Dialog(frame, "Dialog");
dialog.setName("Dialog-owner");
window1 = new Window(frame);
window1.setName("1st child");
window2 = new Window(window1);
window2.setName("2nd child");
test1(frame, window1);
test2(frame, window1, window2);
test3(frame, window1, window2);
window1 = new Window(dialog);
window1.setName("1st child");
window2 = new Window(window1);
window2.setName("2nd child");
test1(dialog, window1);
test2(dialog, window1, window2);
test3(dialog, window1, window2);
Sysout.println("Test passed.");
}
void test1(Window owner, Window child) {
Sysout.println("* * * STAGE 1 * * *\nowner=" + owner);
owner.setFocusableWindowState(false);
owner.setSize(100, 100);
owner.setVisible(true);
child.add(button);
child.setBounds(0, 300, 100, 100);
child.setVisible(true);
waitTillShown(child);
clickOn(button);
if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
throw new RuntimeException("Test Failed.");
}
owner.dispose();
child.dispose();
}
void test2(Window owner, Window child1, Window child2) {
Sysout.println("* * * STAGE 2 * * *\nowner=" + owner);
owner.setFocusableWindowState(false);
owner.setSize(100, 100);
owner.setVisible(true);
child1.setFocusableWindowState(true);
child1.setBounds(0, 300, 100, 100);
child1.setVisible(true);
child2.add(button);
child2.setBounds(0, 500, 100, 100);
child2.setVisible(true);
clickOn(button);
if (button == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
throw new RuntimeException("Test failed.");
}
owner.dispose();
child1.dispose();
child2.dispose();
}
void test3(Window owner, Window child1, Window child2) {
Sysout.println("* * * STAGE 3 * * *\nowner=" + owner);
owner.setFocusableWindowState(true);
owner.setSize(100, 100);
owner.setVisible(true);
child1.setFocusableWindowState(false);
child1.setBounds(0, 300, 100, 100);
child1.setVisible(true);
child2.setFocusableWindowState(true);
child2.add(button);
child2.setBounds(0, 500, 100, 100);
child2.setVisible(true);
clickOn(button);
System.err.println("focus owner: " + KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
if (button != KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
throw new RuntimeException("Test failed.");
}
owner.dispose();
child1.dispose();
child2.dispose();
}
void clickOn(Component c) {
Point p = c.getLocationOnScreen();
Dimension d = c.getSize();
Sysout.println("Clicking " + c);
if (c instanceof Frame) {
robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2);
} else {
robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2));
}
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
waitForIdle();
}
void waitTillShown(Component c) {
while (true) {
try {
Thread.sleep(100);
c.getLocationOnScreen();
break;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (IllegalComponentStateException e) {}
}
}
void waitForIdle() {
try {
Toolkit.getDefaultToolkit().sync();
sun.awt.SunToolkit.flushPendingEvents();
EventQueue.invokeAndWait( new Runnable() {
public void run() {} // Dummy implementation
});
} catch(InterruptedException ie) {
Sysout.println("waitForIdle, non-fatal exception caught:");
ie.printStackTrace();
} catch(InvocationTargetException ite) {
Sysout.println("waitForIdle, non-fatal exception caught:");
ite.printStackTrace();
}
// wait longer...
robot.delay(200);
}
}
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
System.err.println(messageIn);
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 4452384
@summary Tests that non-focusable windows doesn't generate any focus events when accessed.
@author dom: area=awt.focus
@run main Test
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Test extends Frame {
public static final int DEF_WIDTH = 400,
DEF_HEIGHT = 300,
DEF_TOP = 1,
DEF_LEFT = 100,
DEF_ROW = 0,
DEF_COL = 0;
static boolean automatic = true;
static Window[] windows;
static Frame main_frame, jumpingFrame;
static Button focus_button;
static Robot robot;
static void pause(int timeout) {
Toolkit.getDefaultToolkit().sync();
robot.waitForIdle();
robot.delay(100);
}
static GlobalListener listener;
public static void main(String[] args) {
listener = new GlobalListener();
Toolkit.getDefaultToolkit().addAWTEventListener(listener,
AWTEvent.FOCUS_EVENT_MASK |
AWTEvent.WINDOW_EVENT_MASK);
try{
robot = new Robot();
} catch(Exception e) {}
// Create several pairs - focusable Frame with focusable component(button) and non-focusable:
// window, resizable frame, non-resizable frame, dialog, non-resiable dialog
main_frame = new Frame("focusable frame");
focus_button = new Button("button to focus");
main_frame.add(focus_button);
main_frame.pack();
main_frame.setVisible(true);
main_frame.setLocation(10, 600);
main_frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
listener.report();
System.exit(0);
}
});
jumpingFrame = new Frame("Jumping frame");
jumpingFrame.setBounds(DEF_LEFT, DEF_TOP, DEF_WIDTH, DEF_HEIGHT);
windows = new Window[7];
windows[0] = new TestWindow(0, 0, false, main_frame);
//windows[1] = new TestWindow(2, 1, true, main_frame);
windows[2] = new Test(1, 0, false, true);
windows[3] = new Test(2, 0, false, false);
//windows[4] = new Test(3, 0, true, true);
windows[5] = new TestDialog(0, 1, false, true, main_frame);
windows[6] = new TestDialog(1, 1, false, false, main_frame);
if (!automatic) {
int windowInd;
for (windowInd = 0; windowInd < windows.length; windowInd++) {
if (windows[windowInd] != null) {
windows[windowInd].setVisible(true);
}
}
}
// Run the test
// 1. Click on all controls, check for no focus events for non-focusable, right focus events for focusable
// 2. Perform some action with control, check if it works
if (automatic) {
int windowInd;
for (windowInd = 0; windowInd < windows.length; windowInd++) {
if (windows[windowInd] != null) {
windows[windowInd].setVisible(true);
focus_button.requestFocus();
pause(1000);
// Verify that click on non-focusable window causes no focus lost on active window
performFocusClick(windows[windowInd]);
focus_button.requestFocus();
pause(500);
performActionClick(windows[windowInd]);
// Verify that toFront, toBack doesn't cause non-focusable window to become active
jumpingFrame.setVisible(true);
pause(1000);
jumpingFrame.toBack();
pause(500);
jumpingFrame.toFront();
pause(500);
windows[windowInd].toBack();
pause(500);
windows[windowInd].toFront();
pause(500);
// Verify that iconifiyng/deiconfiying and
// zooming/unzooming doesn't cause non-focusable
// window to become active
if (windows[windowInd] instanceof Frame) {
Frame toTest = (Frame)windows[windowInd];
// Deiconification currently doesn't work!
// toTest.setExtendedState(Frame.ICONIFIED);
// pause(500);
// toTest.setExtendedState(Frame.NORMAL);
pause(500);
toTest.setExtendedState(Frame.MAXIMIZED_BOTH);
pause(500);
toTest.setExtendedState(Frame.NORMAL);
}
windows[windowInd].dispose();
jumpingFrame.dispose();
}
}
pause(1000);
System.err.println("Test finished.");
if (!listener.report()) {
throw new RuntimeException("Test Failed. See error stream output for details");
}
}
}
static void performFocusClick(Window parent) {
if (parent == null) {
return;
}
for (int compInd = 0; compInd < parent.getComponentCount(); compInd++) {
Component child = parent.getComponent(compInd);
if (child instanceof TestPanel) {
TestPanel pan = (TestPanel)child;
pan.performFocusClicks(robot);
pause(100);
}
}
}
static void performActionClick(Window parent) {
if (parent == null) {
return;
}
for (int compInd = 0; compInd < parent.getComponentCount(); compInd++) {
Component child = parent.getComponent(compInd);
if (child instanceof TestPanel) {
TestPanel pan = (TestPanel)child;
pan.performActionClicks(robot);
pause(100);
}
}
}
public Test(int row, int col, boolean focusable, boolean resizable) {
super("Frame" + row + "" + col);
TestPanel panel = new TestPanel(row, col);
if (Test.automatic) {
row = Test.DEF_ROW;
col = Test.DEF_COL;
}
setName(getTitle());
add("Center", panel);
Label l = new Label(getClass().getSuperclass().getName() + ", " + (focusable?"focusable":"non-focusable") +
", " + (resizable?"resizable":"non-resizable"));
l.setBackground(Color.green);
add("North", l);
setBounds(Test.DEF_LEFT + DEF_WIDTH*col, DEF_TOP + DEF_HEIGHT*row, DEF_WIDTH, DEF_HEIGHT);
if (!focusable) {
setFocusableWindowState(false);
}
if (!resizable) {
setResizable(false);
}
// setVisible(true);
}
}
class TestWindow extends Window {
public TestWindow(int row, int col, boolean focusable, Frame owner) {
super(owner);
setName("Window" + row + "" + col);
TestPanel panel = new TestPanel(row, col);
if (Test.automatic) {
row = Test.DEF_ROW;
col = Test.DEF_COL;
}
add("Center", panel);
Label l = new Label(getClass().getSuperclass().getName() + ", " + (focusable?"focusable":"non-focusable") +
", " + (false?"resizable":"non-resizable"));
l.setBackground(Color.green);
add("North", l);
setBounds(Test.DEF_LEFT + Test.DEF_WIDTH*col, Test.DEF_TOP + Test.DEF_HEIGHT*row, Test.DEF_WIDTH, Test.DEF_HEIGHT);
if (!focusable) {
setFocusableWindowState(false);
}
// setVisible(true);
}
}
class TestDialog extends Dialog {
public TestDialog(int row, int col, boolean focusable, boolean resizable, Frame owner) {
super(owner);
setName("Dialog" + row + "" + col);
TestPanel panel = new TestPanel(row, col);
if (Test.automatic) {
row = Test.DEF_ROW;
col = Test.DEF_COL;
}
add("Center", panel);
Label l = new Label(getClass().getSuperclass().getName() + ", " + (focusable?"focusable":"non-focusable") +
", " + (resizable?"resizable":"non-resizable"));
l.setBackground(Color.green);
add("North", l);
setBounds(Test.DEF_LEFT + Test.DEF_WIDTH*col, Test.DEF_TOP + Test.DEF_HEIGHT*row, Test.DEF_WIDTH, Test.DEF_HEIGHT);
if (!focusable) {
setFocusableWindowState(false);
}
if (!resizable) {
setResizable(false);
}
// setVisible(true);
}
}
class TestPanel extends Panel {
void clickComponent(Component comp, Robot robot) {
if (comp instanceof Choice) {
return;
}
Point compLoc = comp.getLocationOnScreen();
Dimension size = comp.getSize();
robot.mouseMove(compLoc.x + size.width/2, compLoc.y + size.height/2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
void performFocusClicks(Robot robot) {
for (int childInd = 0; childInd < getComponentCount(); childInd++) {
performFocusClick(getComponent(childInd), robot);
}
}
void performFocusClick(Component comp, Robot robot) {
clickComponent(comp, robot);
}
void performActionClicks(Robot robot) {
for (int childInd = 0; childInd < getComponentCount(); childInd++) {
performActionClick(getComponent(childInd), robot);
}
}
void performActionClick(Component comp, Robot robot) {
}
public TestPanel(int row, int col) {
setLayout(new FlowLayout());
Button b;
add(b = new Button("press"+ row + "" + col));
b.setName(b.getLabel());
// b.addMouseListener(new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// System.err.println(e);
// }
// });
TextField t;
add(t = new TextField("text" + row + "" + col));
t.setName(t.getText());
java.awt.List list = new java.awt.List();
add(list);
list.setName("list");
list.add("one");
list.add("two");
list.add("three");
list.setMultipleMode(true);
list.setName("list" + row + "" + col);
Checkbox check = new Checkbox("checker");
add(check);
check.setName("check" + row + "" + col);
Choice choice = new Choice();
choice.add("one");
choice.add("two");
choice.add("three");
add(choice);
choice.setName("choice" + row + "" + col);
Canvas can = new Canvas() {
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
};
can.setBackground(Color.blue);
add(can);
can.setName("canvas" + row + "" + col);
TextArea ta = new TextArea("text\ntttt\naaaa\nwwwww\nqqqqqq\neeeeee\nrrrrrr\nyyyyyy\nuuuuu", 3, 5);
add(ta);
ta.setName("textarea" + row + "" + col);
Scrollbar bar = new Scrollbar(Scrollbar.HORIZONTAL);
add(bar);
bar.setName("scrollbar" + row + "" + col);
CheckboxGroup group = new CheckboxGroup();
Checkbox ch1 = new Checkbox("one", group, true);
Checkbox ch2 = new Checkbox("two", group, false);
add(ch1);
add(ch2);
ch1.setName("checkbox1 " + row + "" + col);
ch2.setName("checkbox2 " + row + "" + col);
ScrollPane pane = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
add(pane);
Button bigButton = new Button("abc") {
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
pane.add(bigButton);
bigButton.setName("bigbutton" + row + "" + col);
}
}
class GlobalListener implements AWTEventListener {
java.util.List errors = new java.util.LinkedList();
public boolean report() {
if (errors.size() != 0) {
System.err.println("Test FAILED");
} else {
System.err.println("Test PASSED");
return true;
}
ListIterator iter = errors.listIterator();
while (iter.hasNext()) {
System.err.println(iter.next());
}
return false;
}
public GlobalListener() {
}
Window getWindowParent(Component comp) {
while (comp != null && !(comp instanceof Window)) {
comp = comp.getParent();
}
return (Window)comp;
}
void reportError(AWTEvent e, String message) {
String error = "ERROR: " + message + " : " + e;
errors.add(error);
System.err.println(error);
}
public void eventDispatched(AWTEvent e) {
Component comp = (Component)e.getSource();
Window parent = getWindowParent(comp);
if (!(e instanceof WindowEvent || e instanceof FocusEvent)) {
System.err.println("Strange event " + e);
}
// Skip WINDOW_OPENED
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.err.println(e);
}
switch (e.getID()) {
case WindowEvent.WINDOW_OPENED:
case WindowEvent.WINDOW_CLOSING:
case WindowEvent.WINDOW_CLOSED:
case WindowEvent.WINDOW_ICONIFIED:
case WindowEvent.WINDOW_DEICONIFIED:
case WindowEvent.WINDOW_STATE_CHANGED:
return;
case WindowEvent.WINDOW_LOST_FOCUS: {
WindowEvent we = (WindowEvent)e;
if (we.getOppositeWindow() != null && !we.getOppositeWindow().getFocusableWindowState()) {
reportError(e, "frame lost focus because of non-focusable window");
}
break;
}
}
// Check that Window owner is focusable
if (!parent.getFocusableWindowState()) {
reportError(e, "focus event for component in non-focusable window " + parent.getName());
}
if (!comp.isFocusable()) {
reportError(e, "focus event for non-focusable component");
}
// if (e instanceof WindowEvent || e instanceof FocusEvent) {
// // System.err.println(e);
// }
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 6183877 6216005 6225560
@summary Tests that keyboard input doesn't freeze due to type-ahead problems
@author Denis Mikhalkin: area=awt.focus
@run main/timeout=300 TestFocusFreeze
*/
// Note the area= after Your Name in the author tag. Here, you
// should put which functional area the test falls in. See the
// AWT-core home page -> test areas and/or -> AWT team for a list of
// areas.
/**
* TestFocusFreeze.java
*
* summary: XXX A brief summary of what this tests
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.concurrent.atomic.*;
import sun.awt.SunToolkit;
public class TestFocusFreeze
{
//*** test-writer defined static variables go here ***
private static void init()
{
//*** Create instructions for the user here ***
FocusTest.test();
}//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()
{
Sysout.println( "The test passed." );
Sysout.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 )
{
Sysout.println( "The test failed: " + whyFailed );
Sysout.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 TestFocusFreeze
//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
{
}
//*********** End Standard Test Machinery Section **********
//************ Begin classes defined for the test ****************
// if want to make listeners, here is the recommended place for them, then instantiate
// them in init()
/* Example of a class which may be written as part of a test
class NewClass implements anInterface
{
static int newVar = 0;
public void eventDispatched(AWTEvent e)
{
//Counting events to see if we get enough
eventCount++;
if( eventCount == 20 )
{
//got enough events, so pass
TestFocusFreeze.pass();
}
else if( tries == 20 )
{
//tried too many times without getting enough events so fail
TestFocusFreeze.fail();
}
}// eventDispatched()
}// NewClass class
*/
//************** End classes defined for the test *******************
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
System.out.println(messageIn);
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
class FocusTest extends JFrame implements ActionListener {
private JDialog pageDialog = null;
private AtomicBoolean passed = new AtomicBoolean();
private static volatile boolean all_passed = true;
private static volatile long pressTime;
private static Object testLock = new Object();
private static Object resultLock = new Object();
public FocusTest() {
final GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
pageDialog = new JDialog(this, "JDialog", true, gc);
Container c = pageDialog.getContentPane();
c.setLayout(new BorderLayout());
JButton btnApprove =new JButton("Exit Button");
btnApprove.addActionListener(this);
c.add("South", btnApprove);
pageDialog.pack();
JButton bb = new JButton("Action");
bb.addActionListener(new ActionListener() {
final JDialog pageDialog = FocusTest.this.pageDialog;
public void actionPerformed(ActionEvent e) {
synchronized(testLock) {
testLock.notify();
}
pageDialog.setVisible(true);
}
});
add(bb);
pack();
setVisible(true);
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
bb.requestFocus();
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
if (!bb.isFocusOwner()) {
System.err.println("Couldn't make bb focused");
all_passed = false;
return;
}
new Thread() {
public void run() {
try {
Robot r = new Robot();
synchronized (testLock) {
testLock.wait();
}
r.keyPress(KeyEvent.VK_SPACE);
r.delay(50);
r.keyRelease(KeyEvent.VK_SPACE);
synchronized(passed) {
passed.wait(1000);
}
pageDialog.dispose();
FocusTest.this.dispose();
if (!passed.get()) {
all_passed = false;
}
} catch (Exception e) {
e.printStackTrace();
}
synchronized (resultLock) {
resultLock.notifyAll();
}
}
}.start();
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_SPACE);
r.delay(50);
r.keyRelease(KeyEvent.VK_SPACE);
} catch (Exception e) {
e.printStackTrace();
all_passed = false;
return;
}
try {
synchronized (resultLock) {
resultLock.wait();
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae) {
System.err.println("Action performed");
passed.set(true);
synchronized(passed) {
passed.notify();
}
}
public static void test() {
FocusTest test = null;
for (int i = 0; i < 10; i++) {
test = new FocusTest();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
if (!all_passed) {
TestFocusFreeze.fail("Not all passed");
} else {
TestFocusFreeze.pass();
}
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
test
@bug 4782886
@summary FocusManager consumes wrong KEYTYPED-Events
@author son: area=awt.focus
@run applet WrongKeyTypedConsumedTest.html
*/
/**
* WrongKeyTypedConsumedTest.java
*
* summary: FocusManager consumes wrong KEYTYPED-Events
*/
import java.applet.Applet;
import java.awt.AWTException;
import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Robot;
import java.awt.TextArea;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class WrongKeyTypedConsumedTest extends Applet
{
//Declare things used in the test, like buttons and labels here
public void init()
{
//Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
String[] instructions =
{
"This is an AUTOMATIC test",
"simply wait until it is done"
};
Sysout.createDialog( );
Sysout.printInstructions( instructions );
}//End init()
public void start ()
{
//Get things going. Request focus, set size, et cetera
setSize (200,200);
setVisible(true);
validate();
JFrame frame = new JFrame("The Frame");
Set ftk = new HashSet();
ftk.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_DOWN, 0));
frame.getContentPane().
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
ftk);
JCheckBox checkbox = new JCheckBox("test");
frame.getContentPane().add(checkbox, BorderLayout.NORTH);
JTextArea textarea = new JTextArea(40, 10);
frame.getContentPane().add(textarea);
frame.pack();
frame.setVisible(true);
try {
Robot robot = new Robot();
// wait for activation
robot.delay(2000);
if (!frame.isActive()) {
Point loc = frame.getLocationOnScreen();
Dimension size = frame.getSize();
robot.mouseMove(loc.x + size.width/2,
loc.y + size.height/2);
frame.toFront();
robot.delay(1000);
if (!frame.isActive()) {
throw new RuntimeException("Test Fialed: frame isn't active");
}
}
// verify if checkbox has focus
if (!checkbox.isFocusOwner()) {
checkbox.requestFocusInWindow();
robot.delay(1000);
if (!checkbox.isFocusOwner()) {
throw new RuntimeException("Test Failed: checkbox doesn't have focus");
}
}
// press VK_DOWN
robot.keyPress(KeyEvent.VK_DOWN);
robot.delay(250);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.delay(1000);
// verify if text area has focus
if (!textarea.isFocusOwner()) {
throw new RuntimeException("Test Failed: focus wasn't transfered to text area");
}
// press '1'
robot.keyPress(KeyEvent.VK_1);
robot.delay(250);
robot.keyRelease(KeyEvent.VK_1);
robot.delay(1000);
// verify if KEY_TYPED arraived
if (!"1".equals(textarea.getText())) {
throw new RuntimeException("Test Failed: text area text is \"" + textarea.getText() + "\", not \"1\"");
}
} catch(AWTException e) {
e.printStackTrace();
throw new RuntimeException("Test failed because of some internal exception");
}
Sysout.println("Test Passed");
}// start()
}// class WrongKeyTypedConsumedTest
/****************************************************
Standard Test Machinery
DO NOT modify anything below -- it's a standard
chunk of code whose purpose is to make user
interaction uniform, and thereby make it simpler
to read and understand someone else's test.
****************************************************/
/**
This is part of the standard test machinery.
It creates a dialog (with the instructions), and is the interface
for sending text messages to the user.
To print the instructions, send an array of strings to Sysout.createDialog
WithInstructions method. Put one line of instructions per array entry.
To display a message for the tester to see, simply call Sysout.println
with the string to be displayed.
This mimics System.out.println but works within the test harness as well
as standalone.
*/
class Sysout
{
private static TestDialog dialog;
public static void createDialogWithInstructions( String[] instructions )
{
dialog = new TestDialog( new Frame(), "Instructions" );
dialog.printInstructions( instructions );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void createDialog( )
{
dialog = new TestDialog( new Frame(), "Instructions" );
String[] defInstr = { "Instructions will appear here. ", "" } ;
dialog.printInstructions( defInstr );
dialog.setVisible(true);
println( "Any messages for the tester will display here." );
}
public static void printInstructions( String[] instructions )
{
dialog.printInstructions( instructions );
}
public static void println( String messageIn )
{
dialog.displayMessage( messageIn );
}
}// Sysout class
/**
This is part of the standard test machinery. It provides a place for the
test instructions to be displayed, and a place for interactive messages
to the user to be displayed.
To have the test instructions displayed, see Sysout.
To have a message to the user be displayed, see Sysout.
Do not call anything in this dialog directly.
*/
class TestDialog extends Dialog
{
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog( Frame frame, String name )
{
super( frame, name );
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth );
add( "North", instructionsText );
messageText = new TextArea( "", 5, maxStringLength, scrollBoth );
add("Center", messageText);
pack();
setVisible(true);
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions( String[] instructions )
{
//Clear out any current instructions
instructionsText.setText( "" );
//Go down array of instruction strings
String printStr, remainingStr;
for( int i=0; i < instructions.length; i++ )
{
//chop up each into pieces maxSringLength long
remainingStr = instructions[ i ];
while( remainingStr.length() > 0 )
{
//if longer than max then chop off first max chars to print
if( remainingStr.length() >= maxStringLength )
{
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf( ' ', maxStringLength - 1 );
if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring( 0, posOfSpace + 1 );
remainingStr = remainingStr.substring( posOfSpace + 1 );
}
//else just print
else
{
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append( printStr + "\n" );
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage( String messageIn )
{
messageText.append( messageIn + "\n" );
System.out.println(messageIn);
}
}// TestDialog class
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册