我创建了一个Map,其中包含KeyEvent常量作为键,JButton作为数据,我将它们添加到createButton函数内的Map中:
/*TouchType.java*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JScrollPane;
//for the map
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
public class TouchType extends JFrame{
public TouchType(){//constructor
super("Typing application");
...
Map<Integer,Object> mp = new HashMap<Integer,Object>();//declaring a map object
...
row1.add(createButton(VK_DEAD_TILDE, "~"));
row1.add(createButton(VK_1, "1"));
row1.add(createButton(VK_2, "2"));
...
}//end of constructor
private void createButton(int keyCode, String name){
newButton = new JButton(name);
mp.put(keyCode, newButton);
}
不幸的是编译器抱怨常量,这是一个示例错误:
G:\JAVA\GUI\2015\createFrames\keyboard>javac *.java
TouchType.java:54: error: cannot find symbol
row1.add(createButton(VK_DEAD_TILDE, "~"));
^
symbol: variable VK_DEAD_TILDE
location: class TouchType
TouchType.java:55: error: cannot find symbol
row1.add(createButton(VK_1, "1"));
^
symbol: variable VK_1
location: class TouchType
TouchType.java:56: error: cannot find symbol
row1.add(createButton(VK_2, "2"));
^
symbol: variable VK_2
location: class TouchType
TouchType.java:57: error: cannot find symbol
row1.add(createButton(VK_3, "3"));
^
symbol: variable VK_3
location: class TouchType
TouchType.java:58: error: cannot find symbol
row1.add(createButton(VK_4, "4"));
^
symbol: variable VK_4
location: class TouchType
TouchType.java:59: error: cannot find symbol
row1.add(createButton(VK_5, "5"));
^
symbol: variable VK_5
location: class TouchType
TouchType.java:60: error: cannot find symbol
row1.add(createButton(VK_6, "6"));
^
symbol: variable VK_6
location: class TouchType
TouchType.java:61: error: cannot find symbol
row1.add(createButton(VK_7, "7"));
^
symbol: variable VK_7
location: class TouchType
TouchType.java:62: error: cannot find symbol
row1.add(createButton(VK_8, "8"));
^
symbol: variable VK_8
location: class TouchType
TouchType.java:63: error: cannot find symbol
row1.add(createButton(VK_9, "9"));
知道为什么请?无法理解......对不起,Java的新手!
答案 0 :(得分:2)
您似乎希望能够引用KeyEvent
中的常量,而无需导入或限定它们。你应该有:
row1.add(createButton(KeyEvent.VK_DEAD_TILDE, "~"));
或添加:
import static java.awt.event.KeyEvent.*;
这样KeyEvent
的所有静态成员都可以不受限制地使用。