KEY_PAD イベントをテストして、タイプされた文字をキャッチしないのはなぜですか。そうすれば、「+」記号は、「Shift」と「+」の組み合わせだけでなく、数字の pa からも来る可能性があります。
たとえば、次のようなものです。
public boolean dispatchKeyEvent(KeyEvent event) {
int eventID = event.getID();
if (eventID == KeyEvent.KEY_TYPED) {
char key = event.getKeyChar();
if (key == '+') {
/// Continue here...
System.out.println("++++");
}
}
}
-- 編集: これは完全な例です ( http://www.java2s.com/Code/Java/Event/KeyEventDemo.htmから簡略化)
「Shift」+「+」を入力しようとすると、表示される文字は「+」のはずです
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class KeyEventTest extends JPanel implements KeyListener, ActionListener {
JTextArea displayArea;
JTextField typingArea;
static final String newline = "\n";
public KeyEventTest() {
super(new BorderLayout());
JButton button = new JButton("Clear");
button.addActionListener(this);
typingArea = new JTextField();
typingArea.addKeyListener(this);
displayArea = new JTextArea();
displayArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(displayArea);
scrollPane.setPreferredSize(new Dimension(375, 125));
add(typingArea, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
}
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent e) {
displayInfo(e, "KEY TYPED: ");
}
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
}
/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
}
/** Handle the button click. */
public void actionPerformed(ActionEvent e) {
displayArea.setText("");
typingArea.setText("");
typingArea.requestFocusInWindow();
}
protected void displayInfo(KeyEvent e, String s) {
String typedKey = null;
int id = e.getID();
if (id == KeyEvent.KEY_TYPED) {
char c = e.getKeyChar();
typedKey = "key character = '" + c + "'";
}
displayArea.append(s + newline + " " + typedKey + newline);
displayArea.setCaretPosition(displayArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("KeyEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new KeyEventTest();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
よろしく