Doing an action after a set delay in java - 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();
}
}

Related

Problem in Destroying Firefox Process after some wait of 10 Seconds

proc.wait(10,TimesUnit.Seconds) is not working and its not destroying firefox.exe. here's my code. Can somebody tell me what I am doing wrong? When I execute the code, Firefox just opens and the program finishes. It should destroy the process Firefox after 10 seconds. Is the code correct as it should be?
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
import java.lang.management.*;
public class JavaFirefox
{
public static void main(String args[])
{
try
{
System.out.println("Creating Process");;
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("C:/Program Files/Mozilla Firefox/firefox");
proc.waitFor(10,TimeUnit.SECONDS);
proc.destroy();
}
catch (Exception t)
{
t.printStackTrace();
}
}
}
I am expecting that when firefox opens it will wait for 10 seconds and then it will destroy the process.
The issue has been resolved. Strangely the code was correct. I just changed my default browser from Firefox and to Google Chrome and the code started working.

vlcj setPosition()/setTime() doesn't do anything - what am I doing wrong?

thanks so much in advance for helping me with this seemingly tiny thing - yet I can't figure it out. MP4 Video/audio playback works just fine, yet I can't set the position in the video.
Here's my stripped down code:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import javax.swing.JPanel;
import com.sun.jna.NativeLibrary;
import java.util.logging.Level;
import java.util.logging.Logger;
import uk.co.caprica.vlcj.binding.RuntimeUtil;
import uk.co.caprica.vlcj.player.base.ControlsApi;
import uk.co.caprica.vlcj.player.base.MediaApi;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.CallbackMediaPlayerComponent;
import uk.co.caprica.vlcj.player.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.component.callback.FilledCallbackImagePainter;
import uk.co.caprica.vlcj.player.component.callback.FixedCallbackImagePainter;
import uk.co.caprica.vlcj.player.component.callback.ScaledCallbackImagePainter;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.player.renderer.RendererItem;
import uk.co.caprica.vlcjplayer.event.TickEvent;
import uk.co.caprica.vlcjplayer.view.action.mediaplayer.MediaPlayerActions;
public class TestClass extends JPanel {
private EmbeddedMediaPlayerComponent ourMediaPlayer;
TestClass(){
//NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
ourMediaPlayer = new EmbeddedMediaPlayerComponent();
/* Set the canvas */
Canvas c = new Canvas();
c.setBackground(Color.black);
c.setVisible(true);
/* Set the layout */
this.setLayout(new BorderLayout());
/* Add the canvas */
this.add(c, BorderLayout.CENTER);
this.setVisible(true);
this.add(ourMediaPlayer);
}
public void play() {
/* Play the video */
System.out.println("Starting...");
ourMediaPlayer.mediaPlayer().controls().setPosition((float) 0.5); // NOPE
ourMediaPlayer.mediaPlayer().media().play("/home/manfred/ExtraDisk/Work/BTL/Movement2022/walking.mp4"); // works
ourMediaPlayer.mediaPlayer().controls().stop(); // works
ourMediaPlayer.mediaPlayer().controls().setPosition((float) 0.5); //NOPE
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestClass.class.getName()).log(Level.SEVERE, null, ex);
}
ourMediaPlayer.mediaPlayer().controls().setPosition((float) 0.5); //NOPE
ourMediaPlayer.mediaPlayer().controls().setTime(2000); // NOPE
ourMediaPlayer.mediaPlayer().controls().start(); //works
//System.time.sleep(2);
System.out.println("Started!");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestClass.class.getName()).log(Level.SEVERE, null, ex);
}
ourMediaPlayer.mediaPlayer().controls().stop(); // works
}
}
Playback via .mediaPlayer().media().play() works, so does start and stop via .mediaPlayer().controls().start() and .mediaPlayer().controls().stop().
What doesn't work is .mediaPlayer().controls().setTime(xx) and .mediaPlayer().controls().setPosition(xx), basically nothing happens.
What am I not doing right here? Is this a threading issue? Anyone have any working minimal examples?
Thanks again, any help is greatly appreciated!
It is not possible to use the API to set the time/position before playback has started.
LibVLC operates asynchronously for many operations. Just calling play() does not mean that playback has started, so setting the time/position immediately after play() is called will not (always) work.
There are at least two approaches you can use:
Wait for a media player "ready" event, and set the time/position (this will fire an event each time the media player is ready, so each time you play it, although you can write a one-shot listener that unregisters itself if you only want to do it the first time you play).
public static void main(String[] args) throws Exception {
MediaPlayer mediaPlayer = new MediaPlayerFactory().mediaPlayers().newMediaPlayer();
mediaPlayer.events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
#Override
public void mediaPlayerReady(MediaPlayer mediaPlayer) {
mediaPlayer.controls().setTime(10000);
}
});
mediaPlayer.media().play("/home/movies/whatever.mp4");
Thread.currentThread().join();
}
With this first approach there is the small risk that you will see one or two video frames rendered before skipping occurs.
Use media options to set the start time (in seconds, including fractions of seconds like 10.5):
public static void main(String[] args) throws Exception {
MediaPlayer mediaPlayer = new MediaPlayerFactory().mediaPlayers().newMediaPlayer();
mediaPlayer.media().play("/home/movies/whatever.mp4", ":start-time=10");
Thread.currentThread().join();
}
Thanks to caprica's ingenious insights, this snippet actually works (don't know why, but it does - and that's all that matters for now):
ourMediaPlayer.mediaPlayer().media().play("/home/manfred/ExtraDisk/Work/BTL/Movement2022/walking.mp4"); // works
ourMediaPlayer.mediaPlayer().controls().stop(); // works
ourMediaPlayer.mediaPlayer().controls().start(); // works
ourMediaPlayer.mediaPlayer().controls().setTime(5000); // WORKS
Still a bit of a mystery, but I'll take it!

