Java Exclusive Fullscreen Mode Keeps Throwing 'Invalid display mode' - java

I can't for the life of me figure out Exlusive Fullscreen. It keeps throwing 'Invalid display mode' no matter which of my display modes I try.
I've tried doing this as the official Java tutorials show, and as other people's tutorials show. I keep getting the same error thrown. The try-finally, as suggested in the official Java tutorials, gives me the same issues. I've already made sure I'm using my supported modes.
Could this have something to do with my laptop's display being overclocked from 75Hz to 100Hz? I have of course tried supplying my own DisplayMode with DisplayMode.REFRESH_RATE_UNKNOWN.
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class Main {
private static GraphicsEnvironment gfxEnv;
private static GraphicsDevice gfxDevice;
private static DisplayMode defaultDisplayMode;
public static void main(String[] args) {
init();
}
private static void init() {
gfxEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
gfxDevice = gfxEnv.getDefaultScreenDevice();
defaultDisplayMode = gfxDevice.getDisplayMode();
DisplayMode[] displayModes = gfxDevice.getDisplayModes();
DisplayMode dm1920x1080x75 = displayModes[displayModes.length - 1];
System.out.println(dm1920x1080x75);
JFrame window = new JFrame();
window.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
aMethodIWantToCallElseWhere();
}
});
window.setUndecorated(true);
window.setResizable(false);
if (gfxDevice.isFullScreenSupported()) {
gfxDevice.setFullScreenWindow(window);
if (gfxDevice.isDisplayChangeSupported())
gfxDevice.setDisplayMode(dm1920x1080x75);
}
}
public static void aMethodIWantToCallElseWhere() {
if (gfxDevice.isDisplayChangeSupported())
gfxDevice.setDisplayMode(defaultDisplayMode);
gfxDevice.setFullScreenWindow(null);
}
}
Console output:
1920x1080x32bpp#75Hz
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid display mode
at java.desktop/sun.awt.Win32GraphicsDevice.setDisplayMode(Win32GraphicsDevice.java:452)
at Main.aMethodIWantToCallElseWhere(Main.java:48)
at Main$1.keyTyped(Main.java:33)
at...
This does enter fullscreen without any issues. But exiting it is where the problem appears. I've tried this in the suggested try-finally way, which throws the exact same error - 'Invalid display mode'.
I've played around with a bunch of different ideas, but I'm now out of them.
Am I missing something?
I'd like to avoid the try-finally, just so that I can change modes on user request. I hope that's possible.
EDIT
So I tried setting my display back from 100Hz to 75Hz. That solved it. How would I go about getting it running with an overclocked display that doesn't even appear in getDisplayModes?

Related

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!

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");
}
}

Java - How can I implement an Applet into a JavaFX component? [duplicate]

I can't seem to find anything on this - other than it can't be embedded in a web view.
I currently have an image viewing product which is accessed via an applet and controlled via JavaScript from an HTML page.
I am investigating a client application using JavaFX and it would likely need to access that applet. I attempted to embed it into the WebView and that didn't work. Searching on this site stated that webview doesn't support plug in technology. This is to build an applet with Java FX - but rather to invoke and interact with an existing product.
Therefore I am left wondering if there is another way - using JavaFX 8?
Thanks!
A quick trial with a really simple sample applet, demonstrates that it is possible to embed Swing applets into JavaFX applications (with Java 8).
Sample
Here is the HelloWorld applet from the Oracle getting started with applets documentation:
import javax.swing.*;
public class HelloWorldApplet extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
And here is a JavaFX application which embeds it:
import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import java.util.concurrent.*;
public class JavaFXSwingAppletHolderApplication extends Application {
private JApplet applet = new HelloWorldApplet();
private Dimension appletSize;
#Override public void init() throws ExecutionException, InterruptedException {
applet.init();
FutureTask<Dimension> sizingTask = new FutureTask<>(() ->
applet.getRootPane().getPreferredSize()
);
SwingUtilities.invokeLater(sizingTask);
appletSize = sizingTask.get();
}
#Override public void start(Stage stage) {
final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(() ->
swingNode.setContent(applet.getRootPane())
);
stage.setScene(
new Scene(
new Group(swingNode),
appletSize.getWidth(), appletSize.getHeight(),
Color.BLACK
)
);
stage.show();
}
#Override public void stop() {
applet.stop();
applet.destroy();
}
public static void main(String[] args) {
launch(args);
}
}
Notes
I'm not sure if the sizingTask is the above code is strictly necessary, I just stuck it in there just in case as I know little about Swing layout, so thought it best to be explicit.
This sample only embeds a basic applet, your applet will be more complex so you will need to validate a similar solution for your particular applet to ensure it works for you.
Recommendation
Most existing applets are quite small - it is probably a better idea to reimplement an applet as a pure JavaFX component implementation rather than try to embed the applet in a JavaFX application.
Also note that the applet API is deprecated as part of Java 9, by JEP 289: Deprecated the Applet API.

