Swing component add to ScrollPane(JavaFX) - java

I'm making JavaFX application which will open pdf files. I found free library for PDF Viewer but it's made in Swing. So I need to add JPanel to ScrollPane(JavaFX). I tried but without success.
I got this error:
Aug 13, 2016 9:59:09 PM org.icepdf.core.pobjects.Document
WARNING: PDF write support was not found on the class path.
I found here on stackoverflow how to add swing component to javafx pane and I do that but I got this error.
Any suggestion is welcome.
package application;
import java.awt.Component;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
import javafx.embed.swing.SwingNode;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
public class PDFView{
public JPanel viewerComponentPanel;
public static Node showPDF(File sFiles) throws MalformedURLException {
String filePath = sFiles.toURI().toURL().toString();
// build a controller
SwingController controller = new SwingController();
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
final SwingNode swingNode = new SwingNode();
createAndSetSwingContent(swingNode, viewerComponentPanel);
// Open a PDF document to view
controller.openDocument(filePath);
return swingNode;
}
private static void createAndSetSwingContent(final SwingNode swingNode, JPanel viewerComponentPanel) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
swingNode.setContent(viewerComponentPanel);
}
});
}
}
This is main class where I call the method from PDFView class
for(int i=0;i<fileNumber;i++){
choosedName=sFiles[i].getName();
String ext=choosedName.substring(choosedName.lastIndexOf(".") + 1);
switch (ext) {
case "doc":
break;
case "docx":
break;
case "pdf":
tab = new Tab();
tab.setText(choosedName);
s1=new ScrollPane();
tab.setContent(s1);
s1.setContent(PDFView.showPDF(sFiles[i]));
tpane.getTabs().add(tab);

I downloaded icepdf viewer and core jars.
and a minimal change in your code:
//String filePath = sFiles.toURI().toURL().toString();
String filePath = sFiles.getAbsolutePath();
then, it worked for me, hope also works for you...

Related

Configure keybord layout before and after for testing with assertj-swing

I am using assertj-swing to test a simple GUI application. When I enter text in a JTextField, I am getting: IllegalArgumentException: Invalid key code '65406'
It seems it happens because I am using a german keyboard layout, so to solve this problem I added the code below into onSetUp method:
window.target().getInputContext().selectInputMethod(new Locale("en", "US"));
By changing the input method the test passed, but I could not restore the original keyboard layout after the test, thus after testing my layout is always en-US, instead of de-DE.
I tried to set direct to de-DE in the method onTearDown using the line above, or store the current layout onSetUp and restore onTearDown, but the value I am writing into selectInputMethod is always overwritten before I restore it or even after, so that sometimes I see it changes to de-DE and them back en-US.
Does someone had similar problems trying to configure the keyboard layout?
Below you can read an example of the tests I am having trouble with:
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.util.Locale;
import org.assertj.swing.edt.GuiActionRunner;
import org.assertj.swing.fixture.FrameFixture;
import org.assertj.swing.junit.testcase.AssertJSwingJUnitTestCase;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class GuiExampleTest extends AssertJSwingJUnitTestCase {
private FrameFixture window;
private TransformationGui gui;
#Rule
public TemporaryFolder workingPath = new TemporaryFolder();
#Override
protected void onSetUp() {
gui = GuiActionRunner.execute(() -> new TransformationGui());
window = new FrameFixture(robot(), gui);
window.target().getInputContext().selectInputMethod(new Locale("en", "US"));
window.show();
}
#Override
protected void onTearDown() {
window.cleanUp();
}
#Test
public void acceptMyField() throws Exception {
window.textBox("myfield").enterText(givenSomeExcelFile().toString());
assertThat(window.textBox("myfield").text()).endsWith("SomeFile.xlsx");
}
private File givenSomeExcelFile() throws Exception {
return workingPath.newFile("SomeFile.xlsx");
}
}

Context Click doesn't work with Marathon Java Driver

I am currently trying to automate JMeter (as an sample application) using Marathon Java Drivers. I am able to open JMeter but when i try to right click on Test Plan under the left pane, i am not able to do so. Can you please tell me what i am doing wrong. Thanks.
package javadriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Window;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import net.sourceforge.marathon.javadriver.JavaDriver;
import net.sourceforge.marathon.javadriver.JavaProfile;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchMode;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchType;
import org.openqa.selenium.support.PageFactory;
public class JavaDriverTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
JavaProfile profile = new JavaProfile(LaunchMode.JAVA_COMMAND_LINE);
profile.setLaunchType(LaunchType.SWING_APPLICATION);
profile.setMainClass("org.apache.jmeter.NewDriver");
profile.addClassPath("C:\\apache-jmeter-5.1.1\\bin\\ApacheJMeter.jar");
profile.setWorkingDirectory("C:\\\\apache-jmeter-5.1.1\\\\bin");
WebDriver driver = new JavaDriver(profile);
Window window = driver.manage().window();
window.maximize();
WebElement elementLocator = driver.findElement(By.cssSelector("label[text='Test Plan']"));
new Actions(driver).moveToElement(elementLocator, 50, 25).contextClick(elementLocator).build().perform();
//new Actions(driver).clickAndHold(elementLocator);
//new Actions(driver).contextClick(elementLocator).perform();
//driver.quit();
}
}
Looks like you are trying to get the components before the application is completely opened. So Marathon is not able to find the component.
The right click you wanted to perform is a tree item so you need to find the tree and then get node from that.
Check this link for how to locate different types of components where for Swing and JavaFX both are defined. https://marathontesting.com/marathonite-user-guide/selenium-webdriver-bindings/
Please check the following code this will give a better understanding.
package javadriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import net.sourceforge.marathon.javadriver.JavaDriver;
import net.sourceforge.marathon.javadriver.JavaProfile;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchMode;
import net.sourceforge.marathon.javadriver.JavaProfile.LaunchType;
public class JMeterTest {
private JavaDriver driver;
#BeforeTest
public void createJavaProfile_ExecJarLauncher() {
// We prefer Executable jar rather than using Java Command Line
// launcher as the application loads with a blurb and then the main
// window opens. So that we can specify the Start window from where the
// operations are performed. Other wise after creating driver you need to put sleep until the main window is opens.
JavaProfile profile = new JavaProfile(LaunchMode.EXECUTABLE_JAR);
profile.setLaunchType(LaunchType.SWING_APPLICATION);
profile.setExecutableJar("/Users/adityakarra/Projects/apache-jmeter-5.2.1/bin/ApacheJMeter.jar");
profile.setWorkingDirectory("/Users/adityakarra/Projects/apache-jmeter-5.2.1/bin");
// As the application title differs based on the Version number we have
// passed regex to match the window title.
profile.setStartWindowTitle("/^Apache JMeter.*");
driver = new JavaDriver(profile);
// Finally printing the window title after every thing is loaded.
System.out.println("Window Title ::: " + driver.getTitle());
}
#Test
public void getTreeItem() throws InterruptedException {
// As the context menu you wanted to click is a tree item. So find the
// tree initally.
WebElement tree = driver.findElementByTagName("tree");
// Now for getting the tree item we use select by properties and get the
// node.
WebElement node = tree.findElement(By.cssSelector(".::select-by-properties('{\"select\":\"/Test Plan\"}')"));
// Performing right click on the tree item
new Actions(driver).moveToElement(node, 50, 25).contextClick(node).build().perform();
// Clicking on one of the menu items in the context menu.
driver.findElementByCssSelector("menu-item[text='Disable']").click();
new Actions(driver).moveToElement(node, 50, 25).contextClick(node).build().perform();
driver.findElementByCssSelector("menu-item[text='Enable']").click();
}
#AfterTest
public void tearDown() {
if (driver != null)
driver.quit();
}
}
Note: I'm one of the contributor for Marathon.

