Add key bindings to JButtons that get their actions from action commands? - java

I found a cool way in another question to create a JButton whose actions are written and viewed in an easy way:
public JButton makeToolbarButton(String title, String actionCommand) {
JButton button = new JButton(title);
button.setActionCommand(actionCommand);
button.addActionListener(this);
return button;
}
The class this method is in implements ActionListener, and the buttons commands are assigned by:
public void actionPerformed(ActionEvent e) {
int action = Integer.parseInt(e.getActionCommand());
switch(action) {
case 1:
System.out.println("This button pressed.");
break;
}
}
And the buttons are made by:
JButton button1 = makeToolbarButton("Button 1", "1");
So my question is: can I add KeyStrokes to a button by this method? I tried something like this (inside of the makeToolbarButton method):
button.getInputMap().put(KeyStroke.getKeyStroke("B"), "button_pressed");
button.getActionMap().put("button_pressed", button.getAction());
But I figure this doesn't work because the action command isn't actually assigning an action to a specific button. Is there a way to add something to the makeToolbarButton() method and a parameter for the KeyStroke to accomplish this?

I think you're missing the point of the Action API. A Action is intended to provide a single, self contained, unit of work. This means that the actionCommand really isn't required, as when the actionListener event is triggered, you know exactly the context in which it's been executed
I'd also avoid using KeyStroke.getKeyStroke(String), as the text is a verbose description of what you want to do (ie pressed B or something, but needless to say, it's a pain to get right)
So, the following demonstrates how you might use Actions and assign them to a button AND a key binding
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ActionTest {
public static void main(String[] args) {
new ActionTest();
}
public ActionTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
add(createButton(new ActionOne(), KeyStroke.getKeyStroke(KeyEvent.VK_1, 0)));
add(createButton(new ActionTwo(), KeyStroke.getKeyStroke(KeyEvent.VK_2, 0)));
}
public JButton createButton(Action action, KeyStroke keyStroke) {
JButton btn = new JButton(action);
btn.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "button_pressed");
btn.getActionMap().put("button_pressed", action);
return btn;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
public class ActionOne extends AbstractAction {
public ActionOne() {
putValue(NAME, "1");
putValue(Action.ACTION_COMMAND_KEY, "Action.one");
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
public class ActionTwo extends AbstractAction {
public ActionTwo() {
putValue(NAME, "2");
putValue(Action.ACTION_COMMAND_KEY, "Action.two");
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
}
}
See How to Use Actions for more details

Related

How to check that text was selected in Swing?

I have simple JTextField and KeyListener.
JTextField textField = new JTextField();
textField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
#Override
public void keyReleased(KeyEvent e)
{
validateThatTextWasSelectedWithShiftAndArrow();
}
});
How do I check that someone select text with key combination (SHIFT + LEFT or RIGHT ARROW) ?
Swing makes heavy use of the Key Bindings API to make it easy to work with existing functionality. We already know the JTextField is fully capable of performing selection, we just need to be able to plug into it.
The JTextField uses the selection-backward and selection-forward to execute the required functionality when the system dependent key strokes are activated, we just need to inject our code into it.
For this, I wrote a simple ReplaceAction action, which takes the old Action we are interested, and calls two methods, one before and one after the old Action is called. This allows you to inject your required functionality into whatever point is required to achieve whatever functionality you are trying to implement...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MonitorSelection {
public static void main(String[] args) {
new MonitorSelection();
}
public MonitorSelection() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JTextField field = new JTextField(10);
add(field);
InputMap im = field.getInputMap(WHEN_FOCUSED);
ActionMap am = field.getActionMap();
Action oldAction = am.get("selection-backward");
am.put("selection-backward", new ReplacedAction(oldAction){
#Override
protected void doAfterReplacedAction() {
System.out.println("Before selection-backward");
}
#Override
protected void doBeforeReplacedAction() {
System.out.println("After selection-backward");
}
});
oldAction = am.get("selection-forward");
am.put("selection-forward", new ReplacedAction(oldAction){
#Override
protected void doAfterReplacedAction() {
System.out.println("Before selection-forward");
}
#Override
protected void doBeforeReplacedAction() {
System.out.println("After selection-forward");
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class ReplacedAction extends AbstractAction {
private Action replaced;
public ReplacedAction(Action replaced) {
this.replaced = replaced;
}
#Override
public void actionPerformed(ActionEvent e) {
doBeforeReplacedAction();
replaced.actionPerformed(e);
doAfterReplacedAction();
}
protected void doBeforeReplacedAction() {
}
protected void doAfterReplacedAction() {
}
}
}

Click j/ToggleButton then set Icon/Image

I am making a 4x4 board kinda like minesweeper. Each button has a bomb or another image.
Here's my code:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
this.jToggleButton1.setIcon(new javax.swing.ImageIcon("bombaa.png"));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.jToggleButton1.setIcon(new javax.swing.ImageIcon("bombaa.png"));
}
also tried this way...
private void setIcon1(){
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("bombaa.png")));
}
and call setIcon() in the jButton1ActionPerformed and jButton1MouseClicked BUT this sets my image as the main Icon for the program.
Basically what I need is: Click a button and set the image/icon one time only.
Start by creating your own button, one which you can control the selected state...
public class StickyModel extends JToggleButton.ToggleButtonModel {
public void reset() {
super.setSelected(false);
}
#Override
public void setSelected(boolean b) {
if (!isSelected()) {
super.setSelected(b);
}
}
}
This will prevent the button from becoming "unselected" once it has been set selected (it also includes a reset method which will make it "unselected" for you)
Create your buttons with a "blank" or empty "default" icon and a set the selectedIcon property to what you want shown when the button is selected...
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Blank.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Bomb.png"))));
So, when the button is clicked, it will use the selectedIcon
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
try {
add(createButton());
add(createButton());
add(createButton());
} catch (IOException exp) {
exp.printStackTrace();
}
}
protected JToggleButton createButton() throws IOException {
JToggleButton btn = new JToggleButton();
btn.setModel(new StickyModel());
btn.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Blank.png"))));
btn.setSelectedIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Bomb.png"))));
return btn;
}
}
public class StickyModel extends JToggleButton.ToggleButtonModel {
public void reset() {
super.setSelected(false);
}
#Override
public void setSelected(boolean b) {
if (!isSelected()) {
super.setSelected(b);
}
}
}
}

