2017-06-17 22 views
-1

其實我正在寫代碼。我想顯示消息對話框(不按任何按鈕)當我離開我的JTextField但不知道如何做到這一點。請幫忙。我使用NetBeans。如何顯示消息當我離開JTextField在java

+1

你可以分享你的代碼。代碼,你到目前爲止嘗試過。 – Blasanka

+0

我還沒有寫代碼,但它的邏輯,我想實施我的代碼 –

回答

2

您可以使用Focus Listener API來實現。

focusLost事件中,您可以顯示您的對話框。從文檔

實施例:

public void focusLost(FocusEvent e) 
{ 
    displayMessage("Focus lost", e); 
} 
+0

謝謝,它的工作原理。 –

+0

@MustajeeburRehman:不客氣!我很高興它有幫助。 :) – Azeem

1

可以使用FocusListenerfocusLost()方法。

簡單的例子:

import java.awt.FlowLayout; 
import java.awt.event.FocusEvent; 
import java.awt.event.FocusListener; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JTextField; 

public class ExampleClass { 
    JFrame MainFrame; 
    JTextField textField1; 
    JTextField textField2; 

    public ExampleClass(){ 
     MainFrame = new JFrame("Example"); 
     MainFrame.setLayout(new FlowLayout()); 

     textField1 = new JTextField(10); 
     textFieldFocus(); 

     textField2 = new JTextField("Dummy text"); 

     MainFrame.add(textField1); 
     MainFrame.add(textField2); 
     MainFrame.pack(); 
     MainFrame.setVisible(true); 
    } 
    private void textFieldFocus() {          
     textField1.addFocusListener(new FocusListener() { 

      @Override 
      public void focusLost(FocusEvent e) { 
       JOptionPane.showMessageDialog(null, "Done!"); 

      } 

      @Override 
      public void focusGained(FocusEvent e) {} 
     }); 
    } 
    public static void main(String[] args) { 
     new ExampleClass(); 
    } 
}