I don't know how to use KeyEvent.
If you execute the code below,
enableEvents (long) will be accessed protected by Component
said the error.
I think it's a basic question, but I couldn't find it when I searched for it, so I asked.
How should I describe it?Please give me your wisdom...
public class Sample
{
public static void main(String[]args) {
javax.swing.JFrame.enableEvents(java.awt.AWTEvent.KEY_EVENT_MASK);
}
protected void processKeyEvent(java.awt.event.KeyEvent){
System.out.println("key pressed");
}
}
The KeyEvent
adds KeyListener to the component, where it is most likely used.
For more information, the tutorial How to Write a Key Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listens) will help.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public classKeyEventTest{
public static void main(String[]args) {
EventQueue.invokeLater(()->{
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.addKeyListener(){
@Override public void keyPressed (KeyEvente) {
System.out.println("Called when key pressed."+e);
}
@Override public void keyReleased (KeyEvente) {
System.out.println("Called when key is released."+e);
}
@Override public void keyTyped (KeyEvente) {
System.out.println("Called when key is typed."+e);
}
});
f.setSize (320,240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
First, you have to think about the purpose of keystrokes.
As far as I can see from the code, it seems to be a sample that I just want to accept keystrokes for JFrame.
You should use KeyListener because you want to receive keystrokes from outside the component, as other answers say.
However, I think you used processKeyEvent after looking at some introductory book or website, so I will show you how to do it.
import java.awt.*;
import java.awt.event.*;
class Sample extensions JFrame {
public static void main(String[]args) {
Sample frame = new Sample();
frame.setVisible(true);
}
Sample() {
enableEvents(AWTEvent.KEY_EVENT_MASK);
}
public void processKeyEvent(KeyEvent){
System.out.println("key pressed");
}
}
The processKeyEvent method is defined internally to define its own components.Therefore, it must be overridden within the Component subclass as described above.There is no point in implementing it in a class that does not inherit anything, and it is not invoked on its own.
Similarly, enableEvents are also invoked from within the Component subclass.That's why it's protected.
© 2024 OneMinuteCode. All rights reserved.