我需要一些关于我的 java 代码的帮助我是 java 的新手,我想要做的是一旦我按下一个字母我想显示一些消息只是为了验证代码是否有效。使用 javax swing 库特别是 keylistener 和 key event,我不知道我是否做得对。这是我的代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class KeyStrokeButton{
public JFrame frame;
public JPanel panel;
public JButton btnfocus, btnrelease, btnwindow, btnancestor;
public JTextField text;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
KeyStrokeButton mydesign = new KeyStrokeButton();
mydesign.design();
}
});
}
public void design()
{
panel = new JPanel();
panel.setLayout(null);
frame = new JFrame("Keystroke Tutorials");
frame.getContentPane().add(panel);
frame.setSize(250, 250);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnfocus = new JButton("<html><center>Focus");
btnfocus.setBounds(10, 10, 90, 80);
panel.add(btnfocus);
btnfocus.addKeyListener(new ClickPressed());
btnrelease = new JButton("Release");
btnrelease.setBounds(110, 10, 90, 80);
panel.add(btnrelease);
btnancestor = new JButton("Ancestor");
btnancestor.setBounds(10, 100, 90, 80);
panel.add(btnancestor);
btnwindow = new JButton("Window");
btnwindow.setBounds(110, 100, 90, 80);
panel.add(btnwindow);
}
class ClickPressed implements KeyListener
{
public void KeyPressed(KeyEvent e)
{
//any code.
}
}
}
我想尽可能地为事件分离我的代码,所以我创建了一个类以使其可读。