2012-12-20 13 views
5

Sono bloccato in qualche punto che non posso aggiungere una chiave Shortcut piace: CTRL +SPACE al mio programma, Cerco una settimana e ho could'd trovare qualsiasi risposte.Come aggiungere le chiavi ShortCut a JTextField?

+5

Leggi su combinazioni di tasti: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html –

risposta

6

Ti consigliamo di dare un'occhiata al Java Tutorial per una buona panoramica delle associazioni di tasti.

Ecco un rapido esempio:

import java.awt.event.*; 
import javax.swing.*; 

public class KeyBindings extends Box{ 
    public KeyBindings(){ 
     super(BoxLayout.Y_AXIS); 
     final JTextPane textArea = new JTextPane(); 
     textArea.insertComponent(new JLabel("Text")); 
     add(textArea); 

     Action action = new AbstractAction() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       textArea.setText("New Text"); 
      }}; 
     String keyStrokeAndKey = "control SPACE"; 
     KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey); 
     textArea.getInputMap().put(keyStroke, keyStrokeAndKey); 
     textArea.getActionMap().put(keyStrokeAndKey, action); 
    } 


    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setContentPane(new KeyBindings()); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 
+0

indovinate un po '! E 'stato fatto. Grazie per il consiglio e grazie per la soluzione è lo stesso per JTextField e cercherò keyBindings. – Azad

Problemi correlati