2016-06-07 57 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