sarxos webcam-capture-live-streaming example error: package us.sosia.video.stream.agent.ui does not exist

I want to make a webcam capture software and a stream software using sarxos's webcam library. Wanting to understand the examples first i don't know what to change or add in order to go past this error at import us.sosia.
package us.sosia.video.stream.agent.ui does not exist
package us.sosia.video.stream.handler
Maybe i have to make a Marvin project and change the pow.xml file but i don't know how to do this and still add my sarxos library to the Marvin project using NetBeans.
first class is StreamServer:
package us.sosia.video.stream.agent;
import java.awt.Dimension;
import java.net.InetSocketAddress;
import com.github.sarxos.webcam.Webcam;
public class StreamServer {
/**
* #author kerr
* #param args
*/
public static void main(String[] args) {
Webcam.setAutoOpenMode(true);
Webcam webcam = Webcam.getDefault();
Dimension dimension = new Dimension(320, 240);
webcam.setViewSize(dimension);
StreamServerAgent serverAgent = new StreamServerAgent(webcam, dimension);
serverAgent.start(new InetSocketAddress("localhost", 20000));
}
}
Second class is StreamClient:
package us.sosia.video.stream.agent;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.sosia.video.stream.agent.ui.SingleVideoDisplayWindow;
import us.sosia.video.stream.handler.StreamFrameListener;
public class StreamClient {
/**
* #author kerr
* */
private final static Dimension dimension = new Dimension(320,240);
private final static SingleVideoDisplayWindow displayWindow = new SingleVideoDisplayWindow("Stream example",dimension);
protected final static Logger logger = LoggerFactory.getLogger(StreamClient.class);
public static void main(String[] args) {
//setup the videoWindow
displayWindow.setVisible(true);
//setup the connection
logger.info("setup dimension :{}",dimension);
StreamClientAgent clientAgent = new StreamClientAgent(new StreamFrameListenerIMPL(),dimension);
clientAgent.connect(new InetSocketAddress("localhost", 20000));
}
protected static class StreamFrameListenerIMPL implements StreamFrameListener{
private volatile long count = 0;
#Override
public void onFrameReceived(BufferedImage image) {
logger.info("frame received :{}",count++);
displayWindow.updateImage(image);
}
}
}
I need a way to go past this error.
Thanks in advance.
your first 2 lines in both files are:
package us.sosia.video.stream.agent;
This means that these files should be in the following path
"/us/sosia/video/stream/agent/"
Remove this line from both files.

