I've created a Map containing a KeyEvent constant as key and a JButton as data and I add them to the Map inside a createButton function:
/*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);
}
Unfortunately the compiler complains about the constants, here is a sample error:
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"));
Any idea why please? Can't quite understand...sorry, new to Java!
You appear to be expecting to be able to reference constants from KeyEvent
without either importing them or qualifying them. You should either have:
row1.add(createButton(KeyEvent.VK_DEAD_TILDE, "~"));
Or add:
import static java.awt.event.KeyEvent.*;
so that all the static members of KeyEvent
can be used without qualification.
See more on this question at Stackoverflow