How to implement splash screen Java [duplicate] - java

This question already has answers here:
Make splash screen with progress bar like Eclipse
(2 answers)
Closed 9 years ago.
i get this source code for creating splash screen and thread management in Java. But i don't know how to implement it.
public class SplashWindow extends JWindow {
public SplashWindow(String filename, Frame f, int waitTime)
{
super(f);
JLabel l = new JLabel(new ImageIcon(filename));
getContentPane().add(l, BorderLayout.CENTER);
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
Dimension labelSize = l.getPreferredSize();
setLocation(screenSize.width/2 - (labelSize.width/2),
screenSize.height/2 - (labelSize.height/2));
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
setVisible(false);
dispose();
}
});
final int pause = waitTime;
final Runnable closerRunner = new Runnable()
{
public void run()
{
setVisible(false);
dispose();
}
};
Runnable waitRunner = new Runnable()
{
public void run()
{
try
{
Thread.sleep(pause);
SwingUtilities.invokeAndWait(closerRunner);
}
catch(Exception e)
{
e.printStackTrace();
// can catch InvocationTargetException
// can catch InterruptedException
}
}
};
setVisible(true);
Thread splashThread = new Thread(waitRunner, "SplashThread");
splashThread.start();
}
}
I try to implement like this :
...
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
SplashWindow window = new SplashWindow("splash-scren.jpg", frame, 1000);
}
...
But nothing to show.
Please help me, thank you :)

Dont put :
"setVisible(true);"
In the constructor , after
SplashWindow window = new SplashWindow("splash-scren.jpg", frame, 1000);
write:
window.setVisible(true);

Related

How to escape a Java swing window in fullscreen? [duplicate]

