How to make Enter key and Submit button have same ActionEvent? - java

So I have a Submit button with an ActionEvent that consists of around 50 lines of code. How would I assign the exact same ActionEvent for the JFrame as the Submit button whenever it detects the Enter key being pressed? This is what my Submit button's ActionEvent looks like
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// miscellaneous code that needs to be repeated for 'Enter' key press
}
});
What and where would the code for giving the JFrame the same ActionEvent as the Submit button go?

Start by taking a look at How to Use Root Panes and in particular JRootPane#setDefaultButton
When you have components which may consume the Enter key (like text fields), you might need to consider using the key bindings API
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter.pressed");
am.put("Enter.pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
btnSubmit.doClick();
}
});
Now, about now, I might consider making an Action which be applied to both the JButton and key binding
Have a look at How to Use Key Bindings and How to Use Actions for more details

I don't know if there's a more correct swing way, but this should do the trick:
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
}
btnSubmit.addActionListener(listener);
btnEnter.addActionListener(listener);

One way to do this is to use the .doClick() method on the Submit button and create a KeyAdapter:
KeyAdapter Enter = new KeyAdapter(){
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
btnSubmit.doClick();
}
}
};
txtField1.addKeyListener(Enter);
txtField2.addKeyListener(Enter);

Related

How to disable F10 default action in window (show window menu)?

The default action of F10 is to show the menu of the window.
However, I would like to disable this feature.
UPDATED:
Background: I would like to implement a special behavior in a JTextField if the user presses any key. Unfortunately, the JTextField don't get the event when F10 is pressed because it is catched by the window (and the menu is shown).
Does anyone know how to disable this key binding in the window?
I tried to disable it in the root pane but without success:
frame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "none");
I searched a lot but found no solution for this issue. Maybe one of you knows an answer.
UPDATE2
Here a code example to reproduce this behavior:
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
final JTextField edit = new JTextField();
edit.setEditable(false);
edit.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(final KeyEvent ke) {
edit.setText(KeyEvent.getKeyText(ke.getKeyCode()));
}
});
final JFrame frame = new JFrame("DEMO");
frame.setSize(320, 240);
frame.getContentPane().add(edit);
frame.setVisible(true);
}
});
}
Plase note: There is a different behavior according to whether "setDefaultLookAndFeelDecorated" is set to true or false.
Thanks in advance :)
I tried to disable it in the root pane but without success:
Check out Key Bindings for the bindings of all Swing components.
You will see that the F10 key is bound to the JMenuBar. So you should be able to use:
menuBar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "none");
Edit:
Missed the point that you didn't have a menu bar.
It appears you can't just set the binding to "none". Looks like Swing is still searching up the tree to find an Action to execute. You need to provide a dummy Action that does nothing:
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("do nothing");
}
};
JPanel content = (JPanel)frame.getContentPane();
String key = "F10";
KeyStroke f10 = KeyStroke.getKeyStroke( key );
frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(f10, key);
frame.getRootPane().getActionMap().put(key, action);
If I did undertand you correctly , Create Keypressed event for your JTextField on netbeans put to following code
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
// Add below
int key = evt.getKeyCode();
if (evt.getSource() == jTextField1)
{
if (key == KeyEvent.VK_F10)
{
// your actions here
System.out.println("Hello I am f10");
}
}
// end of if
}

Disable a Key Entirely Temporarily with Corresponding Button Java

I have a program that, put in short, advances upon the pressing of a button. During certain execution phases the button is temporarily deactivated to prevent it from firing in code at the wrong point in time. I have now created some Key Bindings to act as shortcuts for the pressing of the buttons, but need to disable them during the same aforementioned times, or else they will cause my array to be trashed and wiped before I even use it.
Any tips, methods, or Java methods I can use to [very] easily but a hold via disablement?
Have the bound key press the JButton with doClick(). Then when the button needs to be deactivated, call setEnabled(false) on the button.
As an aside, I suppose your button and key binding could share the same action, but I don't know if calling setEnabled(false) on the Action will prevent the key from running the Action's actionPerformed method. Time to test.... Be right back...
Edit: yep you can just have the JButton and the bound key share the same Action that is enabled/disabled:
import java.awt.event.*;
import javax.swing.*;
public class TestBoundAbstractActions {
public static void main(String[] args) {
final MyAction myAction = new MyAction();
final JButton actionButton = new JButton(myAction);
JRadioButton enableRadioButton = new JRadioButton("Enabled", true);
enableRadioButton.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
myAction.setEnabled(e.getStateChange() == ItemEvent.SELECTED);
}
});
JPanel panel = new JPanel();
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
String mKey = "m key";
panel.getInputMap(condition).put(KeyStroke.getKeyStroke(KeyEvent.VK_M, 0), mKey);
panel.getActionMap().put(mKey, myAction);
panel.add(new JLabel("Press \"m\" to activate key-bound action"));
panel.add(actionButton);
panel.add(enableRadioButton);
JOptionPane.showMessageDialog(null, panel);
}
}
class MyAction extends AbstractAction {
public MyAction() {
super("My Action");
putValue(MNEMONIC_KEY, KeyEvent.VK_M);
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("boo!");
}
}

