How to make full screen java applets? - java

I am designing a psychology experiment with java applets. I have to make my java applets full screen. What is the best way of doing this and how can I do this.
Since I haven't been using java applets for 3 years(The last time I've used it was for a course homework :) ) I have forgotten most of the concepts. I googled and found that link:
Dani web
But in the method described in above link you have to put a JFrame inside the applet which I have no idea how to do it.
Whatever I need a quick and dirty method b'cause I don't have much time and this is the reason why I asked it here.
Thanx in advance

The obvious answer is don't use applets. Write an application that uses a JFrame or JWindow as its top-level container. It's not a huge amount of work to convert an applet into an application. Applets are designed to be embedded in something else, usually a web page.
If you already have an applet and want to make it full screen, there's two quick and dirty hacks:
1). If you know the screen resolution, just set the applet parameters to be that size in the HTML and then run the browser in full screen mode.
2). Run the applet in appletviewer, rather than a web page, and maximise the appletviewer window.

Why not just open a new Frame from the applet (either from the "start()" method or, preferably, after the user presses an "open" button) and set it to be maximized?
JFrame frame = new JFrame();
//more initialization code here
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(dim.width, dim.height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Don't forget: The JFrame should be created and opened from the EDT. Applet start() is not guaranteed to be called on that thread, so use SwingUtilities.invokeLater(). Of course, if you opt for the button route, button listener is called on the EDT, so you should be safe.

I think you want to use WebStart. You can deploy from a browser but it is otherwise a full blown application. There are a few browserish security restrictions, but, as you're using an Applet currently, I think I can assume they're not a problem.

I've found a solution for this problem that works fine. Tested in Linux 64 bits (Chrome and Firefox) and in Windows 7 64 bits (Chrome and Explorer)
The only problem has been that my applet uses all the space in the browser and when the user switch off the full screen mode, the applet is not scaled to the browser size. The solution has been to keep the previous size of the applet before to enter in a fullscreen mode and then, set this size when the applet returns to the normal mode:
public void setFullScreen() {
if (!this.fullscreen) {
size = this.getSize();
if (this.parent == null) {
this.parent = getParent();
}
this.frame = new Frame();
this.frame.setUndecorated(true);
this.frame.add(this);
this.frame.setVisible(true);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = ge.getScreenDevices();
devices[0].setFullScreenWindow(this.frame);
this.fullscreen = true;
} else {
if (this.parent != null) {
this.parent.add(this);
}
if (this.frame != null) {
this.frame.dispose();
}
this.fullscreen = false;
this.setSize(size);
this.revalidate();
}
this.requestFocus();
}

Related

Adding JCEF Browser in jPanel within Netbeans Platform Application

I'm working on a Netbeans Platform application running on Java 11 in which I'd like to use the chromium browser from the JCEF project. (org.jcef)
I've already implemented the browser within an org.openide.windows.TopComponent and that works just fine by implementing it in the constructor like so:
public BrowserTopComponent() {
initComponents();
CefSettings settings = new CefSettings();
settings.windowless_rendering_enabled = false;
File jcef_helper = InstalledFileLocator.getDefault().locate(
"modules/lib/jcef_helper.exe",
"com.mycompany.nbm.browser",
false);
settings.browser_subprocess_path = jcef_helper.getAbsolutePath();
modules_path = jcef_helper.getAbsolutePath().split("modules")[0] + "modules";
cefApp_ = CefApp.getInstance(settings);
client_ = cefApp_.createClient();
browser_ = client_.createBrowser(HOME, false, false);
browerUI_ = browser_.getUIComponent();
add(browerUI_, BorderLayout.CENTER);
}
Now I'd like to include the browser in another TopComponent but not in its entire area, but instead within just one jPanel.
Theoretically that should be possible by exchanging add(browerUI_, BorderLayout.CENTER); from the previous code with:
jPanelBrowser.add(browerUI_, BorderLayout.CENTER);
jPanelBrowser.validate();
That however did not work at all. It doesn't throw any errors, it just doesn't do anything.
If anyone has any experience in making jcef work in such a scenario, any help would be greatly appreciated!
I ran into a similar issue and found that when you are adding it to a JPanel you have to set the size of the client.
client_.setSize(800, 600)
Once I did that it showed for me.

Swing Paint Issues On Secondary Monitor?

I recently ran into an issue that I cannot explain. Hopefully someone knows what I can do to resolve my issue. I have a dual monitor machine running Windows 7 64-bit. Both monitors are identical models and settings. The primary monitor is on the right. I am using JRE 1.8.0_131
The issue I am seeing is that recently I discovered I am no longer able to run my Java Swing application on my second monitor. This was working perfectly fine before, as in I could move my application between both monitors, resizing and switching to/from maximized with no problems. Now whenever my application is on my second monitor, all I see is a frame that shows the part of my desktop background that is behind the frame
Below is a small sample program that creates a frame for each monitor. The frame on my primary monitor looks fine. The one on my secondary monitor is messed up like I mentioned. Simply moving the bad frame to my primary monitor does nothing to fix it but if I minimize then restore it looks fine (i.e. if I force the frame to repaint on the primary monitor it looks fine). Similarly, moving the good frame to the secondary monitor and forcing a repaint results in the bad frame
My JRE has not been updated in months so that does not seem like the issue. As an experiment I tried using JDK 1.7.0_17 but it has the same results. My machine got a Windows update yesterday which maybe coincidentally is when I noticed this issue. I am not saying that is the issue, just noting the information I have
Anyhow, any thoughts or suggestions would be greatly appreciated. This issue is annoying since dual monitor support is helpful for having my application and Eclipse visible at the same time, as well as the fact that my application has multiple frames which I placed one per monitor
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
for (final GraphicsDevice device : GraphicsEnvironment
.getLocalGraphicsEnvironment().getScreenDevices())
{
final DisplayMode displayMode = device.getDisplayMode();
LOGGER.debug(
"testSwing: device: {}, ID string: {}, isFullScreenSupported: {}, "
+ "displayModeWidth: {}, displayModeHeight: {}, "
+ "displayModeBitDepth: {}, displayModeRefreshRate: {}", device,
device.getIDstring(), device.isFullScreenSupported(),
displayMode.getWidth(), displayMode.getHeight(), displayMode.getBitDepth(),
displayMode.getRefreshRate());
if (GraphicsDevice.TYPE_RASTER_SCREEN == device.getType())
{
final GraphicsConfiguration configuration =
device.getDefaultConfiguration();
final JFrame frame = new JFrame("Test Frame", configuration);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(
new JLabel(device.getIDstring(), SwingConstants.CENTER));
final Rectangle screenBounds = configuration.getBounds();
frame.setBounds((screenBounds.x + (screenBounds.width / 2)) - 100,
(screenBounds.y + (screenBounds.height / 2)) - 100, 200, 200);
frame.setVisible(true);
}
}
}
});
NOTE: LOGGER is just a SLF4J logger which I added only to see if there was any useful information I could gather. This can be removed when running as it has no effect on the issue described above
Output from running this on my machine:
testSwing: device: Win32GraphicsDevice[screen=0], ID string: \Display0, isFullScreenSupported: true, displayModeWidth: 1920, displayModeHeight: 1200, displayModeBitDepth: 32, displayModeRefreshRate: 59
testSwing: device: Win32GraphicsDevice[screen=1], ID string: \Display1, isFullScreenSupported: true, displayModeWidth: 1920, displayModeHeight: 1200, displayModeBitDepth: 32, displayModeRefreshRate: 59
It is happening because moving your application has contents which is not updating when it is moving to another monitor and still trying to get data from initial monitor.
Try this link. Its about displaying JFrame on multiple monitors. Hope this will help.
how to display JFrame in full screen display mode at a multi-monitor environment?

