8339842: Open source several AWT focus tests - series 2

Reviewed-by: prr
This commit is contained in:
Prasanta Sadhukhan 2024-09-16 05:41:58 +00:00
parent dc00eb87bc
commit 4b7906375b
4 changed files with 701 additions and 0 deletions

@ -0,0 +1,122 @@
/*
* Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4060975
* @summary tests that a component doesn't lose focus on resize
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual FocusChangeOnResizeTest
*/
import java.util.List;
import java.awt.Button;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class FocusChangeOnResizeTest {
private static final String INSTRUCTIONS = """
For the Frame and the Dialog:
Press the LOWER BUTTON to resize the Frame or Dialog programmatically.
Give the focus to the LOWER BUTTON and resize the Frame or Dialog manually.
If the LOWER BUTTON always has focus after resize
(for both frame and dialog) the test passes.""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("PopupMenu Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 2)
.columns(35)
.testUI(FocusChangeOnResizeTest::createTestUI)
.logArea()
.build()
.awaitAndCheck();
}
private static List<Window> createTestUI() {
Frame frame = new Frame("FocusChangeOnResizeTest frame");
Dialog dialog = new Dialog(frame, "Test dialog");
frame.add(new TestPanel(frame));
dialog.add(new TestPanel(dialog));
frame.setBounds (150, 200, 200, 200);
dialog.setBounds (150, 500, 200, 200);
return List.of(frame, dialog);
}
static FocusListener eventLogger = new FocusListener() {
public void focusGained(FocusEvent e) {
PassFailJFrame.log(e.toString());
}
public void focusLost(FocusEvent e) {
PassFailJFrame.log(e.toString());
}
};
}
class TestPanel extends Panel {
TextField textField = new TextField("TEXT FIELD");
Button button1 = new Button("UPPER BUTTON");
Button button2 = new Button("LOWER BUTTON");
public TestPanel(Window parent) {
setLayout(new GridLayout(3, 1));
add(textField);
add(button1);
add(button2);
textField.setName("TEXT FIELD");
button1.setName("UPPER BUTTON");
button2.setName("LOWER BUTTON");
textField.addFocusListener(FocusChangeOnResizeTest.eventLogger);
button1.addFocusListener(FocusChangeOnResizeTest.eventLogger);
button2.addFocusListener(FocusChangeOnResizeTest.eventLogger);
button2.addActionListener(new Resizer(parent));
}
}
class Resizer implements ActionListener {
Window target;
public Resizer(Window window) {
target = window;
}
public void actionPerformed(ActionEvent e) {
target.setSize(200, 100);
target.doLayout();
target.pack();
}
}

@ -0,0 +1,261 @@
/*
* Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4124119
* @summary Checks that lightweight components do not lose focus after
dragging the frame by using the mouse.
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual LightweightFocusLostTest
*/
import java.awt.AWTEvent;
import java.awt.AWTEventMulticaster;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Label;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LightweightFocusLostTest {
private static final String INSTRUCTIONS = """
Steps to try to reproduce this problem:
When this test is run a window will display (Test Focus).
Click in the text field to give it the focus (a blinking cursor
will appear) and then move the frame with the mouse. The text field
(component which uses a lightweight component) should still have focus.
You should still see the blinking cursor in the text field after the
frame has been moved. If this is the behavior that you observe, the
test has passed, Press the Pass button. Otherwise the test has failed,
Press the Fail button.""";
public static void main(String[] args) throws Exception {
PassFailJFrame.builder()
.title("LightweightFocusLostTest Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 5)
.columns(35)
.testUI(LightweightFocusLostTest::createTestUI)
.logArea()
.build()
.awaitAndCheck();
}
private static Frame createTestUI() {
Frame f = new Frame("LightweightFocusLostTest");
f.setLayout(new BorderLayout());
String sLabel = "Lightweight component below (text field)";
Label TFL = new Label(sLabel, Label.LEFT);
f.add(TFL, BorderLayout.NORTH);
SimpleTextField canvas = new SimpleTextField(30, 5);
f.add(canvas, BorderLayout.CENTER);
f.setSize(new Dimension(300,125));
f.requestFocus();
return f;
}
}
class SimpleTextField extends Component implements Runnable {
int border;
int length;
Font font;
FontMetrics fontM;
char[] buffer;
int bufferIx;
boolean hasFocus;
boolean cursorOn;
SimpleTextField(int len, int bor) {
super();
border = bor;
length = len;
buffer = new char[len];
font = getFont();
if (font == null) {
font = new Font("Dialog", Font.PLAIN, 20);
}
fontM = getFontMetrics(font);
// Listen for key and mouse events.
this.addMouseListener(new MouseEventHandler());
this.addFocusListener(new FocusEventHandler());
this.addKeyListener(new KeyEventHandler());
// Set text cursor.
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
// Start the thread that blinks the cursor.
(new Thread(this)).start();
}
public Dimension getMinimumSize() {
// The minimum height depends on the point size.
int w = fontM.charWidth('m') * length;
return new Dimension(w + 2 * border, fontM.getHeight() + 2 * border);
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMaximumSize() {
return new Dimension(Short.MAX_VALUE, getPreferredSize().height);
}
public boolean isFocusTraversable() {
return true;
}
public void paint(Graphics g) {
int y = (getSize().height-fontM.getHeight())/2;
// Clear the background using the text background color.
g.setColor(SystemColor.text);
g.fillRect(0, 0, getSize().width, getSize().height);
g.setFont(font);
g.setColor(SystemColor.textText);
g.drawChars(buffer, 0, bufferIx, border, y + fontM.getAscent());
// Draw blinking cursor.
int x = fontM.charsWidth(buffer, 0, bufferIx) + border;
int w = fontM.charWidth('c');
if (hasFocus) {
g.setColor(getForeground());
g.fillRect(x, y, w, fontM.getHeight());
if (cursorOn) {
if (bufferIx < buffer.length) {
g.setColor(SystemColor.text);
g.fillRect(x + 2, y + 2, w - 4, fontM.getHeight() - 4);
}
}
}
}
// Event handlers
class MouseEventHandler extends MouseAdapter {
public void mousePressed(MouseEvent evt) {
requestFocus();
}
}
class FocusEventHandler extends FocusAdapter {
public void focusGained(FocusEvent evt) {
PassFailJFrame.log("Focus gained: " + evt);
hasFocus = true;
repaint();
}
public void focusLost(FocusEvent evt) {
PassFailJFrame.log("Focus lost: " + evt);
hasFocus = false;
repaint();
}
}
class KeyEventHandler extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DELETE:
case KeyEvent.VK_BACK_SPACE:
if (bufferIx > 0) {
bufferIx--;
repaint();
}
break;
case KeyEvent.VK_ENTER:
ActionEvent action =
new ActionEvent(SimpleTextField.this,
ActionEvent.ACTION_PERFORMED,
String.valueOf(buffer, 0, bufferIx));
// Send contents of buffer to listeners
processEvent(action);
break;
default:
repaint();
}
}
public void keyTyped(KeyEvent evt) {
if (bufferIx < buffer.length
&& !evt.isActionKey()
&& !Character.isISOControl(evt.getKeyChar())) {
buffer[bufferIx++] = evt.getKeyChar();
}
}
}
// Support for Action Listener.
ActionListener actionListener;
public void addActionListener(ActionListener l) {
actionListener = AWTEventMulticaster.add(actionListener, l);
}
// Override processEvent() to deal with ActionEvent.
protected void processEvent(AWTEvent evt) {
if (evt instanceof ActionEvent) {
processActionEvent((ActionEvent)evt);
} else {
super.processEvent(evt);
}
}
// Supply method to process Action event.
protected void processActionEvent(ActionEvent evt) {
if (actionListener != null) {
actionListener.actionPerformed(evt);
}
}
public void run() {
while (true) {
try {
// If component has focus, blink the cursor every 1/2 second.
Thread.sleep(500);
cursorOn = !cursorOn;
if (hasFocus) {
repaint();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

@ -0,0 +1,207 @@
/*
* Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4098290 4140890
* @summary Using non-opaque windows - popups are initially not painted correctly
* @library /java/awt/regtesthelpers
* @build PassFailJFrame
* @run main/manual MixedWeightFocus
*/
import java.util.List;
import java.awt.AWTEvent;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MixedWeightFocus {
static FocusFrame f;
private static final String INSTRUCTIONS = """
This tests that permanent FOCUS_LOST messages are sent to lightweight
components when the focus shifts to a heavyweight component. It also
tests that components retain the focus when their parent window is
deactivated and activated.
1. Tab or mouse between the light and heavyweight buttons in this test
and verify that the focus rectangle on the lightweight components
disappears when focus shifts to a heavyweight button.
2. Activate another application then reactivate the test frame window.
Verify that the component that had the focus (light or heavy) when
the frame was deactivated regains the focus when it's reactivated. Do
the same thing for the modeless dialog. Also test this by moving the
activation between the dialog and the frame.
3. Verify that lightweight components with the focus in a deactivated
window draw their focus rectangles in gray instead of blue-- this indicates
they received temporary instead of permanent FOCUS_LOST events.
NOTE: There is currently another problem with lightweight components
where if you click on one to activate its frame window, the lightweight
that previously had the focus will not get a FOCUS_LOST event. This
may manifest itself with a gray focus rectangle not getting erased.
Ignore this for now (Win32 only).""";
public static void main(String[] argv) throws Exception {
PassFailJFrame.builder()
.title("MixedWeightFocus Instructions")
.instructions(INSTRUCTIONS)
.rows((int) INSTRUCTIONS.lines().count() + 5)
.columns(45)
.testUI(MixedWeightFocus::createTestUI)
.build()
.awaitAndCheck();
}
private static List<Window> createTestUI() {
FocusFrame f = new FocusFrame();
ModelessDialog dlg = new ModelessDialog(f);
return List.of(f, dlg);
}
}
class FocusFrame extends Frame {
public FocusFrame() {
super("FocusFrame");
Panel p = new Panel();
p.add(new Button("button 1"));
p.add(new LightweightComp("lw 1"));
p.add(new Button("button 2"));
p.add(new LightweightComp("lw 2"));
add(p);
pack();
setLocation(100, 100);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
dispose();
}
});
}
}
class ModelessDialog extends Dialog {
public ModelessDialog(Frame frame) {
super(frame, "ModelessDialog", false);
setLayout( new FlowLayout() );
add(new Button("button 1"));
add(new LightweightComp("lw 1"));
pack();
setLocation(100, 400);
}
}
// simple lightweight component, focus traversable, highlights upon focus
class LightweightComp extends Component {
FontMetrics fm;
String label;
private static final int FOCUS_GONE = 0;
private static final int FOCUS_TEMP = 1;
private static final int FOCUS_HAVE = 2;
int focusLevel = FOCUS_GONE;
public static int nameCounter = 0;
public LightweightComp(String lwLabel ) {
label = lwLabel;
enableEvents(AWTEvent.FOCUS_EVENT_MASK|AWTEvent.MOUSE_EVENT_MASK);
setName("lw"+Integer.toString(nameCounter++));
}
public Dimension getPreferredSize() {
if (fm == null) {
fm = Toolkit.getDefaultToolkit().getFontMetrics(getFont());
}
return new Dimension(fm.stringWidth(label) + 2, fm.getHeight() + 2);
}
public void paint(Graphics g) {
Dimension s=getSize();
// erase the background
g.setColor(getBackground());
g.fillRect(0, 0, s.width, s.height);
g.setColor(getForeground());
// draw the string
g.drawString(label, 2, fm.getHeight());
// draw a focus rectangle
if (focusLevel > FOCUS_GONE) {
if (focusLevel == FOCUS_TEMP) {
g.setColor(Color.gray);
} else {
g.setColor(Color.blue);
}
g.drawRect(1,1,s.width-2,s.height-2);
}
}
public boolean isFocusTraversable() {
return true;
}
protected void processFocusEvent(FocusEvent e) {
super.processFocusEvent(e);
if (e.getID() == FocusEvent.FOCUS_GAINED) {
focusLevel = FOCUS_HAVE;
} else {
if (e.isTemporary()) {
focusLevel = FOCUS_TEMP;
} else {
focusLevel = FOCUS_GONE;
}
}
repaint();
}
protected void processMouseEvent(MouseEvent e) {
if (e.getID()==MouseEvent.MOUSE_PRESSED) {
requestFocus();
}
super.processMouseEvent(e);
}
}

@ -0,0 +1,111 @@
/*
* Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4474893
* @summary Component.nextFocusHelper should search for first visible focus cycle root ancst
* @key headful
* @run main NextFocusHelperTest
*/
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.FlowLayout;
import java.awt.KeyboardFocusManager;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
public class NextFocusHelperTest {
static Panel panel;
static Frame frame;
static Button btn1;
static Button btn3;
static Button hideButton;
public static void main(String[] args) throws Exception {
Robot robot = new Robot();
robot.setAutoDelay(100);
try {
EventQueue.invokeAndWait(() -> createTestUI());
robot.waitForIdle();
robot.delay(1000);
Point loc = btn1.getLocationOnScreen();
Dimension dim = btn1.getSize();
robot.mouseMove(loc.x + dim.width/2, loc.y + dim.height/2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
robot.delay(500);
Point loc1 = hideButton.getLocationOnScreen();
Dimension dim1 = hideButton.getSize();
robot.mouseMove(loc1.x + dim1.width/2, loc1.y + dim1.height/2);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.waitForIdle();
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()
instanceof Button btn) {
if (!btn.getLabel().equals("Button 3")) {
throw new RuntimeException("Wrong button has focus");
}
}
} finally {
EventQueue.invokeAndWait(() -> {
if (frame != null) {
frame.dispose();
}
});
}
}
private static void createTestUI() {
frame = new Frame("NextFocusHelperTest Frame");
frame.setLayout(new FlowLayout());
panel = new Panel();
panel.setFocusCycleRoot(true);
btn1 = new Button("Button In Panel");
panel.add(btn1);
hideButton = new Button("Hide Panel");
hideButton.setFocusable(false);
hideButton.addActionListener(e -> {
panel.setVisible(false);
});
frame.add(new Button("Button 1"));
frame.add(panel);
frame.add(new Button("Button 3"));
frame.add(hideButton);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}