Using JNativeHook from an applet in browser

I am trying to use JNativeHook from a browser applet to grab a certain keyboard event. I am getting some strange behavior and it does not seem to be working. This is the code I have so far:
import java.awt.*;
import java.applet.Applet;
import netscape.javascript.*;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Test extends Applet implements NativeKeyListener {
JSObject window;
public void nativeKeyPressed(NativeKeyEvent e) {
window.eval("console.log('"+NativeKeyEvent.getKeyText(e.getKeyCode()) + "');");
}
public void nativeKeyReleased(NativeKeyEvent e) {
}
public void nativeKeyTyped(NativeKeyEvent e) {
}
public void init() {
window = JSObject.getWindow(this);
window.eval("console.log('test');");
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
window.eval("console.log('There was a problem registering the native hook.');");
window.eval("console.log('"+ex.getMessage()+"');");
System.exit(1);
}
//Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(this);
}
}
Ideally I would like to be able to callback into a javascript function after a certain key is pressed globally. I have read some stuff about permissions and signing but I am not sure if this is causing an issue for localhost testing (I have to click through warnings).
I am also not 100% on the inner workings of JNativeHook. I am tempted to just write a small DLL for each platform using JNI, but I wanted to check to see if I was missing something fundamental first.
It is possible to run native code (JNativeHook) from JNLP but you need to sign the code with a valid certificate. You can run from localhost without one if you want to do some testing.

Illegal start of expression error in java swing auto-generated code

I am using Java Swing to create a GUI.
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.InputVerifier;
import java.lang.Process;
import java.lang.ProcessBuilder;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
It is telling me that the line " private void outputDirActionPerformed..." has an illegal start of expression, however that line of code is autogenerated by NetBeans. commandPLINK is an array of parameters, and is behaving correctly.
ProcessBuilder pb = new ProcessBuilder(commandPLINK);
try {
pb.inheritIO();
Process p = pb.start();
} catch (IOException ex) {
Logger.getLogger(rtPCRGui.class.getName()).log(Level.SEVERE, null, ex);
}
} //convertButtonActionPerformed
private void outputDirActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
Any idea what might be happening that's causing the autogenerated code to throw this error?
This error happens when you are missing a } somewhere before the line that triggers the error. You should look at the preceding method and see if every { is matched with a corresponding }.
Also, you may look if there is an extra } after the generated method.
To be more clear, this error means that the compiler did not expect to have a function definition starting there, because it is believing that you are still in a method block, and a method can not be inside another method.

Double-click vs java -jar MyJar.jar

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"

Categories

Resources