Open External Application From JavaFX

I found a way to open a link on default browser using HostServices.
getHostServices().showDocument("http://www.google.com");
Is there any way to open a media in default media player?
Is there any way to launch a specific File or Application?
Generally speaking, you can use Desktop#open(file) to open a file natively as next:
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");
}
Launches the associated application to open the file. If the specified
file is a directory, the file manager of the current platform is
launched to open it.
More specifically, in case of a browser you can use directly Desktop#browse(uri), as next:
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");
}
Launches the default browser to display a URI. If the default browser
is not able to handle the specified URI, the application registered
for handling URIs of the specified type is invoked. The application is
determined from the protocol and path of the URI, as defined by the
URI class. If the calling thread does not have the necessary
permissions, and this is invoked from within an applet,
AppletContext.showDocument() is used. Similarly, if the calling does
not have the necessary permissions, and this is invoked from within a
Java Web Started application, BasicService.showDocument() is used.
If you want to either open a URL which has an http: scheme in the browser, or open a file using the default application for that file type, the HostServices.showDocument(...) method you referenced provides a "pure JavaFX" way to do this. Note that you can't use this (as far as I can tell) to download a file from a web server and open it with the default application.
To open a file with the default application, you must convert the file to the string representation of the file: URL. Here is a simple example:
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);
}
}
Only the solution with java.awt.Desktop worked for me to open a file from JavaFX.
However, at first, my application got stuck and I had to figure out that it is necessary to call Desktop#open(File file) from a new thread. Calling the method from the current thread or the JavaFX application thread Platform#runLater(Runnable runnable) resulted in the application to hang indefinitely without an exception being thrown.
This is a small sample JavaFX application with the working file open solution:
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);
}
}
The other proposed solution with javafx.application.HostServices did not work at all. I am using OpenJFX 8u141 on Ubuntu 17.10 amd64 and I got the following exception when invoking HostServices#showDocument(String uri):
java.lang.ClassNotFoundException: com.sun.deploy.uitoolkit.impl.fx.HostServicesFactory
Obviously, JavaFX HostServices is not yet properly implemented on all platforms. On this topic see also: https://github.com/Qabel/qabel-desktop/issues/420

Opening Page in IE using Java & Getting Confirmation on its load

I want to load a URL in the user's default browser. And once the webpage gets loaded completely I want to take its screenshot.
Currently I am doing it like this:
import java.awt.Desktop;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;
import javax.imageio.ImageIO;
public class Example {
public static void main(String x[]) throws Exception
{
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://192.168.1.125:8001/html/en/default/process/ProcessDesigner.jsp?wftId=81454277&wftVersion=1");
desktop.browse(oURL);
desktop.wait();
//desktop.print("");
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
try {
Thread.sleep(20000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "jpg", new File("E:\\Akram\\SSFolder\\fi2.jpg"));
System.out.println("Done");
}
}
Here I am using the sleep function so that I should be able to capture snapshot after screen gets loaded, but some web pages may take longer to load.
So I want confirmation that the web page is ready / loaded completely so that I can take its snapshot.
How can I achieve this?

Categories

Resources