How to add a seekbar to a video played using vlcj in Java Swing?

I’ve trimmed down the code to only the relevant parts and posted it below. The code works fine. The video plays when you run it but it doesn’t have a seekbar.
public class Screen {
//JFrmae
private JFrame frame;
// Panel which I add the canvas to
private JPanel pVid = new JPanel();
// Canvas
Canvas canvas = new Canvas();
// Embedded Media Player
EmbeddedMediaPlayer emp;
/**
* Create the application.
*/
public Screen() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//Frame
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Adding the panel to the frame
frame.getContentPane().add(pVid);
//Adding the canvas to the panel
pVid.add(canvas);
//Setting canvas size
canvas.setSize(715, 402);
//Loading the VLC native library
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "lib");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
//Initializing the media player
MediaPlayerFactory mpf = new MediaPlayerFactory();
//Misc
emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(frame));
emp.setVideoSurface(mpf.newVideoSurface(canvas));
//Video file name and playing
String file = "video.mp4";
emp.prepareMedia(file);
emp.play();
//pack method
frame.pack();
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen window = new Screen();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I’ve looked for an answer online for the last 4 days. Finally I decided to ask here. The official website for vlcj has pictures of a vlcj player they’ve made. There is a seekbar in those pictures. Link to the webpage which has the pics: http://capricasoftware.co.uk/#/projects/vlcj
They have a number of useful tutorials there but they don’t have any instructions for adding the seekbar.
Then I tried downloading their vlcj-player project from their GitHub page. It showed an error because it couldn’t resolve the “com.google.common.collect.ImmutableList” which is supposed to be imported. (At the moment I’m reading about ImmutableList and stuff and see if there’s a way to fix it.) Since I couldn’t figure that out yet, I looked for a class named seekbar or the like in their project. I couldn’t find any.
I also searched elsewhere online for the answer but I just couldn’t find it. I’d really appreciate any help. Thank you.
Edit:
(This edit is in response to the suggestion given to me by #caprica. Read their comment to this question and my reply to that in the comment to understand what I'm talking about here in this edit. I think it'll be useful for others in the future.)
All right, there must have been some problem with my Eclipse or computer. (I’ll type out how I fixed it at the end of this comment.) It’s working now. I’ll type out what I did step by step so that may be it’ll be useful to others in the future to download and install the project.
Download the project.
Import it as a Maven project. (Import > Maven > Existing Maven Project)
Now in Eclipse right click the imported project and select Run As > Maven Install
And that’s it. Now you can just run the project normally. If you don’t know how to run the project, do it like this. Right click the project and select Run As > Java Application and then Select VlcjPlayer – uk.co.caprica.vlcplayer.
Alternatively you can open the class where the main method is and run it. VlcjPlayer class is where the main method is located. The class is in the package uk.co.caprica.vlcplayer.
The problem I faced was that somehow all the necessary files didn’t get downloaded when I ran it as Maven Install. But it worked fine in another computer. Since I knew where the files are downloaded to, I just copied the folder from that PC and put it in the same place in my PC. The folder name is ‘repository’. It’s location is C:\Users\User Name\ .m2. Perhaps Eclipse in this PC has some problem. I’ll reinstall it later to avoid problems in the future.
And this may be useful, the VLC that’s installed in this PC is 64 bit. Not sure if that makes a difference but mentioning it just in case.
Now that the app is working fine I will see the code and see how the seekbar is made. Thanks a lot #caprica for telling me that I should import it as a Maven project. :)
The Basic Controls tutorial shows the essential approach: Add a panel of buttons to the frame and give each button an ActionListener that invokes the relevant media player command. As an example, this notional Rewind button would "skip backwards 10 seconds (-10,000 milliseconds)."
JPanel controlsPane = new JPanel();
JButton rewindButton = new JButton("Rewind");
rewindButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.getMediaPlayer().skip(-10000);
}
});
controlsPane.add(rewindButton);
frame.add(controlsPane, BorderLayout.SOUTH);
The software design is up to you, but you should at least be aware of
JToolBar, seen here and here.
Action, seen here and cited here.
Timer, seen here as a way to repeat an Action.
All right, guys. I’ve figured out how to do it. I’m not sure how it was done in the official Vlcj project but I’ve figured out my own simple way by learning from the official project.
It just takes a few lines of code. It’s very simple.
These are the steps you have to follow:
Create a JSlider.
To the JSlider, add a mouseMotionListener (‘mouseDragged’ to be exact).
Inside that put in the code which would update the video position based on
the change in the JSlider.
Create a Timer.
Put the code inside it to set the value of the JSlider based on the position
of the video.
And that’s it!
This is the code. It comes inside the initialize() method which you can see in the code I’ve given in the question. (And of course you'll also have to create the JSlider and add it to the panel. I haven't shown the code since it's simple.)
js.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (js.getValue() / 100 < 1) {
emp.setPosition((float) js.getValue() / 100);
}
}
});
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
js.setValue(Math.round(emp.getPosition() * 100));
}
});
timer.start();
Some explanation.
The value you get when you use emp.getPosition always seems to be in decimals. It’s something like 0.1334344 at the start of the video and it’s something like 0.998988 at the end. But the value of JSlider is in int. From 0 to 100. So in the mouseMotionListener added to the JSlider I’ve converted the int value of the JSlider to float by dividing it by 100.
And in the action listener inside the timer I’ve multiplied the value of the video position by 100 and then rounded it off to make it an int value. So that value can be set in the JSlider to make it move in sync with the video.
I’m sure the code is rudimentary and there could be some best practices which I may not have followed. Sorry about that but I’m just getting into java by learning the stuff which I find interesting. Those who are good at java and have used such code in an actual project can comment below with how it can be improved.

