2016-06-07 56 views
0

我基本上希望能夠通過按鍵盤上的按鍵來按JButton。例如:用鍵連接JButtons

如果我按「T」,它應該使用JButton「測試」。如果我按「H」,它應該使用JButton「你好」,等等......

這是最簡單(和最懶惰)的方式來做到這一點?

回答

0

套裝mnemonic焦炭那個按鈕

JButton btnTesting = new JButton("Testing"); 
btnTesting.setMnemonic('T'); 

你會在這種情況下,按Alt + T使用它。

編輯

要重現沒有你將不得不使用的KeyListener您在集裝箱保持你的按鈕註冊ALT鍵此功能。您將必須實施確定哪個按鍵對應哪個按鍵的邏輯。

樣品:

import java.awt.EventQueue; 
import java.awt.FlowLayout; 
import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

    public class ButtonPressDemo { 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        initGUI(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    private static void initGUI() { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setBounds(100, 100, 300, 300); 

     JPanel contentPane = new JPanel(); 
     contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); 
     // add your buttons 
     contentPane.add(new JButton("A")); 
     contentPane.add(new JButton("B")); 
     contentPane.add(new JButton("C")); 

     contentPane.addKeyListener(new KeyAdapter() { 

      @Override 
      public void keyPressed(KeyEvent e) { 
       int keyPressed = e.getKeyCode(); 
       System.out.println("pressed key: "+keyPressed); 
       // do something ... 
      } 
     }); 
     contentPane.setFocusable(true); // panel with keyListener must be focusable 
     frame.setContentPane(contentPane); 
     contentPane.requestFocusInWindow(); // panel with key listener must have focus 
     frame.setVisible(true); 
    } 
} 

用這種方法你的GUI不會在視覺上反應按下記憶鍵即按鈕將無法運行動畫,他們將與setMnemonic來和助記符字符不會自動在標籤下劃線按鈕。

+0

沒有辦法沒有「ALT」嗎? –

+0

您將不得不在面板上註冊關鍵監聽器,該監聽器保存您的按鈕獲取鍵入的字符並確定它代表哪個按鈕。 – MatheM