This question already has answers here:
Full screen Window won't get keyboard input using KeyListener or KeyBoardFocusManager
(2 answers)
Closed 5 years ago.
I've built a swing window in eclipse that goes to fullscreen when opened, however it becomes impossible to toggle the fullscreen off.
I've tried researching online (I am aware of similar threads) but I've come across issues when attempting solutions.
Here is my JFrame
private void initialize()
{
frmCpStats = new JFrame();
frmCpStats.setTitle("CP Stats");
Toolkit tk = Toolkit.getDefaultToolkit();
int x =((int) tk.getScreenSize().getWidth());
int y =((int) tk.getScreenSize().getHeight());
frmCpStats.setExtendedState(JFrame.MAXIMIZED_BOTH);
frmCpStats.setSize(x, y);
frmCpStats.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCpStats.setUndecorated(true);
KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
int w = frmCpStats.WHEN_IN_FOCUSED_WINDOW;
dialog.getRootPane().registerKeyboardAction(e -> window.dispose(), k, w);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StatsDisplay window = new StatsDisplay();
window.frmCpStats.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public StatsDisplay() {
initialize();
}
Eclipse identifies errors Cannot be resolved or is not a field with VK_ESCAPE and WHEN_IN_FOCUSED_WINDOW, and dialog cannot be resolved with dialog. I'm quite unfamiliar with how swing actually works, so I haven't the foggiest idea why these errors are occurring.
You're almost there. Key Bindings works in this situation. Please note my MCVE:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class StatsDisplay {
private JFrame frmCpStats;
private void initialize() {
frmCpStats = new JFrame();
JPanel contentPane = (JPanel) frmCpStats.getContentPane();
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = contentPane.getInputMap(condition);
ActionMap actionMap = contentPane.getActionMap();
KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
inputMap.put(escapeStroke, escapeStroke.toString());
actionMap.put(escapeStroke.toString(), new AbstractAction() {
#Override
public void actionPerformed(ActionEvent arg0) {
frmCpStats.dispose();
}
});
frmCpStats.setTitle("CP Stats");
Toolkit tk = Toolkit.getDefaultToolkit();
int x = ((int) tk.getScreenSize().getWidth());
int y = ((int) tk.getScreenSize().getHeight());
frmCpStats.setExtendedState(JFrame.MAXIMIZED_BOTH);
frmCpStats.setSize(x, y);
frmCpStats.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCpStats.setUndecorated(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StatsDisplay window = new StatsDisplay();
window.frmCpStats.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public StatsDisplay() {
initialize();
}
}
Curious as to why you're calling window.dispose() when its the frmCpStats JFrame that you're actually trying to dispose of??
Remove these code lines
frmCpStats.setExtendedState(JFrame.MAXIMIZED_BOTH);
frmCpStats.setUndecorated(true);

How to check if a JFrame is open by checking it's one of the components are visible

I have this code sample in a separate jDialog (jDialog is in the same package as that of JFrame) which used to check (using a Thread) if the jCheckBox1 in the jFrame is whether visible or not. JDialog is set to visible by clicking a JLabel (Change Password) in JFrame. I have not set the visibility of the JFrame even to false even after I click on the Change Password JLabel.
The problem I encountered is that even if the JFrame is not visible i.e when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible" and I'm more than sure that the jFrame is not visible and not running.
This is the code snippet (Thread) I have used to check the visibility of the JFrame's jCheckBox1:
LockOptions lock = new LockOptions();
private void setLocation2() {
new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lock.jCheckBox1.isVisible()) {
System.out.println("Visible");
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
And this is the Code I have written in JFrame's Change Password JLabel:
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {
Container c = new ChangePassword(this, rootPaneCheckingEnabled);
if (!c.isShowing()) {
c.setVisible(true);
hideMeToSystemTray();
this.requestFocusInWindow();
}
}
But when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible"
I have attached a Screenshots of both JFrame and JDialog
JFrame containing jCheckBox1
JDialog:
OK, let's have the simplest possible example.
The following code creates a main frame having a button to create a new frame of class LockOptionsWindow, which extends JFrame.
The class FrameDemo implements Runnable. So can it be accessed on the event dispatching thread using SwingUtilities.invokeLater as mentioned in Swing's Threading Policy. So it is possible creating a new thread checklockoptionswindow which then can check whether the new window created by the button is visible or not visible.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameDemo extends WindowAdapter implements ActionListener, Runnable {
private LockOptionsWindow lockoptionswindow;
private Thread checklockoptionswindow = new Thread();
private void showLockOptionsWindow() {
if (lockoptionswindow != null && lockoptionswindow.isDisplayable()) {
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
} else {
lockoptionswindow = new LockOptionsWindow();
lockoptionswindow.setSize(new Dimension(300, 100));
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
}
}
private void startCheckLockOptionsWindow() {
if (!checklockoptionswindow.isAlive()) {
checklockoptionswindow = new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lockoptionswindow.isVisible()) {
if (lockoptionswindow.getExtendedState() == Frame.ICONIFIED) {
System.out.println("Visible iconified");
} else {
System.out.print("Visible on screen ");
int x = lockoptionswindow.getLocation().x;
int y = lockoptionswindow.getLocation().y;
System.out.println("at position " + x + ", " + y);
}
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
checklockoptionswindow.start();
}
}
public void actionPerformed(ActionEvent e) {
showLockOptionsWindow();
startCheckLockOptionsWindow();
}
public void run() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Show LockOptions frame");
button.addActionListener(this);
Container contentPane = frame.getContentPane();
contentPane.add(button);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new FrameDemo());
}
class LockOptionsWindow extends JFrame {
public LockOptionsWindow() {
super("LockOptions frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
Edited to determine whether the LockOptionsWindow is visible iconified only or is really showed as window on the screen.

Why doesn't this Java program close on exit?

I have this webcam program that runs in a JFrame. Whenever I close the frame, it prints out "Closed" like it's supposed to, but my IDE says that is still running. Why is this and how do I fix it? I am not running any threads anywhere in the program. This doesn't have anything to do with the default close operation as I have tested for that already.
public class Webcam extends JPanel {
private static BufferedImage image;
public Webcam() {
super();
}
public static void main(String args[]) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
JFrame frame = new JFrame("Webcam");
Webcam panel = new Webcam();
// Initialize JPanel parameters
//frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(1080, 720);
frame.setContentPane(panel);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
System.exit(0);
}
});
Mat currentImage = new Mat();
VideoCapture capture = new VideoCapture(0);
if(capture.isOpened()) {
// Infinitely update the images
while(true) {
// VideoCapture returns current Mat
capture.read(currentImage);
if(!currentImage.empty()) {
frame.setSize(currentImage.width() + 40, currentImage.height() + 60);
image = panel.matrixToBuffer(currentImage);
// Update the panel
panel.repaint();
}
else {
System.out.println("Error: no frame captured");
frame.dispose();
System.exit(0);
break;
}
}
}
return;
}
Okay, while I appreciate all of the helpful comments, the issue was that the VideoCapture had an internal thread running, and adding capture.release() to my listener fixed it.

Extension of JDialog (hidden?) not showing up in front of parent JFrame?

I have an application I'm making for a game to automatically update a game client.
Once you press Launch, it will open up my DownloadFrame (extends JDialog), and will look like this:
If you click the icon for the application in the taskbar, (maybe Windows 8 is the problem?) it will minimize the application like usual. However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent. It looks like this:
Here's my code for my extension of JDialog. Apologies in advance for it being messy.
public class DownloadFrame extends JDialog implements Runnable {
private static final long serialVersionUID = -8764984599528942303L;
private Background frame;
private ImageIcon[] gifs;
private JLabel spinner;
public DownloadFrame() {
super(Loader.application, false);
setLayout(null);
setUndecorated(true);
setAutoRequestFocus(true);
new Thread(this).start();
generateBackground();
generateButton();
generateGif();
}
private void generateBackground() {
frame = new Background("sub_background.png");
setSize(frame.getWidth(), frame.getHeight());
setBackground(new Color(1.0f, 1.0f, 1.0f, 0.0f));
setLocationRelativeTo(null);
setLocation(this.getX(), this.getY() + 5);
setLayout(null);
setContentPane(frame);
}
private void generateGif() {
gifs = Utils.generateGifImages();
spinner = new JLabel(gifs[0]);
spinner.setBounds(70, 30, gifs[0].getIconWidth(), gifs[0].getIconHeight());
add(spinner);
}
private HoverableButton cancel;
public HoverableButton getCancelButton() {
return cancel;
}
private void generateButton() {
cancel = new HoverableButton(Settings.CANCEL_BUTTON, 75, 145);
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
/*
* TODO -
* stop the download in progress
*/
for (HoverableButton button : Loader.application.getPrimaryButtons()) {
button.setActive(true);
button.setVisible(true);
}
dispose();
}
});
add(cancel);
}
private int cycleCount;
private void cycleGif() {
if (spinner == null) {
return;
}
cycleCount++;
if (cycleCount > 7) {
cycleCount = 0;
}
spinner.setIcon(gifs[cycleCount]);
}
#Override
public void run() {
while (true) {
cycleGif();
try {
Thread.sleep(100L);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
In case it's needed, here's my usage of it. Most of the stuff can be ignored I'm sure, it's simply there to hide the four buttons while the download is in progress.
((HoverableButton) components[2]).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
HoverableButton source = (HoverableButton) components[2];
if (source.isActive()) {
try {
Thread.sleep(500L);
} catch (Exception ex) {
ex.printStackTrace();
}
if (panel == null) {
panel = new DownloadFrame();
panel.setVisible(true);
} else {
panel.setVisible(true);
panel.getCancelButton().removeHighlight();
}
for (HoverableButton button : getPrimaryButtons()) {
button.setActive(false);
button.setVisible(false);
button.removeHighlight();
}
/*
* TODO -
* handle checking for updates / downloading updates
*/
}
}
});
However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent
Yes. When you create the JDialog, you need to specify the "owner" JFrame of the dialog in the constructor.
So you must create and make the JFrame and make the frame visible before you create the dialog.