Why does viewport changelistener get called multiple times

I've got a viewport, and I've attached a change listener to it. Whenever I scroll through my viewport, my change listener gets called about four times. I'm not sure how to avoid this; I only want the call to happen once?
There's no way around this, JViewport will fire several stateChanged events because it's providing notification about changes to a number of properties...
From the JavaDocs...
Adds a ChangeListener to the list that is notified each
time the view's size, position, or the viewport's extent size has
changed.
At this point, it's kind of hard to know what to suggest as we don't know what it is you are trying to achieve, however, if you have to use a ChangeListener, you could set up a coalescing mechanism. That is, rather then responding to each event, you basically wait until a long enough delay has occurred between events before responding to it...
For example...
public class DelayedChangeHandler implements ChangeListener {
private Timer timer;
private ChangeEvent last;
public DelayedChangeHandler() {
timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stableStateChanged();
}
});
timer.setRepeats(false);
}
#Override
public void stateChanged(ChangeEvent e) {
last = e;
timer.restart();
}
protected void stableStateChanged() {
System.out.println("Finally...");
}
}
Basically, this is a ChangeListener implementation that uses a non-repeating javax.swing.Timer with a short delay. Each time stateChanged is called, the timer is restart. Finally, when the timer is allowed to "tick", it calls stableStateChanged indicating that enough time has passed since the last event was raised.
This assumes that you don't so much care about what caused the event, only that the event occured...
A runnable example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestViewport {
public static void main(String[] args) {
new TestViewport();
}
public TestViewport() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(1000, 1000);
}
};
JScrollPane sp = new JScrollPane(pane);
sp.getViewport().addChangeListener(new DelayedChangeHandler());
sp.getViewport().addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(evt.getPropertyName());
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(sp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DelayedChangeHandler implements ChangeListener {
private Timer timer;
private ChangeEvent last;
public DelayedChangeHandler() {
timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stableStateChanged();
}
});
timer.setRepeats(false);
}
#Override
public void stateChanged(ChangeEvent e) {
last = e;
timer.restart();
}
protected void stableStateChanged() {
System.out.println("Finally...");
}
}
}
You can try to use AdjustmentListener for gettign scroll event once, try next:
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.UnsupportedEncodingException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Example {
public static void main(String[] args) throws UnsupportedEncodingException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane pane = new JScrollPane(new JTextArea());
pane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if(e.getValueIsAdjusting()){
return;
}
System.out.println("vertical scrolled");
System.out.println("bar value = " + e.getValue());
}
});
frame.setContentPane(pane);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Here is another example.

