Cor Wopereis
Cor Wopereis

Reputation: 9

activate event with a keypress

I am trying to find a sulotion to translate the void keypressed from c# to java without any succes yet anyone a sulotion?

I want when i press the key 13(enter) that Private void doen() activates once.

import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.*;
import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;

public class Paneel extends JPanel {

    private static final long serialVersionUID = 1L;
    String text;
    String AccountName = "default";
    String autosavecheck = "";
    String iss;
    JProgressBar monsterbar, progressbar;
    JButton sendknop, clearknop, creditsknop, saveknop, loadknop, restartknop,
            disableautosaveknop;
    JTextArea commandstextbox, dialoogtextbox;
    JTextField naamtextbox, invoertextbox;
    JOptionPane resetdialog;
    Toolkit toolkit;
    Timer timer;

    public Paneel() {

        setLayout(null);
// --------------------------------
        dialoogtextbox = new JTextArea();
        dialoogtextbox.setFont(new Font("sansserif", Font.BOLD, 12));
        dialoogtextbox.setBounds(12, 12, 838, 207);
        dialoogtextbox.list();

        invoertextbox = new JTextField(12);
        invoertextbox.setBounds(12, 330, 982, 20);
        invoertextbox.setEnabled(false);
        commandstextbox = new JTextArea();
        commandstextbox.setBounds(856, 28, 138, 191);
        naamtextbox = new JTextField(12);
        naamtextbox.setBounds(772, 263, 220, 20);

        toolkit = Toolkit.getDefaultToolkit();
        timer1 = new Timer();
        toolkit = Toolkit.getDefaultToolkit();
        autosave = new Timer();
        toolkit = Toolkit.getDefaultToolkit();
        monstertimer = new Timer();
        toolkit = Toolkit.getDefaultToolkit();
        autodisabletimer = new Timer();

        sendknop = new JButton("Send");
        sendknop.setBounds(12, 260, 75, 23);
        sendknop.addActionListener(new sendknopHandler());

        add(sendknop);
    }

    private void keypressed() {
        if (e.KeyChar == (char) Keys.Return) {
            doen();
        }
    }

    private void doen() {
        text = invoertextbox.getText();
        invoertextbox.setText("");
    }
}

Upvotes: 0

Views: 3850

Answers (7)

mKorbel
mKorbel

Reputation: 109815

a) public Paneel() { missing } after code line add(sendknop);, the same issue is with public class Paneel extends JPanel {,

b) from this code and in this form you'll never listening any event because code isn't runnable, your question is about Java Basic, not about Swing GUI, nor about listener

c) for listening of ENTER key you have to add ActionListener to the JButton

d) for Swing GUI have to use Swing Timer instead of util.Timer, otherwise you have an issue with Concurency in Swing

e) for Swing GUI don't to use KeyListener, there is KeyBindings and with output to the Swing Action

f) otherwise Swing JComponents have got Focus in the Window for KeyListener

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347194

As you can, there are a number of approaches you could try. You didn't really specify on which component you were interested in monitoring, so we've thrown a few different suggestions at you...

In the following example of demonstrated key bindings and the default button of the RootPane.

Unfortunately, the JTextArea consumes the enter key before the root pane is notified, meaning that it won't fire. This is a general issue with text fields as they respond to the enter key action.

The other problem you will face is the fact that I've overridden the default behavior of the JtextField's enter key, meaning it will no longer insert new lines.

public class TestPane extends JPanel {

    private JTextArea textArea;
    private JButton doneButton;

    public TestPane() {

        textArea = new JTextArea(10, 50);
        doneButton = new JButton("Done");

        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(4, 4, 4, 4);

        add(new JScrollPane(textArea), gbc);

        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.insets = new Insets(4, 4, 4, 4);

        add(doneButton, gbc);

        InputMap inputMap = textArea.getInputMap(JComponent.WHEN_FOCUSED);
        ActionMap actionMap = textArea.getActionMap();

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
        actionMap.put("enter", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {

                System.out.println("I'm done here");

            }
        });

        doneButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("All the way out...");
            }
        });

    }

    @Override
    public void addNotify() {

        super.addNotify();

        // This is the button that will be activate by "default", depending on
        // what that means for the individual platforms...
        SwingUtilities.getRootPane(this).setDefaultButton(doneButton);

    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {

                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception exp) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(400, 400);
                frame.setLocationRelativeTo(null);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.setVisible(true);

            }
        });

    }

}

Upvotes: 2

David Kroukamp
David Kroukamp

Reputation: 36423

Well if you want to call the method once a JButton is pressed you'd have to add an ActionListener to the JButton and call the method from within the actionPerformed(ActionEvent ae) like this:

jBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("called");
        //call method here
    }
    });

or if you want to call the method once a key is pressed on the JPanel use KeyBindings instead of a KeyListener like so:

JPanel panel=...;
...    

panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "send");
panel.getActionMap().put("send", new MyAction());

...

class MyAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
    System.out.println("called");
    //call method here
}

}

Upvotes: 2

toe
toe

Reputation: 121

Add a key listener to your invoertextbox by adding the following lines to the initialization part of your code:

invoertextbox.addKeyListener(this);

Then extend your class implement the KeyListener interface by adding:

import java.awt.event.KeyListener;

public class Paneel extends JPanel implements KeyListener {

And implement the following methods of the interface within your Paneel class:

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
  if (e.getKeyCode()==KeyEvent.VK_ENTER) {
    doen();
  }
}

@Override
public void keyReleased(KeyEvent e) {
}

private void doen() {
  text = invoertextbox.getText();
  invoertextbox.setText("");
}

Consider using keyTyped(KeyEvent) instead of keyPressed(KeyEvent).

"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered, and are the preferred way to find out about character input. In the simplest case, a key typed event is produced by a single key press (e.g., 'a') […] (JavaDoc for KeyEvent)

Upvotes: 0

Pim_D
Pim_D

Reputation: 89

Is "key 13" a button or is it when user types "13"?

if it's a button, just use

button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                           your statements;
                    }
}

otherwise use the key listener Peter responded.

Upvotes: 1

Peter
Peter

Reputation: 5798

learn all about listeners and more specific key listeners

Upvotes: 1

csvan
csvan

Reputation: 9454

First: get your formatting right, see the instructions for inserting code snippets. Helps those of us who read it :)

I am not entirely sure what you are asking here, but I guess you are trying to get your program to respond to a user clicking any of your buttons. This takes place in the various ActionListeners you should have for buttons. For example, in your case, the sendknopHandler should contain the logic to handle what happens when a user presses this specific button. Inside this class, you will have to filter out the source of the action (i.e. the button pressed), what the action is, and how you want to respond.

Upvotes: 1

Related Questions