Minimizing the application in windows problem

I've wrote a simple application to store some text in a derby DB. I have 2 button each one creating a new inputDialog. My problem is that when I run the program on my Ubuntu PC all is well. When I run it on a windows 7 PC when the input dialog is displayed the whole thing is minimized and hidden from the user. So each time I want some input from the user he has to restore the application. And the other problem is that the program doesn't appear in the alt-tab menu too. Here is the code that I use to display the dialog:
String s = (String) JOptionPane.showInputDialog(this, "Моля въведете име:");
All help will be greatly appreciated.
I tried the following code - directly from main() via eclipse running on Windows 7 64-bit. The JFrame remains on display, even if I try otherwise.
JFrame f = new JFrame();
f.setSize(750, 500);
f.show();
JOptionPane.showInputDialog(f, "hello", "there");
System.out.println("hi");
Try this, and if you get the same result then at least we know it's a windows issue that we're dealing with rather than a Java issue.
EDIT:
After looking through your code, I found the offending line. Also as a side note, you should generally call setVisible() after you have done configuring your window. This is especially true with my code, as it would throw an exception if you try to call setUndecorated() after you have displayed the window.
Your Code:
this.setVisible(true); //This should be called after you finish configuration
device.setFullScreenWindow(this); //This is the problem!!!
Instead you should use:
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setVisible(true);
If you want to have your window fullscreen then use:
this.setUndecorated(true);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setVisible(true);