Is it possible to create programs in Java that create text to link in Chrome?

I apologize for the long question.
I was browsing a forum the other day and I saw a few pieces of text that were linking to youtube and other sites.
I had to always highlight and then copy and paste or right click "go to" in google chrome browser.
Since I've been playing with Java a little bit, I thought about making my own little program that will give a link to text that has an address . For example if I said "hey, check this video out I saw the other day 'www.youtube.com' " I'd want the youtube part to be clickable.
Could anybody tell me if such a thing is possible and if it is, what libraries would I have to use for this and lastly, how can I find a list of all imports and libraries in java?
Thanks.
Use HTML in JEditorPane and add HyperLinkListener to detect click on URLs.
Than use Desktop API to open default browser with the URL.
Something like:
import java.awt.Desktop;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class Test {
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JEditorPane jep = new JEditorPane();
jep.setContentType("text/html");//set content as html
jep.setText("Welcome to <a href='http://stackoverflow.com/'>StackOverflow</a>.");
jep.setEditable(false);//so its not editable
jep.setOpaque(false);//so we dont see whit background
jep.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent hle) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
System.out.println(hle.getURL());
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(hle.getURL().toURI());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
JFrame f = new JFrame("HyperlinkListener");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(jep);
f.pack();
f.setVisible(true);
}
});
}
}

VLCJ NullPointer (I just want a simple cross-platform java video player)

I am wanting to make a simple java applicaiton to play video. I want it to play mpeg4 and mov formats in particular. JMF is what I started with and I have a lovely working example. However, there is no support for mov or mpeg4 formats. I've looked at Xuggler but can't see a SIMPLE way to get it working. VLCJ seemed easy - I downloaded the jar files and attached them to my project (vlcj-2.1.0.jar, jna-3.4.0.jar, platform-3.4.0.jar, vlcj-2.1.0.jar)). I got the sample code and adapted it (below). But when I run the code, I get a java.lang.NullPointerException exception. I've tried adjusting the number and direciton of the slashes (forward and backward) in the filename. Nothing seems to work. Please could you help???
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JFileChooser;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import java.lang.Object;
import uk.co.caprica.vlcj.mrl.FileMrl;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class TestPlayer {
private final JFrame frame;
private EmbeddedMediaPlayerComponent mediaPlayer;
public static void loadLibs(){
NativeLibrary.addSearchPath(
RuntimeUtil.getLibVlcLibraryName(), "C:/Program Files/VideoLAN/VLC/"
);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}
public static void main(final String[] args){
loadLibs();
final String mrl = "file://C:/Test.mov";
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestPlayer().run(mrl);
}
});
}
public TestPlayer(){
frame = new JFrame("test VLCJ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100,100);
frame.setSize(600,400);
frame.setVisible(true);
}
private void run(String mrl){
System.out.println(mrl);
try{
mediaPlayer.getMediaPlayer().playMedia(mrl);
}catch(Exception e){
System.err.println(e.toString());
}
}
}
I'm using VLC version 2.0.2 and VLCJ 2.1.0 sources and JDK 1.7 on windows 32 bit. I hope it's something simple...
It looks like you are using mediaPlayerwithout ever initializing it, thus causing a NullPointerException in run().
Try initializing it in your constructor.

Categories

Resources