Kill thread on close

I have a constructor of a JFrame where I have a Thread(t1) which is running thanks to a
while(true)
I would like to know how to implement my JFrame so it can kill the thread when I close it, because t1 need to be running when the JFrame is active
EDIT:
Here is the code:
public class Vue_Session extends JFrame {
private JPanel contentPane;
private int idsess;
private User u;
public Vue_Session(User us, int id) {
this.u = us;
this.idsess = id;
toServ t=new toServ(idsess);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) screenSize.getWidth() / 2 - 800 + (800 / 2), 90, 800,
600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
Vue_Idee vueIdee = new Vue_Idee(this.idsess, this.u);
contentPane.add(vueIdee, BorderLayout.SOUTH);
Vue_IdeeSession vueSess = new Vue_IdeeSession(this.idsess);
contentPane.add(vueSess, BorderLayout.CENTER);
Thread t1 = new Thread( new Runnable(){
public void run(){
while(true){
try{
Thread.sleep(500);
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.getIdee();
vueSess.act();
revalidate();
}
}
});
t1.start();
}
You can handle it with a boolean variable like
boolean end = false;
while (!end){...}
Also I suggest you use ExecutorService or ForkJoinPool so you can simply control your tasks, threads, etc
EDIT:
boolean end = false;
new Thread(() -> {
while (!end) {
//...
}
}).start();
and this is where you should end your tasks:
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
end = true;
System.exit(0);
// or this.dispose();
}
});
good luck :)
It's a controversial topic but in general I would replace the while (true) construct with
while(!Thread.currentThread().isInterrupted()){
try{
Thread.sleep(500);
}catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
t.getIdee();
vueSess.act();
revalidate();
}
More information on this topic can be found here:
http://www.javaspecialists.eu/archive/Issue056.html
Okay, here was the answer:
I needed to add en WindowListenne:
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent b) {
t1.stop();
dispose();
}
});
And also:
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
First, you need to make the thread kill-able. To do this, instead of looping forever, loop as long as certain looping flag is true.
After that, you need to create a listener that gets called whenever the user closes the frame. You can use WindowAdapter to do this. When the listener is called, set the looping flag to false. Once the thread dies, you can safely terminate the program.
For example:
public class Vue_Session extends JFrame {
Thread thread = null;
boolean threadAlvie = true;
boolean threadDie = false;
public Vue_Session(User us, int id) {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
threadAlive = false;
// Wait until the thread dies
while (!threadDie) {
// Sleep for 100 milliseconds.
Thread.sleep(100);
}
System.exit(0);
}
});
thread = new Thread(new Runnable() {
public void run(){
while (threadAlive){
// do something
}
threadDie = true;
}
});
thread.start();
}
}

Categories