2016-10-06 3 views
1

HostServices를 사용하여 기본 브라우저에서 링크를 여는 방법을 찾았습니다.JavaFX에서 외부 응용 프로그램 열기

getHostServices().showDocument("http://www.google.com"); 
  • 기본 미디어 플레이어에서 미디어를 열 수있는 방법이 있습니까?
  • 특정 방법을 사용할 수 있습니까 파일 또는 신청?
+1

특정 문서에 매핑되는 URL (file : // URL 포함)을 사용하여이 작업을 시도 할 때마다 해당 문서 유형의 기본 응용 프로그램으로 문서가 열립니다. 미디어 등에서 같은 방식으로 작동하지 않습니까? 합리적으로 그렇게 할 수 있다면 AWT와 JavaFX (허용되는 대답이 섞여 있음)를 사용하지 않는 것이 좋습니다. –

+0

예,'file : //'이 있으면'IllegalArgumentException'을 직면합니다. 나는 AWT에서 온 당신의 의견을 읽기 전에주의하지 않았다. 답변을 공유해 주시면 대단히 감사하겠습니다. JavaFX를 사용하여이 작업을 수행하는 방법은 내 지식과 경험을 풍부하게합니다. –

+0

글쎄, 난 그냥 다시 테스트하고, 그것은 파일 :// URL과 함께 작동하지만 http : URL (파일을 다운로드하는 브라우저를 엽니 다)와 다른 문서 형식과 작동하지 않습니다. 답변을 추가 하겠지만, 웹 서버에서 다운로드 한 미디어를 열려면 어떻게해야 할 지 모르겠습니다. –

답변

2

, 당신은 참조 HostServices.showDocument(...) 방법은 할 수있는 "순수 자바 FX '방법을 제공합니다 이. 웹 서버에서 파일을 다운로드하여 기본 응용 프로그램으로 열어 볼 수는 없습니다.

기본 응용 프로그램으로 파일을 열려면 파일을 file: URL의 문자열 표현으로 변환해야합니다.

import java.io.File; 

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.Label; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.HBox; 
import javafx.scene.layout.VBox; 
import javafx.stage.FileChooser; 
import javafx.stage.Stage; 

public class OpenResourceNatively extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     TextField textField = new TextField("http://stackoverflow.com/questions/39898704"); 
     Button openURLButton = new Button("Open URL"); 
     EventHandler<ActionEvent> handler = e -> open(textField.getText()); 
     textField.setOnAction(handler); 
     openURLButton.setOnAction(handler); 

     FileChooser fileChooser = new FileChooser(); 
     Button openFileButton = new Button("Open File..."); 
     openFileButton.setOnAction(e -> { 
      File file = fileChooser.showOpenDialog(primaryStage); 
      if (file != null) { 
       open(file.toURI().toString()); 
      } 
     }); 

     VBox root = new VBox(5, 
       new HBox(new Label("URL:"), textField, openURLButton), 
       new HBox(openFileButton) 
     ); 

     root.setPadding(new Insets(20)); 
     primaryStage.setScene(new Scene(root)); 
     primaryStage.show(); 
    } 

    private void open(String resource) { 
     getHostServices().showDocument(resource); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

좋아, 이제 알았어. 'HostServices.showDocument (...)'메소드는 브라우저를 열 수있을뿐만 아니라 운영 체제가 설치된 기본 응용 프로그램으로 모든 종류의 파일을 열 수 있습니다. 고마워요 :) –

+0

AWT에는 시스템 탐색기에서 디렉토리를 열 수있는 방법이있었습니다. JavaFX에서 시스템 탐색기에서 디렉토리를 여는 방법은 무엇입니까? –

+0

@RanaDepto 같은 일 이죠, 그렇죠? 'file'이 디렉토리를 참조하면,'getHostServices(). showDocument (file.toURI(). toString())'는 시스템 파일 브라우저에서 디렉토리를 열 것이다. –

4

일반적으로, 당신은 다음 파일 기본적으로을 열 Desktop#open(file)를 사용할 수 있습니다