Return the choice from an array of buttons

I've got an array that creates buttons from A-Z, but I want to use it in a
Method where it returns the button pressed.
this is my original code for the buttons:
String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].setActionCommand(b[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
JOptionPane.showMessageDialog(null, "You have clicked: "+choice);
}
});
panel.add(buttons[i]);
}
I wasn't sure exactly what you question was, so I have a few answers:
If you want to pull the button creation into a method - see the getButton method in the example
If you want to access the actual button when it's clicked, you can do that by using the ActionEvent.getSource() method (not shown) or by marking the button as final during declaration (shown in example). From there you can do anything you want with the button.
If you question is "How can I create a method which takes in a array of letters and returns to me the last clicked button", you should modify you question to explicitly say that. I didn't answer that here because unless you have a very special situation, it's probably not a good approach to the problem you're working on. You could explain why you need to do that, and we can suggest a better alternative.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempProject extends Box{
/** Label to update with currently pressed keys */
JLabel output = new JLabel();
public TempProject(){
super(BoxLayout.Y_AXIS);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
add(button);
}
}
public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have clicked: "+text);
//If you want to do something with the button:
button.setText("Clicked"); // (can access button because it's marked as final)
}
});
return button;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new TempProject());
frame.pack();
frame.setVisible(true);
new TempProject();
}
});
}
}
ActionListener can return (every Listeners in Swing) Object that representing JButton
from this JButton you can to determine, getActionCommand() or getText()
I'm not sure what exactly you want, but what about storing the keys in a queue (e.g. a Deque<String>) and any method that needs to poll the buttons that have been pressed queries that queue. This way you would also get the order of button presses.
Alternatively, you could register other action listeners on each button (or a central one that dispatches the events) that receive the events in the moment they are fired. I'd probably prefer this approach, but it depends on your exact requirements.
try change in Action listener to this
JOptionPane.showMessageDialog(null, "You have clicked: "+((JButton)e.getSource()).getText());
1. First when you will be creating the button, please set the text on them from A to Z.
2. Now when your GUI is all ready, and you click the button, extract the text on the button, and then display the message that you have clicked this button.
Eg:
I am showing you, how you gonna extract the name of the button pressed, i am using the getText() method
butt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "You have clicked: "+butt.getText());
}
});

Swing: detect Enter in JComboBox?

I've tried using getInputMap() + getActionMap() on a JComboBox and it seems to have no effect.
I've tried addActionListener() / addItemListener() on a JComboBox and I can't seem to distinguish a change of selection from someone pressing the Return/Enter key.
Any suggestions? In my application, I want the Return/Enter key to be stronger than just selecting, it's a selecting + applying action.
Here's my code to setup the key binding. It works fine (e.g. note("hit ENTER") is called) when component is a JList, but doesn't work when component is a JComboBox.
private void setupApplyProfile(final JComponent component, final MyComboBoxModel mcbm)
{
String enterAction = "applyItem";
KeyStroke enterKey = KeyStroke.getKeyStroke("ENTER");
component.getInputMap().put(enterKey, enterAction);
component.getActionMap().put(enterAction, new AbstractAction()
{
#Override public void actionPerformed(ActionEvent e) {
note("hit ENTER");
applySelectedProfile(mcbm);
}
});
}
Aha, this seems to work: note("cb editor action") gets called when I hit Enter in the combo box field.
comboBox.getEditor().addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent arg0) {
note("cb editor action");
}
});
In my application, I want the Return/Enter key to be stronger than just selecting, it's a selecting + applying action.
If I understand the question you can use the following:
comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
The ActionEvent and ItemEvents will only be fired when an item is selected from the drop down list when you use the mouse or the enter key. The eEvents will not be fired if you navigate the drop down list using the up/down arrow keys.

Java set focus on JButton when pressing enter

How can I make it so that when I press enter in a JTextField it activates a specific JButton? What I mean is something along the lines of a web page form where you can press enter to activate the button in the form.
You should use an Action for the JButton:
Action sendAction = new AbstractAction("Send") {
public void actionPerformed(ActionEvent e) {
// do something
}
};
JButton button = new JButton(sendAction);
Then you can set the same action for a JTextField or even on a MenuItem if you want the same action to be available in the Menu:
JTextField textField = new JTextField();
textField.setAction(sendAction);
Something like this should work:
textField.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
button.requestFocusInWindow();
}
});
You can achieve this by adding the default behavior to the button, like this
cmdLogin.setDefaultCapable(true); // by default, this is true
this.getRootPane().setDefaultButton(cmdLogin); // here `this` is your parent container
I'd do something like the following:
textField.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
button.doClick();
}
}
});
}

Categories