I'm trying to make a key make something happen in a JFrame. Right now I'm just trying to disable a button when you press the left key, but nothing is happening. I thought I have everything right, but it does nothing.
EDIT: I noticed that when I don't click start first, it works. But after you press start, it won't respond.
Here's my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener, KeyListener
{
private static final long serialVersionUID = 1L;
private JPanel p1;
private JButton b1, b2;
private JLabel lb1;
private int a;
private Font font = new Font("Arial", Font.BOLD, 20);
public MyFrame()
{
setLayout(new FlowLayout());
setSize(700,600);
setVisible(true);
setResizable(false);
addKeyListener(this);
setFocusable(true);
p1 = new JPanel(); add(p1);
p1.setBackground(Color.BLACK);
p1.setPreferredSize(new Dimension(650,500));
p1.setFocusable(true);
b1 = new JButton("Start"); add(b1);
b1.addActionListener(this);
b2 = new JButton("Test"); add(b2);
b2.setFocusable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
Graphics g = p1.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(30, 210, 10, 70);
g.fillRect(620, 210, 10, 70);
for(int i=0; i<7; i++)
{
g.fillRect(325, a, 10, 70);
a += 90;
}
g.setFont(font);
g.drawString("Player 1: ", 120, 20);
g.drawString("Player 2: ", 450, 20);
}
public void keyPressed(KeyEvent e)
{
int d = e.getKeyCode();
if(d==KeyEvent.VK_LEFT)
{
b2.setEnabled(false);
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
And here's my Main.java file:
public class Main {
public static void main(String[] arg)
{
MyFrame mf = new MyFrame();
}
}
KeyListener has a lot of problems, with regards to focus (among other things). With Swing, it is preferred to use Key Bindings, which gives us more control over the focus options. There are different InputMaps for WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_IN_FOCUSED_WINDOW. Their names are almost self documenting. So if we were to do
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
then we are getting the InputMap for when the frame is focused. We would then bind a KeyStroke with an Action to that InputMap and the component's ActionMap. For example
JPanel panel = (JPanel)frame.getContentPane();
InputMap imap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
imap.put(KeyStroke.getKeyStroke("LEFT"), "leftAction");
ActionMap amap = panel.getActionMap();
Action leftAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
doSomethingWhenLeftIsPressed();
}
};
amap.put("leftAction", leftAction);
Resources
How to use Actions
How to Use Key Bindings
You forgot to tell the JFrame that it should be listening for keys with this line of code:addKeyListener(this);
Related
This question already has answers here:
Keylistener not working for JPanel
(4 answers)
KeyListener not working in JPanel?
(1 answer)
How to use Key Bindings instead of Key Listeners
(4 answers)
Closed 1 year ago.
In my game, I want the player to be able to press ESC and activate a menu. In this menu, they would be able to return to the home screen. I have tried to use .addKeyListener() as you will see below. I have tried using event.getKeyCode() == 27 and event.getKeyCode() == KeyEvent.VK_ESCAPE, but it doesn't seem to change the outcome(JFrame not registering "ESC" being pressed.
Is there a bug in my code? Or am I just missing something blatant..
Code(refer to this if you have an answer):
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class Main {
static JFrame jframe = new JFrame();
static JLabel startingTitle = new JLabel("Welcome!");
static JPanel aiPanel = new JPanel();
static Font buttonFont = new Font("MineCrafter", Font.BOLD, 20);
static JFrame gameScreen = new JFrame();
static JFrame onevoneScreen = new JFrame();
static JFrame escScreen = new JFrame();
static JPanel onevonePanel = new JPanel();
static JFrame aiScreen = new JFrame();
static JPanel title = new JPanel();
static JButton onevone = new JButton("Multiplayer");
static JButton aifight = new JButton("Singleplayer");
static JButton BackToStart = new JButton("Back");
public Main(){
Font myFont = new Font("Serif", Font.BOLD, 30);
startingTitle.setFont(myFont);
startingTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
onevone.setAlignmentX(Component.CENTER_ALIGNMENT);
aifight.setAlignmentX(Component.CENTER_ALIGNMENT);
title.setLayout(new BoxLayout(title, BoxLayout.Y_AXIS));
title.add(Box.createRigidArea(new Dimension(0, 50)));
title.add(startingTitle);
title.add(Box.createRigidArea(new Dimension(0, 50)));
title.add(aifight);
title.add(Box.createRigidArea(new Dimension(0, 25)));
title.addKeyListener(new MKeyListener());
title.add(onevone);
gameScreen.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
gameScreen.setLocationRelativeTo(null);
gameScreen.setExtendedState(JFrame.MAXIMIZED_BOTH);
gameScreen.add(title);
gameScreen.pack();
}
static void setEscScreen(boolean on){
escScreen.setVisible(on);
}
public static void main(String[] argv) throws Exception {
SwingUtilities.invokeLater(Main::new);
BackToStart.setFont(buttonFont);
BackToStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
aiPanel.setVisible(false);
onevonePanel.setVisible(false);
title.setVisible(true);
gameScreen.add(title);
}
});
JButton startGame = new JButton("Launch");
startGame.setFont(buttonFont);
startGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Started");
jframe.setVisible(false);
gameScreen.setVisible(true);
title.setVisible(true);
}
});
// Creates starting screen
onevone.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Activate 1v1");
title.setVisible(false);
onevonePanel.setVisible(true);
gameScreen.add(onevonePanel);
}
});
aifight.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Activate AI");
title.setVisible(false);
aiPanel.setVisible(true);
gameScreen.add(aiPanel);
}
});
// Creates onevoneScreen
JLabel onevoneTitle = new JLabel("1v1[In Progress]");
onevonePanel.add(onevoneTitle);
onevonePanel.addKeyListener(new MKeyListener());
// Creates aiScreen
JLabel aiTitle = new JLabel("ai[In Progress]");
aiPanel.add(aiTitle);
aiPanel.addKeyListener(new MKeyListener());
//Creates escScreen
escScreen.setLayout(new GridBagLayout());
escScreen.add(BackToStart, new GridBagConstraints());
escScreen.getContentPane().setBackground(new Color(211, 211, 211));
escScreen.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
escScreen.setLocationRelativeTo(null);
escScreen.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Creates launch screen
jframe.setLayout( new GridBagLayout() );
jframe.add(startGame, new GridBagConstraints());
jframe.setSize(400, 350);
jframe.setVisible(true);
}
}
class MKeyListener extends KeyAdapter {
static boolean escapedOn = false;
public void keyPressed(KeyEvent event) {
char ch = event.getKeyChar();
int e = event.getKeyCode();
if (e == KeyEvent.VK_ESCAPE){
if (escapedOn == true){
System.out.println("escaped off");
Main.setEscScreen(false);
escapedOn = false;
} else if (escapedOn == false){
System.out.println("escaped on");
Main.setEscScreen(true);
escapedOn = true;
}
}
}
}
Another question that I would like to be answered(but doesn't have to be answered): Can I make the menu JFrame slightly transparent(so that you can see the game in the background)? If I can, can you implement it in the answer too?
I'm not sure why my JButton is not displaying when I add it to the JPanel class: if my class extends JPanel, shouldn't this.add be sufficient? And if I remove this Jpanel class from another Jpanel, the components attached to this panel should disappear as well right? Thank you!
public class Menu extends JPanel{
private static final long serialVersionUID = 1L;
static boolean startGame = false;
public static String user;
public Menu(final JFrame frame) {
JPanel userName = new JPanel(); // create new JPanel
final JTextField text = new JTextField();
text.setText("input your username here");
//adds userName input box to the panel
Action action = new AbstractAction(){
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
user = text.getText();
text.setVisible(false);
Menu.startGame = true;
}};
text.addActionListener(action);
userName.add(text);
frame.add(userName, BorderLayout.SOUTH);
frame.revalidate();
frame.repaint();
setFocusable(true);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
sndMenu newMenu = new sndMenu(frame);
newMenu.setVisible(true);
}
});
/**
* this does not display help!
*/
//add a button to the menu called "help"
JButton help = new JButton("get instructions");
this.add(help,BorderLayout.CENTER);
help.setVisible(true);
help.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
instructions instr = new instructions(frame);
frame.add(instr);
frame.revalidate();
frame.repaint();
}
});
}
public void paint (Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
Font fnt0 = new Font("Manaspace", Font.BOLD, 40);
Font fnt1 = new Font("Manaspace", Font.BOLD, 30);
g.setFont(fnt0);
g.setColor(Color.white);
g.drawString("Welcome To Jumping Box!", 120, 300);
g.setFont(fnt1);
g.drawString("Click to play!", 260, 400);
}
}
I'm developing a game and I have a JFrame that receives in input the player name in a JTextField.
What I want is the possibility to close the window by either pressing a JButton or by pressing the ENTER key.
When the window opens the JTextField must have the focus (the cursor should appear in the component).
I already saw:
How do you make key bindings for a java.awt.Frame?
How do you make key binding for a JFrame no matter what JComponent is in focus?
but I have not solved the problem, there's probably something wrong in the focus management.
I tried the following code:
public class PlayerNameWindow extends JFrame implements KeyListener {
private String playerName;
private JLabel backgroundLabel;
private JLabel enterNameLabel;
private JButton confirmButton;
private JTextField nameField;
private Image background;
public PlayerNameWindow() {
initComponents();
}
private void initComponents() {
backgroundLabel = new JLabel();
enterNameLabel = new JLabel();
confirmButton = new JButton();
nameField = new JTextField();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 200));
setResizable(false);
getContentPane().setLayout(null);
addKeyListener(this);
enterNameLabel.setFont(new Font("Tahoma", 1, 18));
enterNameLabel.setForeground(new Color(255, 255, 255));
enterNameLabel.setText("Enter your name:");
getContentPane().add(enterNameLabel);
enterNameLabel.setBounds(40, 80, 160, 30);
confirmButton.setText("Confirm");
confirmButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
confirmButtonMouseClicked(evt);
}
});
confirmButton.setBounds(160, 150, 90, 25);
getContentPane().add(confirmButton);
getContentPane().add(nameField);
nameField.setBounds(220, 80, 140, 30);
getContentPane().add(backgroundLabel);
backgroundLabel.setBounds(0, 0, 400, 200);
pack();
setLocationRelativeTo(null);
}
private void confirmButtonMouseClicked(MouseEvent evt) {
confirmAction();
}
private void confirmAction() {
playerName = nameField.getText();
System.exit(0);
}
public String getPlayerName() {
return this.playerName;
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER)
System.exit(0);
}
public void keyReleased(KeyEvent e) {
//do-nothing
}
public void keyTyped(KeyEvent e) {
//do-nothing
}
}
How can I do?
Thanks
add keyListener to the JTextField. in your code, nameField.addKeyListener(this);
I've just recently started learning how to use swing, and have been following a tutorial I found online. I've basically followed the tutorial "word for word" but I get the error:
ScoreBoard is not abstract and does not override abstract method
actionPerformed(ActionEvent) in ActionListener
So my question is, how can I implement ActionListener into my class (ScoreBoard) if the class is not abstract?
Here is the entire code: (Because I have no idea where the problem could be)
package scoreboard;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ScoreBoard implements ActionListener{
//Class Variables
int redScore = 0;
int blueScore = 0;
//Class Objects
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel, redLabelT, blueLabelT;
JButton redButton, blueButton, resetButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createFrame();
}
});
}//End Method
public static void createFrame(){
JFrame frame = new JFrame("ScoreBoard");
JFrame.setDefaultLookAndFeelDecorated(true);
ScoreBoard panel = new ScoreBoard();
frame.setContentPane(panel.contentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(250, 190);
frame.setVisible(true);
}//End Method
public JPanel contentPane(){
JPanel basePanel = new JPanel();
basePanel.setLayout(null);
basePanel.setBackground(Color.black);
//Title
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setOpaque(false);
titlePanel.setLocation(10, 0);
titlePanel.setSize(250, 30);
basePanel.add(titlePanel);
redLabelT = new JLabel("Red Team");
redLabelT.setLocation(0, 0);
redLabelT.setSize(100, 30);
redLabelT.setForeground(Color.red);
redLabelT.setHorizontalAlignment(0);
titlePanel.add(redLabelT);
blueLabelT = new JLabel("Blue Team");
blueLabelT.setLocation(120, 0);
blueLabelT.setSize(100, 30);
blueLabelT.setForeground(Color.blue);
blueLabelT.setHorizontalAlignment(0);
titlePanel.add(blueLabelT);
//Score
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setOpaque(false);
scorePanel.setLocation(10, 40);
scorePanel.setSize(250, 30);
basePanel.add(scorePanel);
redLabel = new JLabel("" + redScore);
redLabel.setLocation(0, 0);
redLabel.setSize(100, 30);
redLabel.setForeground(Color.white);
redLabel.setHorizontalAlignment(0);
scorePanel.add(redLabel);
blueLabel = new JLabel("" + blueScore);
blueLabel.setLocation(120, 0);
blueLabel.setSize(100, 30);
blueLabel.setForeground(Color.white);
blueLabel.setHorizontalAlignment(0);
scorePanel.add(blueLabel);
//Buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setOpaque(false);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(250, 70);
basePanel.add(buttonPanel);
redButton = new JButton("Red Score");
redButton.setLocation(0, 0);
redButton.setSize(100, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score");
blueButton.setLocation(120, 0);
blueButton.setSize(100, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
resetButton = new JButton("Reset");
resetButton.setLocation(0, 40);
resetButton.setSize(220, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
return basePanel;
}//End Method
public void actions(ActionEvent e){
if(e.getSource() == redButton){
redScore ++;
redLabel.setText("" + redScore);
}else if(e.getSource() == blueButton){
blueScore++;
blueLabel.setText("" + blueScore);
}else if(e.getSource() == resetButton){
redScore = 0;
blueScore = 0;
redLabel.setText("" + redScore);
blueLabel.setText("" + blueScore);
}
}//End Method
}//End Class
Also if you can explain what an Abstract class is, that'd help too, but really I just need to know how to get JButtons working for now...
Thanks!
The compiler is complaining because your class is not abstract but it does not implement one or more methods that it is declared to implement (specifically the method actionPerformed of ActionListener). I think you simply need to rename your actions method:
public void actions(ActionEvent e){. . .
public void actionPerformed(ActionEvent e){. . .
Put this method into your ScoreBoard class-
#Override
public void actionPerformed(ActionEvent ae) {
// do something
}
You can also add listener in this way, if you don't want ScoreBoard class to implement ActionListener-
redButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
// do something
}
};
If you want to share the listener, create its instance and add it to all the buttons.
To learn about abstract classes, read this http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
you need to check whether all abstract methods of ActionListener are implemented.
you are missing defination of void actionPerformed(ActionEvent e)
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("");
}
}
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
}
}
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);
}
});
}
}
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.
learn all about listeners and more specific key listeners
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.
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
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)