2012-05-14 3 views
2

를 사용하여 버튼에 응답 코드 경우 "A"는 여기 내가 이러한 목표와 프로그램을 만들고 싶어 키 바인딩

를 클릭 할 때입니다 지금까지 가지고있는 코드 : 이제

// Imports 

Public class Test{ 

JButton button = new JButton(); 

//... 

Test(){ 

button.getInputMap().put(KeyStroke.getKeyStroke("A"), "Pressed"); 


//... 

} 

// Where do I add the code that responds when button is pressed? 
} 

가 나는 버튼을 누를 때 실행할 코드를 추가하는 방법은 무엇입니까?

답변

2

actionPerformed에 대해 구체적으로 동작 수신기를 추가해야합니다.

import java.awt.event.ActionEvent; 
import javax.swing.AbstractAction; 
import javax.swing.Action; 
import javax.swing.JButton; 
import javax.swing.JComponent; 
import javax.swing.KeyStroke; 

public class Main { 
    public static void main(String[] argv) throws Exception { 

     JButton component = new JButton(); 
     MyAction action = new MyAction(); 
     component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"), 
      action.getValue(Action.NAME)); 
    } 
} 

class MyAction extends AbstractAction { 
    public MyAction() { 
     super("my action"); 
    } 

    public void actionPerformed(ActionEvent e) { 
     //Here goes the code where the button does something 
     System.out.println("hi");//In this case we print hi 
    } 
} 

이 예에서는 F2 키를 누르면 버튼을 누르는 것과 동일합니다. 내가 생각할 수있는

+0

내가 하나의 버튼 이상이있는 경우? 같은 actionPerformed 메소드를 사용합니까? – Anonymous181

+0

다른 클래스를 생성합니다.이 경우 이름은 MyAction이며 우리는이를 액션으로 인스턴스화합니다. 각 버튼에 대해 새 클래스를 만들 수 있습니다. –

6

두 가지 방법 :

  • 유무의 JButton 및 및 키 바인딩이 같은 AbstractAction로 공유하거나 어쩌면 더 나은
  • 간단히 키 바인딩에서 버튼을 doClick()를 호출합니다.

KeyBindingEg.java

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

public class KeyBindingEg extends JPanel { 
    private JButton btnA = new JButton(); 

    public KeyBindingEg() { 
     Action btnAction = new ActionOne("A"); 
     Action keyBindingAction = new ActionTwo(); 

     int condition = JLabel.WHEN_IN_FOCUSED_WINDOW; 
     InputMap inputmap = btnA.getInputMap(condition); 
     ActionMap actionmap = btnA.getActionMap(); 

     final String aKeyPressed = "a key pressed"; 
     inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), aKeyPressed); 

     actionmap.put(aKeyPressed, keyBindingAction); 
     // actionmap.put(aKeyPressed, btnAction); // one or the other, your choice 

     btnA.setAction(btnAction); 
     add(btnA); 
    } 

    private class ActionOne extends AbstractAction { 
     public ActionOne(String text) { 
     super(text); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
     sharedMethod(); 
     } 
    } 

    private class ActionTwo extends AbstractAction { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
     btnA.doClick(); 
     } 
    } 

    private void sharedMethod() { 
     System.out.println("Method called by either key bindings or action listener"); 
    } 

    private static void createAndShowGui() { 
     JFrame frame = new JFrame("KeyBindingEg"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new KeyBindingEg()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
관련 문제