How does NetBeans' Splash Screen feature work?

New to NetBeans and just noticed that in the File >> Project Properties >> Application dialog there is a text field labeled Splash Screen that allows you to specify a path to an image that you would like displayed when your program is launching.
I want to customize the way my splash screen works (adding a progress bar, etc.) and would like to code it from the ground up but don't know where to start. What are the best practices for Java/Swing-based splash screens?
Thanks for any and all input!
The project properties -> Application -> Splash Screen allows you to add an image to an application. This property sets a value in the MANIFEST.MF called SplashScreen-Image: e.g. SplashScreen-Image: META-INF/GlassFish316x159.jpg This property will automatically cause the image to display as a splash screen. It does not work inside NetBeans, and must be run outside the IDE.
There is a tutorial Splash Screen Beginner Tutorial that details how to use it more detail. The tutorial was done for NetBeans 6.8, but will work on 7.2.1 which is the latest at the time of this post.
I'm not sure how NetBeans does it, but Splash Screens are supported by the JRE since version 6. See http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/splashscreen/
Splash screen is just a instance of java.awt.Window or undecorated javax.swing.JFrame.
To create window just say new Window(null), then set size and position (using tookit you can calculate where the screen center is) and then say window.setVisible(true)
Due to this is your own window you can do what you want: set layout, image, add process bar to the SOUTH etc.
You can also use JFrame: new JFrame().setUndecorated(true)`
There are a couple of ways to do this.
To do a simple splash screen (an image) you can specify this in the command line of you java application.
Here is a simple example
java -splash:<file name> <class name>
However, if you want a progress bar, you are going to have to do something a little more complicated, and write some code yourself. This is done in the following way.
Create a JWindow (or Window or undecorated JFrame) component with your splash screen elements
Set it to visible
Do the rest of your Swing GUI startup code
Set your JFrame to visible, then immediately follow with setting the JWindow to visible(false)
This should show the splash almost immediately, and then hide once the your application is fully loaded.
To see some splash screen code, take a look here. The implementation in the link only shows how to achieve what you can with the -splash command, but it will give you a good start to also include the progress bar that you requested.
I hope this helps you, it is a small example of how to create yourself a simple splash screen using a dummy Progress Bar:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class SplashScreen extends JWindow
{
private static JProgressBar progressBar = new JProgressBar();
private static SplashScreen execute;
private static int count;
private static Timer timer1;
public SplashScreen()
{
Container container = getContentPane();
container.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new javax.swing.border.EtchedBorder());
panel.setBackground(new Color(255,255,255));
panel.setBounds(10,10,348,150);
panel.setLayout(null);
container.add(panel);
JLabel label = new JLabel("Hello World!");
label.setFont(new Font("Verdana",Font.BOLD,14));
label.setBounds(85,25,280,30);
panel.add(label);
progressBar.setMaximum(50);
progressBar.setBounds(55, 180, 250, 15);
container.add(progressBar);
loadProgressBar();
setSize(370,215);
setLocationRelativeTo(null);
setVisible(true);
}
public void loadProgressBar()
{
ActionListener al = new ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
count++;
progressBar.setValue(count);
if (count == 50){
timer1.stop();
execute.setVisible(false);
//load the rest of your application
}
}};
timer1 = new Timer(50, al);
timer1.start();
}
public static void main (String args[]){
execute = new SplashScreen();
}
}
Cheers!
Also consider to build your application on top of the NetBeans Platform (a Swing-based RCP). One of the many benefits: it comes with a customizable splash screen with progress bar.
Sample progress bar:
http://platform.netbeans.org/tutorials/nbm-paintapp.html#wrappingUp
Port a Swing application to the NetBeans Platform:
http://platform.netbeans.org/tutorials/60/nbm-porting-basic.html
Further links:
http://netbeans.org/features/platform/index.html
http://netbeans.org/features/platform/all-docs.html
If your application is build using NetBeans Platform, then here's a tutorial about splash screen customisation: http://wiki.netbeans.org/Splash_Screen_Beginner_Tutorial
There is a sample Javafx equivalent of Splash screen. However this splash screen is basically a java swing applet that is called from javafx to be displayed to the user and simulates more or less eclipse and netbeans splash screen using progress bar and titles for the loaded contents. This is the link.
You must be able to get the code and separate out the splash screen code written in java swings and use it for yourself.
This is a custom java swings splash screen. and hence to center the splash screen it uses the traditional
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = l.getPreferredSize();
setLocation(screenSize.width / 2 - (labelSize.width / 2),
screenSize.height / 2 - (labelSize.height / 2));

Categories

Resources