2016-06-20 1 views
0

JFormattedTextField에 ActionListener를 추가하려고했습니다. 그것은 동안 청취자를 호출하지 않는 텍스트 변경, 초점 변경 :ActionListener를 JFormattedTextField로 설정하는 방법은 무엇입니까?

import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JFormattedTextField; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

class ActionListenerExample extends JPanel { 

    public static void main(String[] args) { 

     JFrame f = new JFrame("Action Listener Example : "); 
     JPanel anyBICPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 1, 1)); 
     anyBICPanel.setName("anyBICPanel"); 
     JLabel anyBICLbl = new JLabel("Any BIC"); 
     anyBICLbl.setName("anyBICLbl"); 
     anyBICPanel.add(anyBICLbl); 
     JFormattedTextField anyBICTxt = new JFormattedTextField(); 
     anyBICTxt.setName("anyBICTxt"); 
     anyBICTxt.setColumns(30); 
     anyBICPanel.add(anyBICTxt); 
     anyBICTxt.addActionListener(anyBICActionListener); 

     JTextField tf2 = new JTextField(5); 
     anyBICPanel.add(tf2); 

     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setContentPane(anyBICPanel); 
     f.pack(); 
     f.setVisible(true); 
    } 
    public static ActionListener anyBICActionListener = new ActionListener() { 

     public void actionPerformed(ActionEvent evnt) { 
      String text = ((JFormattedTextField) evnt.getSource()).getText().toString(); 
      JOptionPane.showMessageDialog(null, "Text : " + text); 
     } 
    }; 
} 

JFormattedTextField에는에 ActionListener를 설정하는 올바른 방법은 무엇입니까? 텍스트 변경이나 변화에 초점을하면서

답변

3

그것은 청취자를 호출하지 않습니다이 눌렀을 때 입력이에만 호출합니다으로의 ActionListener가 적절하게 작동하고 있음을 의미로

좋은. FocusListener, DocumentListener 또는 InputVerifier와 같은 다른 리스너를 사용하려는 것 같습니다.

또한 JFormattedTextField에는 setFocusLostBehavior(int behavior) 메서드가 있습니다.이 메서드를 사용하면 포커스가 손실되고 데이터가 손상되었을 때 수행 할 작업을 지정할 수 있습니다.

1

왜 정적으로 설정 했습니까? 아래처럼 추가하십시오.

anyBICTxt.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent evnt) { 
      String text = ((JFormattedTextField) evnt.getSource()).getText().toString(); 
      JOptionPane.showMessageDialog(null, "Text : " + text); 
    } 
}); 
+0

동일한 수신기를 둘 이상의 사용자 인터페이스에 추가 할 수 있습니다! – AVA

+0

@AVA 네, 추가 할 수 있습니다. 이벤트의 출처를 확인해야하는 경우에 한합니다. – Beniton

관련 문제