I am having a checkbox and a button. I want that when i press ENTER to activate the button. It works as expected if i just press enter at run, but if i use the checkbox before, it doesn't work anymore.
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class Animation{
public Animation(){
JFrame frame = new JFrame();
Pane a = new Pane();
a.addKeyListener(a);
frame.add(a);
//frame.setUndecorated(true);
// frame.setOpacity(0.9f);
frame.setVisible(true);
frame.setSize(700, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Animation();
}
public class Pane extends JPanel implements KeyListener{
JButton buton = new JButton("BUTTON!!!! ");
JCheckBox c = new JCheckBox("Check");
public Pane(){
add(new JCheckBox("CHECKK"));
add(buton);
c.setFocusable(false);
buton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Pressed!");
}
});
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCosw() == KeyEvent.VK_ENTER){
//if(buton.isDisplayable()){
System.out.println("pressed");
//buton.doClick();
//return;
//}
}
}
}
}
keyPressed is not called in this code sample. Is buton.addKeyListener( this ); missing?
If you use checkbox, it receives a focus. You can call setFocusable( false ) on that checkbox. So the only focused component will be the button. And it will always receive key events.
Otherwise, you can add key listener to checkbox too.
Also, take a llok at this answer to find out how to set a global key listener (if you don't want to deny focusing components or don't want to add a key listener to every component).
Related
I am trying to develop a main menu for a game in java, but my JMenuItems wouldn't listen to the KeyEvents and I don't understand why. Note that I don't want to set any JMenuBars nor JMenus as this program is intended to be a game used with screen readers, so I don't want accessibility roles to be read. Furthermore, adding a menu complicates the access to the elements with the keyboard and I want the focus to start in the first option.
This is my code:
import java.util.Set;
import java.util.HashSet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.MenuKeyEvent;
import javax.swing.event.MenuKeyListener;
public class Screen {
public Screen() {
// Accept arrow keys as focus traversal keys
Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTrave rsalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
set.add(KeyStroke.getKeyStroke("DOWN"));
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,set);
set = new HashSet<AWTKeyStroke>(KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
set.add(KeyStroke.getKeyStroke("UP"));
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,set);
// definition of Menu Items
JMenuItem mi=new JMenuItem("play");
JMenuItem mi2=new JMenuItem("exit");
mi.setFocusable(true);
mi2.setFocusable(true);
// Attempt with MenuKeyListener
mi.addMenuKeyListener(new MenuKeyListener() {
public void menuKeyReleased(MenuKeyEvent e) {
System.out.println("Play released");
}
public void menuKeyTyped(MenuKeyEvent e) {}
public void menuKeyPressed(MenuKeyEvent e) {}
});
// Attempt with ActionListener
mi2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mi.setVisible(true);
mi2.setVisible(true);
JPanel mp = new JPanel();
JFrame mf = new JFrame("Game");
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mp.add(mi);
mp.add(mi2);
mf.add(mp);
mf.setVisible(true);
}
public static void main(String args[]) {
new Screen();
}
}
I've tried with both ActionListener and MenuKeyListener, with and without the JPanel, changing visibilities... I also tried to use KeyEventDispatcher but I didn't know how to send a KeyEvent to the component that returns KeyboardFocusManager.getFocusOwner().
Please help.
There's a lot to help with in this case. For starters,
public static void main(String args[]) {
new Screen();
}
is wrong. It is not appropriate to perform any operation that alters the Swing layout or presentation on the main thread. Instead do
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Screen();
}
});
}
if you decide that you want to put swing calls into an object's constructor in this way.
Ideally your Screen would be a JFrame but one that is customized to meet your needs. That means you might want to create a new class GamePanel that extends JPanel
public class Screen extends JFrame {
public Screen() {
super("Game"); // to remind us that the JFrame is created
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new GamePanel());
pack();
setVisible(true);
}
}
public class GamePanel extends JPanel {
public GamePanel() {
super();
}
}
Now, if you want that panel to listen to keys, you need to add a KeyListener interface. This only gives it the capability to listen, it doesn't make it listen.
public class GamePanel extends JPanel implements KeyListener {
...
public void keyTyped(KeyEvent e) {
System.out.println("KEY TYPED: " + e);
}
public void keyPressed(KeyEvent e) {
System.out.println("KEY PRESSED: " + e);
}
public void keyReleased(KeyEvent e) {
System.out.println("KEY RELEASED: " + e);
}
}
Now you can add your key listener to the Screen or to the GamePanel (it will listen to itself). Whenever the focus is in one of these items, and a key is pressed, the even will be routed to the listener.
public class GamePanel extends JPanel implements KeyListener {
public GamePanel() {
super();
addKeyListener(this);
}
...
}
Ideally, you might want to not combine your key listener with the panel itself, but make it a "Command Processor" of some sort. In that case, remove the KeyListener code from the JPanel and make a completely new CommmandHandler object that implements KeyListener.
As far as Actions go, they are convenience items that pre-configure menu entries with lots of things (icons, acceleration keys, text, callback functions). If you are avoiding menus for whatever reason, you will find that much of their utility in setting up menus is misdirected for your purpose. Effectively, they are configuration entries that configure the MenuItem objects to handle a key (through the KeyListener interface and then dispatch a swing Event object. This provide "better than key" tracking of items through an application as it converts a keyboard letter k to a class ActionEvent which is passed to the registered "action handler" typically a subclass of AbstractAction.
An example of an Action would be
public class MoveLeft extends AbstractAction { // which extends ActionListener
private final GameState gameState;
public MoveLeft(GameState gameState) {
super("move left", new ImageIcon(MoveLeft.class.getResource("/images/moveleft.png"));
putValue("SHORT_DESCRIPTION", "left");
putValue("MNEMONIC_KEY", "l");
this.gameState = gameState;
}
public void actionPerformed(ActionEvent e) {
gamestate.getSelected().moveLeft();
}
}
Assuming you wanted this convenience, you would initialize your CommandHandler with Actions, maybe like so:
public CommandHandler implements KeyListener {
private int actionId;
...
public void addAction(Action action) {
handlers.put(action.getValue("MNEMONIC_KEY")., action);
}
public void keyTyped(KeyEvent e) {
Action action = handlers.get(String.valueOf(e.getKeyChar());
ActionEvent event = new ActionEvent(this, id, action.getValue("NAME"));
action.actionPerformed( event );
}
}
As you can see, the added convenience of having Actions defined for the actions within your game is a balanced by making your components that use them be configured by them (and using them in the KeyListener implementations).
For large projects, the simplicity of having all your actions listed generally makes creating Actions well worth the effort; but, for smaller projects that are mostly using custom components, the added one-time-cost of making the KeyListener components use actions might outweigh the benefits.
Don't use JMenuItem this way, that's not how it's intended to be used
Instead, I'd start with JButton. The following makes use of your focus transversal code, the Action API and the key bindings API
import java.awt.AWTKeyStroke;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
set.add(KeyStroke.getKeyStroke("DOWN"));
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
set = new HashSet<AWTKeyStroke>(KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
set.add(KeyStroke.getKeyStroke("UP"));
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
Action playAction = new AbstractAction("Play") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("play");
}
};
playAction.putValue(Action.MNEMONIC_KEY, (int)'P');
Action exitAction = new AbstractAction("Exit") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("exit");
}
};
exitAction.putValue(Action.MNEMONIC_KEY, (int)'x');
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "play");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, 0), "exit");
am.put("play", playAction);
am.put("exit", exitAction);
JButton playButton = new JButton(playAction);
JButton exitButton = new JButton(exitAction);
add(playButton, gbc);
add(exitButton, gbc);
}
}
}
Now, you could do something similar with JLabel, but, JLabel isn't focusable by default, nor does it render any kind of focus indication. Instead, I might be tempted to just strip down a JButton so it didn't paint its border or content/background instead
I have noticed that all JOptionPane method "interfere" with ActionListeners.
I need ActionListener to remain active after a JOptionPane has been opened.
For example:
I have a JButton, I register the mouse being pressed and draw the button red. Upon being released, I draw it blue.
If I just click it, the button will turn blue. Ok
If I hold it clicked, the button will stay red. Ok
If I click it and set it to open a JOptionPane dialog, it stays red, even though I have released the mouse. Not Ok
I haven't been able to find any documentation on this specific behaviour, can someone point me in the right direction?
I do really need to use JOptionPane.
One option -- queue the call to open the JOptionPane on the Swing event queue. This will delay the opening of the modal JOptionPane just a little bit, allowing other button actions to be performed.
Another option is to extract the JDialog from the JOptionPane, and call it in a non-modal way.
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestOptionPane extends JPanel {
private static final Color FOREGROUND = Color.RED;
private static final Color PRESSED_FG = Color.BLUE;
private JButton button1 = new JButton(new Button1Action());
private JButton button2 = new JButton(new Button1Action());
public TestOptionPane() {
setPreferredSize(new Dimension(600, 450));
button1.getModel().addChangeListener(new ButtonModelListener(button1));
button1.setForeground(FOREGROUND);
add(button1);
button2.getModel().addChangeListener(new ButtonModelListener(button2));
button2.setForeground(FOREGROUND);
add(button2);
}
private class Button1Action extends AbstractAction {
public Button1Action() {
super("Queue JOptionPane on Swing event thread");
}
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(TestOptionPane.this, "hello");
});
}
}
private class Button2Action extends AbstractAction {
public Button2Action() {
super("Show non-modal JOptionPane");
}
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(() -> {
Component parentComponent = TestOptionPane.this;
JOptionPane optionPane = new JOptionPane("Hello", JOptionPane.PLAIN_MESSAGE);
JDialog dialog = optionPane.createDialog(parentComponent, "Fubars Rule!");
dialog.setModalityType(ModalityType.MODELESS);
dialog.setLocationRelativeTo(parentComponent);
dialog.setVisible(true);
});
}
}
private class ButtonModelListener implements ChangeListener {
private JButton button;
public ButtonModelListener(JButton button) {
this.button = button;
}
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isPressed()) {
button.setForeground(PRESSED_FG);
} else {
button.setForeground(FOREGROUND);
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestOptionPane");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestOptionPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
In my JFrame I have this listener:
this.addKeyListener(new KeyAdapter(){
#Override
public void keyPressed(KeyEvent arg0) {
//do stuff
}
});
This has been working fine until about 10 minutes ago. Now when I press a key, keyPressed() never even gets called. I tested this with eclipse debugger.
I have no idea what happened. Any ideas?
EDIT #1: This is also happening with a button that I have set up. the action listener does not recognize when the button is clicked.
EDIT #2: Ok So I was able to narrow it down. I have a JFrame, this frame has a main panel and also 2 action listeners (keyListener, the problematic one, and a mouse click listener, working fine). The main panel has two subpanels a and b. panel a has 2 buttons, one is not set up yet. It seems that these buttons are somehow conflicting with the keylistener making it so the key listener and buttons do not work. either way the mouse click listener still works.
Edit #3: Ok here is some simplified code:
The button is working, but the keyListener is not. I am hearing about focus a lot, if this is the problem how can I fix it?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ListenerTest extends JFrame {
private JPanel mainPanel;
private JPanel panelA;
private JPanel panelB;
private JButton buttonA;
private JButton buttonB;
public ListenerTest() {
mainPanel = new JPanel();
panelA = new JPanel();
panelB = new JPanel();
buttonA = new JButton("Button A");
buttonB = new JButton("Button B");
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getKeyChar());
}
});
this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + ", " + e.getY());
}
});
buttonA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button A pressed!");
}
});
panelA.add(buttonA);
panelA.add(buttonB);
mainPanel.add(panelA);
mainPanel.add(panelB);
this.add(mainPanel);
this.setSize(300, 300);
this.setVisible(true);
}
public static void main(String args[]) {
new ListenerTest();
}
}
When you add an action for a specific key (for example: F2) to panelA, this seems to work:
public ListenerTest() {
// Create components...
panelA.getActionMap().put("saveAction", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("F2");
}
});
//panelA.getInputMap().put(KeyStroke.getKeyStroke("F2"), "saveAction");
panelA.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke("F2"), "saveAction");
//this.addKeyListener(new KeyAdapter() {
//mainPanel.addKeyListener(new KeyAdapter() {
panelA.addKeyListener(new KeyAdapter() {
//buttonA.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
System.out.println("Panel A: " + arg0.getKeyChar());
}
});
// Rest of the code...
}
Adding the action also seems to have a side effect: the KeyListener seems to work again for panelA. The focus no longer goes to one of the buttons by default.
Note: when using panelA.getInputMap(), the key action only works when the buttons do not have the focus. Use panelA.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) to make sure the action works when one of the buttons has the focus.
I have sticked below listener inside JtextField when action performed event,
so as to perform action against any change made in text box once user make any change.
but the problem is the code not starting or working unless you press enter only then
the code execute the code, i need to know what i have to add and where to enable below code once text Filed changed instantly .I can see some similar help referring to Oracle listener help but am unable to manage so i need direct simple way.
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
JOptionPane.showMessageDialog(null, "Change case");
}
public void insertUpdate(DocumentEvent de) {
JOptionPane.showMessageDialog(null, "Update Case");
}
public void removeUpdate(DocumentEvent de) {
JOptionPane.showMessageDialog(null, "Remove case");
}
});
// TODO add your handling code here:
}
ActionListener for a text field only listens for enter key being typed. So what your code essentialy does is: when enter key is pressed adds a new DocumentListener to the text field.
The DocumentListener is what you want so take that code (adding the document listener) out of the jTextField1ActionPerformed method and put it in the constructor of the class. Or have a private method, so as not to clutter the constructor.
Assuming you are using Netbeans GUI editor (looks like it from your method signature):
public class MyFrame exentds JFrame {
public MyFrame() {
initComponents();
addDocumentListenerToField();
}
private void addDocumentListenerToField() {
jTextField.getDocument().addDocumentListener(..);
}
}
UPDATE: DEMO
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DocListeenerDemo extends JFrame {
private JTextField field;
private JLabel label;
public DocListeenerDemo() {
initComponents();
addDocumentListenerToField();
}
private void initComponents() {
setLayout(new GridLayout(0, 1));
field = new JTextField(20);
label = new JLabel("", SwingConstants.CENTER);
add(field);
add(label);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
private void addDocumentListenerToField() {
field.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent arg0) {doYourStuff();}
public void insertUpdate(DocumentEvent arg0) {doYourStuff();}
public void removeUpdate(DocumentEvent arg0) {doYourStuff();}
public void doYourStuff() {
label.setText(field.getText());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
DocListeenerDemo demo = new DocListeenerDemo();
demo.setVisible(true);
}
});
}
}
I have not figure out a way to add the DocumentListener through the GUI tool. Sucks.
try using actionListener rather than documentListener
I have made an SSCCE. Please note that it must be Windows Look&Feel.
import java.awt.*;
import javax.swing.*;
public class DefaultButtonBug {
private static final String LAF_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(LAF_WINDOWS);
} catch (Exception ex) {
System.out.println("Setting the L&F failed so I cannot reproduce the bug.");
System.exit(1);
}
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JPanel content = new JPanel();
JButton defaultButton = new JButton("Default");
content.add(defaultButton);
JFrame frame = new JFrame();
frame.getRootPane().setDefaultButton(defaultButton);
frame.setContentPane(content);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Launch this
The button should be focused. If not, click it.
Click on any other window, to make sure this current window loses the focus
The button keeps animating in blue tints, even when this window has no focus anymore!
The button 'pulsing' animation is something not present in the standard Java L&F.
Remark that when this button is no longer the default button (remove the appropriate line in the code), the button will be gray after the window loses focus and there is no animation whatsoever.
My question to you is: is this considered a bug? Because this makes the EDT keep doing stuff instead of being idle when the window is hidden behind another window too (I did some profiling). Indeed, that's the stuff that bothers me the most of all: hiding the window does not make the EDT go idle.
getRootPane() default button - Is this a bug?
not as described in a comment by #Guillaume Polet
but I'd be inclined to use KeyBindings, because any JComponents with FocusInWindow and added ActionListener can consume() ENTER key pressed, for all JButtons JComponents
focus is managable by getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT/*.WHEN_FOCUSED*/)
notice (Win OS) JButton has implemented TAB as an accelerator in KeyBindings, too.
from code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DefaultButtonBug {
private static final String LAF_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(LAF_WINDOWS);
} catch (Exception ex) {
System.out.println("Setting the L&F failed so I cannot reproduce the bug.");
System.exit(1);
}
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JPanel content = new JPanel();
JButton focusedButton1 = new JButton("Focused");
focusedButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Focused pressed");
}
});
content.add(focusedButton1);
final JButton defaultButton2 = new JButton("Default");
defaultButton2.setIcon(UIManager.getIcon("OptionPane.informationIcon"));
defaultButton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Default pressed");
}
});
defaultButton2.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover()) {
defaultButton2.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
} else {
defaultButton2.setIcon(UIManager.getIcon("OptionPane.informationIcon"));
}
}
});
content.add(defaultButton2);
JFrame frame = new JFrame();
frame.getRootPane().setDefaultButton(defaultButton2);
frame.getRootPane().getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT/*.WHEN_FOCUSED*/)
.put(KeyStroke.getKeyStroke("ENTER"), "clickButton");
frame.getRootPane().getActionMap().put("clickButton", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
defaultButton2.doClick();
}
});
frame.getRootPane().setDefaultButton(defaultButton2);
frame.setContentPane(content);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
learning item of day
on Win7/8 (Java6/7) are allowed mouse event on un_focused Java Window (for all standard L&F), can be listener from ChangeListener added to ButtonModel
doesn't work on WinXP
focused
un_fosused firing the same events a
EDIT
in Win7 compiled in JDK7_011 flashing JButtons (focused in Java window) with blue Color
flashing with blue color on second period
and