JApplet can't get focus when run from browser

I have some simple code where I'm trying to get keyboard events into a Java applet. The code runs just fine when being run with appletviewer, but when I'm loading it from a browser (tried both Chrome and Firefox), the JApplet won't get focus on click.
Trying exactly the same code with Applet instead of JApplet works without a problem.
Here's my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
String s = "";
public void init() {
setFocusable(true);
setEnabled(true);
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
s = "KEY PRESSED: " + e.getKeyCode();
repaint();
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
boolean ret = requestFocusInWindow();
s = "requestFocusInWindow: " + ret;
repaint();
}
});
requestFocusInWindow();
}
public void start() {
requestFocusInWindow();
}
public void paint(Graphics g) {
super.paint(g);
requestFocusInWindow();
g.setColor(Color.BLACK);
s = "Focus owner: " + isFocusOwner() + ", " + s;
g.drawString(s, 24, 24);
}
}
Applets should be created on Event Dispatch Thread by wrapping code in overridden init() method in SwingUtilities.invokeAndWait() block
Dont use KeyListener for JApplet/Swing components use KeyBindings
call requestFocusInWindow() on JApplet after creating and adding all content to container (this is not necessary with keybindings though)
Also dont do drawing in paint() rather add JPanel to container and override paintComponent(..)
Here is a small example, its a simple JLabel with a dummy label and textfield added to the container with a KeyBinding for A only; so when A is pressed it will be added to JLabel text:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.AbstractAction;
import javax.swing.JApplet;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Test extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
final JLabel label = new JLabel("Text:");
final JLabel label2 = new JLabel("Dummy label");
final JTextField jtf = new JTextField("Dummy Field");
label2.setFocusable(true);
label.setFocusable(true);
//allwos user to add letter A to JLabel
label.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "A");
label.getActionMap().put("A", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
String tmp = label.getText();
label.setText(tmp + "A");
}
});
setLayout(new GridLayout(3, 1));
add(label);
add(label2);
add(jtf);
}
});
} catch (InterruptedException | InvocationTargetException ex) {
ex.printStackTrace();
}
}
}

JLabel mouse click on icon or text

When it is clicked on JLabel, I want to understand if the click was on "Icon part", or "Text part" of the JLabel, so that different action can be taken. Is there a clever way to do that? Or just I have to solve it relatively with the coordinates of the icon and text?
+1 to #aymeric comment.
What about having two different JLabels
However I do understand why you might be hesitating
negative: requires maintenance of 2 labels.
My clever (:P) solution to this is create your own abstract component - which accepts icon and text as parameters for constructor - by extending JPanel and than adding 2 JLabels to the JPanel, each label has its on MouseAdapter which calls abstract method xxxClicked() (thus any implementing class must override these methods).
Here is an example I made:
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon ii = null;
try {
//I dont remmend getScaledInstance just used it for speed of code writing
ii = new ImageIcon(ImageIO.read(new URL("http://www.candonetworking.com/java.gif")).getScaledInstance(32, 32, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
MyLabel ml = new MyLabel(ii, "Something") {
#Override
void iconClicked() {
System.out.println("Icon clicked");
}
#Override
void textClicked() {
System.out.println("Text clicked");
}
};
frame.add(ml);
frame.pack();
frame.setVisible(true);
}
});
}
}
abstract class MyLabel extends JPanel {
JLabel iconLabel;
JLabel textLabel;
MouseAdapter iconMA;
MouseAdapter textMA;
public MyLabel(ImageIcon icon, String text) {
iconLabel = new JLabel(icon);
textLabel = new JLabel(text);
iconMA = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
iconClicked();
}
};
textMA = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
textClicked();
}
};
iconLabel.addMouseListener(iconMA);
textLabel.addMouseListener(textMA);
add(iconLabel);
add(textLabel);
}
abstract void iconClicked();
abstract void textClicked();
public JLabel getIconLabel() {
return iconLabel;
}
public JLabel getTextLabel() {
return textLabel;
}
}

Categories

Resources