I'm trying to make a full-screen GUI using Java which, on the JFrame, has 2 JPanel's, one of which only takes roughly 0.10 of the screen width. When I place these panels on the frame, using the same height, they appear to display with a different height on Linux & Mac OS but they appear okay on Windows. Does anybody have any idea on how to make both panels the same height for Linux & Mac OS? I re-made the problem quickly using WindowBuilder for posting here.
package View;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import controller.ExitActionListener;
import java.awt.event.ActionListener;
public class TestFrame2 {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame2 window = new TestFrame2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestFrame2() {
initialize();
}
private void initialize() {
frame = new JFrame();
GraphicsDevice device = frame.getGraphicsConfiguration().getDevice();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setSize((int)(frame.getWidth()*0.1), frame.getHeight());
panel.setBackground(Color.BLACK);
frame.getContentPane().add(panel);
JPanel panel1 = new JPanel();
panel1.setBackground(Color.RED);
panel1.setSize(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(panel1);
// temporary close button
ActionListener exitActionListener = new ExitActionListener();
JButton exit = new JButton("Exit System");
exit.setBounds(150 ,200, 150, 100);
exit.addActionListener(exitActionListener);
panel1.add(exit);
//Set program as full screen
device.setFullScreenWindow(frame);
}
}
Related
Im trying to encapsulate the GUI calls to a single class. My window appears but the background remains the default color instead of red.
ChatProgram.java
package ChatPkg;
public class ChatProgram {
/**
* Launch the application.
*/
public static void main(String[] args) {
ChatWindow.initialize();
ChatWindow.RunWindow();
}
}
ChatWindow.java
package ChatPkg;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
public final class ChatWindow {
static JFrame frame;
/**
* Create the application.
*/
private ChatWindow() { }
public static void RunWindow() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Initialize the contents of the frame.
*/
public static void initialize() {
frame = new JFrame("Chat program");
frame.setBounds(100, 100, 450, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox chckbxCvbc = new JCheckBox("cvbc");
frame.getContentPane().add(chckbxCvbc);
// Set background color
frame.getContentPane().setBackground(Color.red);
}
}
Yes i am new to Java and none of the google results solved my problem.
You should NOT add GUI components directly to the content pane of the JFrame. Also, you shouldn't modify its properties (like you tried changing the background).
You always need a JPanel that acts as a container on which the graphical elements are added. Here is how you could write your initialize function:
public static void initialize() {
frame = new JFrame("Chat program");
frame.setBounds(100, 100, 450, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JCheckBox chckbxCvbc = new JCheckBox("cvbc");
panel.add(chckbxCvbc);
// Set background color and add panel to the Jframe
panel.setBackground(Color.RED);
frame.getContentPane().add(panel);
}
I have a class which create a JFrame with an image but everytime I create the class and run the method to instantiate it, it doesn't appear. However, I have noticed that if I was to create the exact same class and run the same method in the main then the frame appears.
This is most of the code from the class with the JFrame that I am trying to create:
JFrame myFrame= new JFrame();
public void CreateFrame()
{
JLabel background=new JLabel(new ImageIcon("image.jpg"));
myFrame.add(background);
background.setLayout(new FlowLayout());
myFrame.setLayout(new GridLayout(1,1));
myFrame.setSize(360,250);
myFrame.setUndecorated(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
myFrame.setLocation((dim.width/2-170), dim.height/2-125);
myFrame.pack();
myFrame.setVisible(true);
}
If I run the code
MyClass mc = new MyClass();
mc.CreateFrame();
in a method in another class it doesn't come up. However, if I run the exact same code in a main method, it works.
For example, this doesn't work:
Example 1
public class otherClass extends JFrame
{
public void MethodA()
{
MyClass mc = new MyClass();
mc.CreateFrame();
}
public static void main(String[] args)
{
otherClass oc = new otherClass();
oc.MethodA();
}
}
but this does work
Example 2
public class otherClass extends JFrame
{
public void MethodA()
{
//CODE
}
public static void main(String[] args)
{
otherClass oc = new otherClass();
oc.MethodA();
MyClass mc = new MyClass();
mc.CreateFrame();
}
}
Can anyone see where I'm going wrong? Sorry if a stupid mistake, I'm still getting to grips with Java.
Thanks
EDIT
import javax.swing.ImageIcon;
import javax.swing.JWindow;
import javax.swing.JLabel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.util.Timer;
import java.util.Date;
import javax.swing.JFrame;
public class MyClass
{
JFrame homeFrame = new JFrame();
public void createFrame()
{
JLabel background=new JLabel(new ImageIcon("images.jpg"));
myFrame.add(background);
background.setLayout(new FlowLayout());
myFrame.setLayout(new GridLayout(1,1));
myFrame.setSize(360,250);
myFrame.setUndecorated(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
myFrame.setLocation((dim.width/2-170), dim.height/2-125);
myFrame.setAlwaysOnTop(true);
myFrame.pack();
myFrame.setVisible(true);
durationOfTime();
}
public void durationOfTime()
{
MainProgram mp = new MainProgram();
long startTime = System.currentTimeMillis();
long elapsedTime = 0L;
int count =0;
while (elapsedTime < 2*1000)
{
if(count==0)
{
mp.launchInitiation();
}
count+=1;
elapsedTime = (new Date()).getTime() - startTime;
}
myFrame.setVisible(false);
mp.homeFrame.setVisible(true);
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.createFrame();
}
}
Full code from class with JFrame trying to make. I am trying to use this JFrame as a splash screen but whatever class I call
MyClass mc = new MyClass();
mc.createFrame();
from, it just doesn't appear. Two seconds do pass by before my main GUI appears up but this method is supposed to be called in a login type frame. However, I have tested it with a blank JFrame / GUI to appear upon button click also and it still doesn't appear.
EDIT2
I also previously tried this SplashScreen example by # http://examples.oreilly.com/jswing2/code/ch08/SplashScreen.java but I couldn't get it to work (same problem, appears when called from main but not when called from action listener)
import java.awt.*;
import javax.swing.*;
public class SplashScreen extends JWindow {
private int duration;
public SplashScreen(int d) {
duration = d;
}
// A simple little method to show a title screen in the center
// of the screen for the amount of time given in the constructor
public void showSplash() {
JPanel content = (JPanel)getContentPane();
content.setBackground(Color.white);
// Set the window's bounds, centering the window
int width = 450;
int height =115;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width-width)/2;
int y = (screen.height-height)/2;
setBounds(x,y,width,height);
// Build the splash screen
JLabel label = new JLabel(new ImageIcon("oreilly.gif"));
JLabel copyrt = new JLabel
("Copyright 2002, O'Reilly & Associates", JLabel.CENTER);
copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12));
content.add(label, BorderLayout.CENTER);
content.add(copyrt, BorderLayout.SOUTH);
Color oraRed = new Color(156, 20, 20, 255);
content.setBorder(BorderFactory.createLineBorder(oraRed, 10));
// Display it
setVisible(true);
// Wait a little while, maybe while loading resources
ClassToLoad ctl = new ClassToLoad();
try {
Thread.sleep(duration);
ctl.initiate();
} catch (Exception e) {}
setVisible(false);
}
public void showSplashAndExit() {
showSplash();
System.exit(0);
}
public static void main(String[] args) {
// Throw a nice little title page up on the screen first
SplashScreen splash = new SplashScreen(10000);
// Normally, we'd call splash.showSplash() and get on with the program.
// But, since this is only a test...
splash.showSplashAndExit();
}
}
I added the code in the lines with ClassToLoad and this SplashScreen is called on an action listener, what happens is the program waits the 2 seconds that I tell it to, no frame appears, and then the main class that I wanted to load while the splash screen is visible loads. I tried this method first but this didn't work which lead to me using the code listed above this edit
EDIT 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestFrame extends JFrame implements ActionListener
{
JPanel thePanel = new JPanel(null); //layout
JButton button = new JButton();
public void startGUI()
{
this.setLayout(new GridLayout(1,1));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CREATEMYPANEL();
this.add(thePanel);
this.setTitle("NO_TITLE_SET");
this.setSize(400,400);
this.setVisible(true);
this.setResizable(true);
}
public void CREATEMYPANEL()
{
button.setLocation(242,151);
button.setSize(100,50);
button.addActionListener(this);
button.setText("button");
thePanel.add(button);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
System.out.println("button has been pressed ");
SplashScreen splash = new SplashScreen(1000);
splash.showSplash();
}
}
public static void main(String[] args )
{
TestFrame tf = new TestFrame();
tf.startGUI();
}
}
An example of where I call splash screen from. Still doesn't work. Also, just a note that the image I am loading is a local image
Apologies for bad question formatting
Your code works for me except for some details I noticed:
You're calling setSize(...) and then calling pack(). Probably your image isn't being loaded and thus your JFrame has a size of 0, 0. (And thus it looks like it never appears). .pack() and .setSize(...) are mutually exclusive.
You're setting the JLabel's layout manager to FlowLayout but never adding anything to it. (You can safely remove it)
I see you're importing java.util.Timer if you want to dispose the JFrame after 2 seconds, then you should be using a javax.swing.Timer instead. Otherwise you could get problems related to threading.
Also don't forget to place your program on the Event Dispatch Thread (EDT) as Swing is not thread safe
Following above recommendations you can have this code:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SplashscreenSample {
private JFrame myFrame;
private JLabel background;
private Timer timer;
public void createFrame() {
timer = new Timer(2000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myFrame.dispose();
#SuppressWarnings("serial")
JFrame frame = new JFrame(getClass().getSimpleName()) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timer.stop();
}
});
myFrame = new JFrame(getClass().getSimpleName());
try {
background = new JLabel(new ImageIcon(new URL("http://cdn.bulbagarden.net/upload/thumb/6/6b/175Togepi.png/250px-175Togepi.png")));
} catch (MalformedURLException e) {
e.printStackTrace();
}
myFrame.add(background);
timer.setInitialDelay(2000);
timer.start();
myFrame.setLayout(new GridLayout(1, 1));
myFrame.setUndecorated(true);
myFrame.setAlwaysOnTop(true);
myFrame.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
myFrame.setLocation((dim.width/2-170), dim.height/2-125);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SplashscreenSample().createFrame());
}
}
Or you can use the Splashscreen class...
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class SplashScreen extends JWindow {
private int duration;
public SplashScreen(int d) {
duration = d;
}
// A simple little method to show a title screen in the center
// of the screen for the amount of time given in the constructor
public void showSplash() {
ImageIcon icon = null;
try {
icon = new ImageIcon(new URL("http://www.cqsisu.com/data/wallpapers/5/718448.gif"));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JPanel content = (JPanel) getContentPane();
content.setBackground(Color.white);
// Set the window's bounds, centering the window
int width = icon.getIconWidth();
int height = icon.getIconHeight();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width - width) / 2;
int y = (screen.height - height) / 2;
setBounds(x, y, width, height);
// Build the splash screen
JLabel label = new JLabel(icon);
JLabel copyrt = new JLabel("Copyright 2002, O'Reilly & Associates", JLabel.CENTER);
copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12));
content.add(label, BorderLayout.CENTER);
content.add(copyrt, BorderLayout.SOUTH);
Color oraRed = new Color(156, 20, 20, 255);
content.setBorder(BorderFactory.createLineBorder(oraRed, 10));
// Display it
setVisible(true);
// Wait a little while, maybe while loading resources
loadResources();
setVisible(false);
}
public void loadResources() {
TestFrame tf = new TestFrame();
try {
Thread.sleep(duration);
tf.startGUI();
} catch (Exception e) {
}
}
public static void main(String[] args) {
SplashScreen splash = new SplashScreen(10000);
splash.showSplash();
}
}
Try creating and setting the frame visible in a constructor of the class.
Could it be that while your program is counting
while (elapsedTime < 2*1000)
{
if(count==0)
{
mp.launchInitiation();
}
count+=1;
elapsedTime = (new Date()).getTime() - startTime;
}
it is blocking for said 2 seconds and waiting for this method to finish, return back to the create method and then just finish that one?
it seems this could be a better comment, but i need 50 rep for some reason to comment.
I wanna create a simple java application, and I have some problems.
This is my main class:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("First B");
panel.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SecWindow SW = new SecWindow();
//-----
}
});
}
}
Secound class:
import javax.swing.JButton;
import javax.swing.JPanel;
public class SecWindow {
public SecWindow() {
SecPanel();
}
public void SecPanel() {
JPanel panel2 = new JPanel();
JButton btnNewButton_2 = new JButton("Sec B");
panel2.add(btnNewButton_2);
}
}
How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().
How can I do this: when I press the "First B" I wanna delete the first panel and create a new one class SecWindow().
You should be using a CardLayout. The CardLayout will allow you to swap panels in the frame.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example uses a combo box to swap the panels so you just need to move that code to the ActionListener of your button.
try{
secWindow secondWindow = new secWindow();
secondWindow.frame.setVisible(true);
window.frame.setVisible(false);
} catch (Exception e) {
e.printStackTrace();
This will hide first window and show second one.
You can not completely "delete" object that has main method in it. your app will start and end in main method.
instead you can make new class and transfer main method over there
I want to show a changing image on my frame. The imagepath is always the same, but the image will be getting overwritten every 10 seconds from another program.
The problem is that the image is not changing when I overwrite it with another image with the same name. So in my understanding: Compiler looks every look in the path and gets the image -> when the image changed it will be changed on the frame!
I hope you understand my problem and somebody could help me.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI extends JFrame{
public ImageIcon imageBar;
public JLabel labelimage1;
private JLabel labelimage2;
private JLabel bar1 = new JLabel();
private JLabel bar2 = new JLabel();
private JLabel bar3 = new JLabel();
private JLabel bar4 = new JLabel();
private JLabel bar5 = new JLabel();
private JButton buttonBar1 = new JButton("1");
private JButton buttonBar2 = new JButton("2");
private JButton buttonBar3 = new JButton("3");
private JButton buttonBar4 = new JButton("4");
private JButton buttonBar5 = new JButton("5");
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JPanel panel3 = new JPanel();
private JFrame window = new JFrame("Interface");
public GUI(){
//set the layouts
panel1.setLayout(new GridLayout(1, 2));
panel2.setLayout(new GridLayout(2, 1));
panel3.setLayout(new GridLayout(2, 5));
//place Panel2 and Panel3 in the window
panel1.add(panel2);
panel1.add(panel3);
//----Panel2
//refreshImage();
//----Panel3
panel3.add(buttonBar1); //add the bars 1-5 on panel3
panel3.add(buttonBar2);
panel3.add(buttonBar3);
panel3.add(buttonBar4);
panel3.add(buttonBar5);
//configure the frame
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setSize(800, 400);
window.getContentPane().add(panel1);
}
public void refreshImage() {
panel2.removeAll(); //delete the old panel
//panel2.repaint();
//panel2.revalidate()
DrawImage pan = new DrawImage();
panel2.add(pan);
panel2.add(labelimage2);
}
}
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class DrawImage extends JPanel implements ActionListener{
private ImageIcon image;
public DrawImage(){
image = new ImageIcon("C:\\Users\\usuario\\Desktop\\image.png");
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
image.paintIcon(this, g, 50, 50);
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
import java.io.File;
public class Main {
public static void main(String[] args) {
GUI Interface = new GUI();
while(true)
{
Interface.refreshImage();
try {
Thread.sleep(5000); //wait for 5000ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Thank you very much!
The likely cause is Java is caching the image in memory, associated with the source name. So rather then trying to reload the image again, Java simply returns the cached version.
You could use ImageIcon#getImage#flush to force Java to reconstruct the image
Problems
You are calling refreshImage from a Thread other then the Event Dispatching Thread, this could cause issues with the updating of the components and cause rendering artifacts
You are forcefully removing the DrawImage pane and adding a new instance, rather the trying to reload the image
You're calling repaint within the paintComponent method, don't do this...
You should consider using a Swing Timer, which will allow you to schedule a regular update and be notified within the context of the Event Dispatching Thread.
You could provide a simple refresh method which flushes the current ImageIcon and schedule a repaint of the panel...or you could just use a JLabel and save your self the time
An example of Image#flush
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SlideShow {
public ImageIcon imageBar;
public static void main(String[] args) {
new SlideShow();
}
public SlideShow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawImage());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawImage extends JPanel {
private ImageIcon image;
public DrawImage() {
image = new ImageIcon("D:\\thumbs\\image.png");
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
refresh();
}
});
timer.start();
}
public void refresh() {
image.getImage().flush();
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image.getImage(), 0, 0, this);
}
}
}
The problem with this, is because the image data is loaded in a background thread, it won't may no be available when the component is first repainted, which could make the component appear to flicker.
A better approach would be to use ImageIO.read, which will ensure that the image is fully loaded before the method returns, the draw back here is that could cause the application to "pause" momentary as the image is loaded, personally, I'd use the refresh method to stop the the Timer (or set the Timer to non-repeating), start a background Thread to load the image (using ImageIO.read) call repaint (which is thread safe) and restart the Timer...
Your while (true) loop risks typing up the Swing event thread locking your program. If it doesn't do that, then you risk unpredictable threading issues by making Swing calls off of the event Thread. These problems can be solved easily by your using a Swing Timer not a while true loop to do your swapping.
Rather than removing and adding components, why not simply display images as ImageIcons within a single non-swapped JLabel.
To swap images here, simply call setIcon(...) on the JLabel.
For an example of using a Swing Timer to swap images, please check out my answer to a similar question here.
For example:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TimerImageSwapper {
public static final String[] IMAGE_URLS = {
"http://imaging.nikon.com/lineup/dslr/d7000/img/sample/img_01.png",
"http://imaging.nikon.com/lineup/dslr/d7000/img/sample/img_02.png",
"http://imaging.nikon.com/lineup/dslr/d7000/img/sample/img_04.png",
"http://imaging.nikon.com/lineup/dslr/d3200/img/sample/img_08.png",
"http://imaging.nikon.com/lineup/dslr/d3200/img/sample/img_05.png",
"http://imaging.nikon.com/lineup/dslr/d3200/img/sample/img_01.png",
"http://imaging.nikon.com/lineup/dslr/d3200/img/sample/img_06.png" };
private ImageIcon[] icons = new ImageIcon[IMAGE_URLS.length];
private JLabel mainLabel = new JLabel();
private int iconIndex = 0;;
public TimerImageSwapper(int timerDelay) throws IOException {
for (int i = 0; i < icons.length; i++) {
URL imgUrl = new URL(IMAGE_URLS[i]);
BufferedImage image = ImageIO.read(imgUrl);
icons[i] = new ImageIcon(image);
}
mainLabel.setIcon(icons[iconIndex]);
new Timer(timerDelay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
iconIndex++;
iconIndex %= IMAGE_URLS.length;
mainLabel.setIcon(icons[iconIndex]);
}
}).start();
}
public Component getMainComponent() {
return mainLabel;
}
private static void createAndShowGui() {
TimerImageSwapper timerImageSwapper;
try {
timerImageSwapper = new TimerImageSwapper(5 * 1000);
JFrame frame = new JFrame("Timer Image Swapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(timerImageSwapper.getMainComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
package javaapplication1;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setTitle("Frame");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(800, 600, 32, 60));
frame.setVisible(true);
JButton btn = new JButton();
btn.setText("Button");
JPanel panel = new JPanel();
panel.add(btn);
frame.add(panel);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "JOptionPane");
}
});
}
}
When I click the button, the application which is set to full screen will go to taskbar/minimized, so I need to click it first in the taskbar before seeing the JOptionPane that I triggered. What do you think is the problem with this? I'd like it to run smoothly without being minimized or going to taskbar. Looking forward for your answers. Thanks in advance. Or is there any other alternative to this?
That code works for me, though you might try this variant with 2 changes.
It creates and shows the GUI on the EDT.
It uses the content pane of the frame as the parent of the JOptionPane
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaApplication1 {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame frame = new JFrame();
frame.setTitle("Frame");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(800, 600, 32, 60));
frame.setVisible(true);
JButton btn = new JButton();
btn.setText("Button");
JPanel panel = new JPanel();
panel.add(btn);
frame.add(panel);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(frame, "JOptionPane");
JOptionPane.showMessageDialog(frame.getContentPane(), "JOptionPane");
}
});
}
};
SwingUtilities.invokeLater(r);
}
}
Update
When I add the following lines to the beginning of the source seen above..
System.out.println(System.getProperty("java.version"));
System.out.println(System.getProperty("java.vm.version"));
..the output & result is as follows.
Running in 1.7
Result: Failure as described in the question.
1.7.0_09
23.5-b02
Running in 1.6
Result: Success with no unusual artifacts or behavior.
1.6.0
1.6.0-b105
Analysis
Note that other results from comments suggest the behavior changed some time between that early 1.6 version, and 1.6.0_25. It seems like a regression bug. The OP should check the bug database & if nothing likely shows up, lodge a new report.
JOptionPane.showInternalMessageDialog(frame.getContentPane(), "JOptionPane");