Double-click vs java -jar MyJar.jar - java

I have a .jar file and when I run it from the command prompt via java -jar MyJar.jar, it works fine. However double-clicking on it doesn't. Double-clicking starts the program correctly, but something on the inside doesn't work.
For the purposes of trying to figure out what is wrong on my own: what is the difference between double-clicking on a runnable .jar vs running it from the command line?

Where the program is executed is important and can change depending on how it was executed.
You can test this by using something like...
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class WhereAmI {
public static void main(String[] args) {
new WhereAmI();
}
public WhereAmI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
try {
String path = new File(".").getCanonicalPath();
JOptionPane.showMessageDialog(null, "I was started in " + path);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
}
For example. When compiled, the Jar resides in /Volumes/Disk02/DevWork/personal/java/projects/wip/StackOverflow/WhereAmI/dist
If I change directories to this location and run java -jar WhereAmI.jar it outputs
If I change directories to /Volumes/Disk02/DevWork/personal/java/projects/wip/StackOverflow/WhereAmI and run java -jar dist/WhereAmI.jar it outputs
The execution context has changed. The same thing will happen when you double click the Jar and it is system dependent. It will also matter if it's a short cut or the actual Jar.
This will mean that if you rely on any relative resources, you must make sure that the Jar is executed within the correct location, relative to your resources.
How to achieve this is dependent on the OS

Double clicking runs it as "javaw -jar MyJar.jar"

Related

opening chrome in selenium issue

I'm currently taking my first automated test class and the instructor has us creating a program in Eclipse after loading Selenium and create a step in the program to look at an executable to bring up chrome then designate a website to check. It looks like i am stuck in a loop?
Here is the program:
java program
Here is the result:
program result
any and all help would be appreciated. Thank you for your time.
I think this is what you want
This code is to open the default browser and go to a specific link
You can specify the path of any browser you want from the path in the code
import java.awt.Desktop;
import java.net.URI;
public class openBrowser {
public openBrowser() {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("https://www.google.com"));
}
}catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[]args) {
new openBrowser();
}
}
For your code you can follow the following steps
Download ChromeDriver from here
Extract the zip file and follow the path ( because it is easy ) C:\\chromeDriver\\chromedriver.exe
include the ChromeDriver location in your PATH environment variable
Download the required Libraries from the following junit openqa
Add the Libraries to your project ( Build Path )
then this is your code
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;
public class WebDriverDemo {
#Test
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(WebDriverDemo.class.getName()).log(Level.SEVERE, null, ex);
}
driver.quit();
}
}
During the implementation of the code in the eclipse, many problems occurred, so I advise you to implement the project on NetBeans
I use Java 8 and Windows 8.1

I can't run a python script from java and I think it's because the script does not have execute permissions