final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; 
if (desktop != null && desktop.isSupported(Desktop.Action.OPEN)) { 
    desktop.open(file); 
} else { 
    throw new UnsupportedOperationException("Open action not supported"); 
} 

파일을 열 수있는 연결된 응용 프로그램을 시작합니다. 지정된 파일이 디렉토리 인 경우 현재 플랫폼의 파일 관리자는 이 실행되도록 열었습니다.

은보다 구체적으로는, 브라우저의 경우에는 다음과 같이 직접 Desktop#browse(uri)를 사용할 수 있습니다

final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; 
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { 
    desktop.browse(uri); 
} else { 
    throw new UnsupportedOperationException("Browse action not supported"); 
} 

URI를 표시하는 기본 브라우저을 시작합니다. 기본 브라우저 이 지정된 URI을 처리 할 수없는 경우 지정된 유형의 URIs을 처리하기 위해 등록 된 응용 프로그램이 호출됩니다. 응용 프로그램은 이며 클래스의 프로토콜과 경로에서 결정되며 URI 클래스로 정의됩니다. 호출 스레드에 필요한 권한이없고 애플릿 내에서 호출되는 경우 AppletContext.showDocument()이 사용됩니다. 마찬가지로, 호출에 에 필요한 사용 권한이없고 이것이 Java Web Started 응용 프로그램 내에서 호출 된 경우 BasicService.showDocument()이 사용됩니다. 브라우저에서 http: 계획이있는 URL을 열거 나 해당 파일 형식에 대한 기본 응용 프로그램을 사용하여 파일을 열 중 하나를 원하는 경우

+1

고마워요. 이 대답은 내 요구 사항을 모두 충족시킵니다. –

0

나 자바 FX에서 파일을 열 수 있도록 java.awt.Desktop 만 솔루션 일 : 다음은 간단한 예입니다.

그러나 처음에는 응용 프로그램이 작동하지 않아 새로운 스레드에서 Desktop#open(File file) (으)로 전화해야한다는 것을 알아야했습니다. 현재 스레드 또는 JavaFX 응용 프로그램 스레드 Platform#runLater(Runnable runnable)에서 메서드를 호출하면 예외가 throw되지 않고 응용 프로그램이 무기한 중지됩니다.

이 작업 파일 개방형 솔루션과 함께 작은 샘플 자바 FX 애플리케이션은 다음과 같습니다

import java.awt.Desktop; 
import java.io.File; 
import java.io.IOException; 

import javafx.application.Application; 
import javafx.concurrent.Task; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.stage.FileChooser; 
import javafx.stage.Stage; 

public class FileOpenDemo extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     final Button button = new Button("Open file"); 

     button.setOnAction(event -> { 
      final FileChooser fileChooser = new FileChooser(); 
      final File file = fileChooser.showOpenDialog(primaryStage.getOwner()); 

      if (file == null) 
       return; 

      System.out.println("File selected: " + file.getName()); 

      if (!Desktop.isDesktopSupported()) { 
       System.out.println("Desktop not supported"); 
       return; 
      } 

      if (!Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) { 
       System.out.println("File opening not supported"); 
       return; 
      } 

      final Task<Void> task = new Task<Void>() { 
       @Override 
       public Void call() throws Exception { 
        try { 
         Desktop.getDesktop().open(file); 
        } catch (IOException e) { 
         System.err.println(e.toString()); 
        } 
        return null; 
       } 
      }; 

      final Thread thread = new Thread(task); 
      thread.setDaemon(true); 
      thread.start(); 
     }); 

     primaryStage.setScene(new Scene(button)); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

javafx.application.HostServices와 다른 제안 된 솔루션이 전혀 작동하지 않았다. 우분투 17.10 AMD64에서 OpenJFX 8u141을 이용하고 있고 HostServices#showDocument(String uri)를 호출 할 때 나는 다음과 같은 예외를 가지고 : 분명히

java.lang.ClassNotFoundException: com.sun.deploy.uitoolkit.impl.fx.HostServicesFactory

는, 자바 FX HostServices 아직 제대로 모든 플랫폼에서 구현되지 않습니다. 이 주제에 대해서는 https://github.com/Qabel/qabel-desktop/issues/420

관련 문제