2014-02-08 66 views
2

我想單擊菜單時發送電子郵件。從setOnAction啓動電子郵件客戶端

 MenuItem sendmail= new MenuItem("Send E-Mail"); 

     sendmail.setOnAction(new EventHandler<ActionEvent>() 
     { 
      @Override 
      public void handle(ActionEvent e) 
      { 
       // Call E-mail Client 
      } 
     }); 

你能告訴我如何從這段代碼中調用安裝到用戶PC的電子郵件客戶端嗎?

回答

3

您可以使用Desktop類。我相信代碼看起來是這樣的:

import java.awt.Desktop; 
if (Desktop.isDesktopSupported()) { 
    Desktop desktop = Desktop.getDesktop(); 
    if (desktop.isSupported(Desktop.Action.MAIL)) { 
     URI mailto = new URI("mailto:[email protected]?subject=Hello%20World"); 
     desktop.mail(mailto); 
    } 
} 
3

這是無證的,但似乎工作,並且是「純FX」的解決方案,而不是依靠java.awt中的API或明知外部可執行文件的路徑。撥打Application.getHostServices().showDocument(...)方法,並通過mailto:url作爲網址:

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.HBox; 
import javafx.stage.Stage; 

public class OpenDefaultBrowser extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     final HBox root = new HBox(5); 
     final TextField textField = new TextField("[email protected]"); 
     final Button goButton = new Button("Mail"); 

     EventHandler<ActionEvent> goHandler = new EventHandler<ActionEvent>() { 

      @Override 
      public void handle(ActionEvent event) { 
       getHostServices().showDocument("mailto:"+textField.getText()); 
      } 

     }; 

     textField.setOnAction(goHandler); 
     goButton.setOnAction(goHandler); 

     root.getChildren().addAll(textField, goButton); 
     final Scene scene = new Scene(root, 250, 150); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
相關問題