I'm trying to run a python script whenever a button on my gui (swing) is pressed. However, the script never runs and I'm not sure how to fix this. I know the script works fine independently, it should be py not python because windows, and my file system ntfs.
So far I've been trying to use code that can be summarized as below:
myBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Process p = Runtime.getRuntime().exec("py myScript.py");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
I don't think I can chmod ntfs stuff but I tried setting permissions via right clicking the python file and trying to mess with the security settings. Full control for the script to users does nothing.
The python script has the following permissions, my guess is my code isn't working because it does not have execute permissions.
-rw-r--r--
Use complete python executable path instead of "py". It executes the file with just read permissions.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
try {
Process p = Runtime.getRuntime().exec("C:/Windows/py myScript.py");
String cmdOutput = null;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((cmdOutput = stdInput.readLine()) != null) {
System.out.println(cmdOutput);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
myScript.py
print("This line will be printed.")
Output:
C:\Users\Administrator\Documents\demo>javac Sample.java
C:\Users\Administrator\Documents\demo>java Sample
This line will be printed.

util.Properties bug corrupting .properties file on win10

This bug is happening only in win10. Currently in win7 it does not happen.
Essentially I write some text that the user has inputted in various fields.
I use this to save all the info the user wrote, so when the application is relaunched the info is already there.
Also, I call this class every time the user clicks a button.
With normal behavior, the application runs fine on win7, and it saves everything properly. With win10 though, saving effectively "corrupts" the file, or at least, it makes it empty.
package whatever;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class SaveFile {
public static void mainSave(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
String instaPathCombined = "config.properties";
output = new FileOutputStream(instaPathCombined);
// set the properties value, the get methods all retrieve a string.
prop.setProperty("a", UI.geta());
prop.setProperty("b", UI.getb());
prop.setProperty("c", UI.getc());
prop.setProperty("d", UI.getd());
prop.setProperty("e", UI.gete());
prop.setProperty("f", UI.getf());
prop.setProperty("g", UI.getg());
prop.setProperty("h", UI.geth());
prop.setProperty("i", UI.geti());
prop.setProperty("j", UI.getj());
prop.setProperty("k", UI.getk());
prop.setProperty("l", UI.getl());
prop.setProperty("m", UI.getm());
prop.setProperty("n", UI.getn());
prop.setProperty("o", UI.geto());
prop.setProperty("p", UI.getp());
prop.setProperty("q", UI.getq());
prop.setProperty("r", UI.getr());
prop.setProperty("s", UI.gets());
prop.setProperty("t", UI.gett());
prop.setProperty("u", UI.getu());
prop.setProperty("v", UI.getv());
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I have no idea on why it does this.
Also, this is literally a win10 issue, no other factors matter here, as I tried it on a VM with a fresh win10 installation and it happened.

Doing an action after a set delay in java

Edit: Got it to work. My problem was I was using cmd to compile which exited the vm before the delay ended. Switched to jGrasp and the program worked as intended. Next I need to learn how to actually make a java applet to properly run on my computer. Thanks for your help everyone
I'm trying to set an alarm of sorts using java. I'd like to open a webpage after a set delay. The code below compiles and runs without errors or warnings but running the code does nothing. Just starts and stops the program. I have a feeling the issue arises from how I catch the exceptions but I'm not sure. I also am a little lost on what the actionPerformed() method does. Any help or insight is greatly appreciated
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.IOException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
public class YtAlarmTest
{
public static void main (String [] args)
{
String url = "https://stackoverflow.com/questions/ask";
int delay = 1000;
ActionListener task = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
try
{
if (Desktop.isDesktopSupported())
{
Desktop.getDesktop().browse(new URI(url));
}
}
catch (URISyntaxException e)
{
System.out.println("exception");
}
catch (IOException e)
{
System.out.println("exceptio");
}
}
};
new Timer(delay, task).start();
}
}

Java Clipboard availability

When I research things on the internet I like to copy and paste certain paragraphs so I could review them later on.
I'm trying to write a program that would continuously check the clipboard for text content and write it to a text file any time it is renewed.
In the following test of the program I had "public class Clipboard" in my clipboard before running the program and the exception happened when I copied text from netbeans (The IDE I was using to run the program) while the program was running:
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TestClipboard {
public static void main(String[] args) {
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
String initial = "";
while(true) {
try {
String paste = c.getContents(null).getTransferData(DataFlavor.stringFlavor).toString();
if(!paste.equals(initial)) {
System.out.println(paste);
initial = paste;
}
} catch (UnsupportedFlavorException | IOException ex) {
Logger.getLogger(TestClipboard.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The output:
public class TestClipboard
Exception in thread "main" java.lang.IllegalStateException: cannot open system clipboard
at sun.awt.windows.WClipboard.openClipboard(Native Method)
at sun.awt.datatransfer.ClipboardTransferable.<init>(ClipboardTransferable.java:78)
at sun.awt.datatransfer.SunClipboard.getContents(SunClipboard.java:144)
at delete.TestClipboard.main(TestClipboard.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 34 seconds)
Why can't it open the system clipboard?
Does the getSystemClipboard() method not have global scope? - In other words, can I not get the clipboard's contents if the copy operation was performed in an internet browser?
You appear to be trying to read from the clipboard while another process is updating to it (or some such).
I fixed by:
Requesting an instance of the Clipboard within the loop
Adding a Thread.sleep into the while-loop
For example...
public class TestClipboard {
public static void main(String[] args) {
String initial = "";
while (true) {
try {
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
String paste = c.getContents(null).getTransferData(DataFlavor.stringFlavor).toString();
if (!paste.equals(initial)) {
System.out.println(paste);
initial = paste;
}
} catch (UnsupportedFlavorException | IOException ex) {
Logger.getLogger(TestClipboard.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Thread.sleep(40);
} catch (InterruptedException ex) {
}
}
}
}
It should be noted that it won't stop it from happening, it will only reduce the number of occurrences. When it is thrown, you could (just about) ignore and try again...

Categories

Resources