我正在使用 Java Swing 编写代码,以便在我键入数字键时按右键。但是我无法通过搜索找到我想要的东西。这是我的代码,我不明白为什么这不起作用。请帮我..
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
class class01 {
public static void main(String[] args) {
JFrame f = new JFrame("Key event test");
f.setSize(230, 500);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
JButton button1 = new JButton("Coffe");
button1.setSize(100, 100);
button1.setLocation(0, 0);
JButton button2 = new JButton("Latte");
button2.setSize(100, 100);
button2.setLocation(0, 100);
JButton button3 = new JButton("Espresso");
button3.setSize(100, 100);
button3.setLocation(100, 100);
JButton button4 = new JButton("Vanilla Latte");
button4.setSize(100, 100);
button4.setLocation(100, 0);
f.add(button1);
f.add(button2);
f.add(button3);
f.add(button4);
// Show message when the corresponding button is pressed.
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button1.keyPressed(KeyEvent.VK_1);
JOptionPane.showMessageDialog(f.getComponent(0), "Coffee selected");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
button2.keyPressed(KeyEvent.VK_2);
JOptionPane.showMessageDialog(f.getComponent(0), "Latte selected");
}
});
}
}
UYOU
梵蒂冈之花
有只小跳蛙
相关分类