Java: JFrame image only appears when maximizing window - java

I am trying to get an image to appear inside of my JFrame. However, this image only appears when I maximize the GUI window. My image is located inside my src folder. I was wondering if I am implementing JFrame incorrectly.
UPDATED CODE
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JLabel(new ImageIcon("logo.png")));
frame.pack();
frame.setVisible(true);

Simple example.
The image is placed within stof package. The example makes use of ImageIO to load the image. The reason for this is two fold.
If something goes wrong, an exception is raised, so you can diagnose it
ImageIO.read won't return until the image is fully loaded. This means that, unlike ImageIcon, you know the image is available for rendering once the call returns. Just remember, if the image is large and you do this from within the event dispatching thread, you will cause the UI to "stall"
Example
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
BufferedImage image = ImageIO.read(Test.class.getResource("/stof/Background.png"));
JFrame frame = new JFrame();
frame.add(new JLabel(new ImageIcon(image)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}

Related

no icon shows on java swing in linux ubunutu

I copied the path of the image but no icon appears click on the image to see
no icon
I created simple frame and needed to include icon
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.awt.Color;
public class App {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("JFrame title goes here");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of app
frame.setResizable(false); // prevent frame from being resized
frame.setSize(700,700);
frame.setVisible(true);
try {
URL resource = frame.getClass().getResource("/games.png");
BufferedImage image = ImageIO.read(resource);
frame.setIconImage(image);
} catch (IOException e) {
e.printStackTrace();
}
frame.getContentPane().setBackground(new Color(123,50,250));
}
}

JFrame Start Up Display Delay

I am having difficulties displaying a JFrame with all of the contents showing immediately. I would like to show the JFrame with all Components already added, but the window appears to become visible out-of-focus, wait a second, then come into focus with the Component(s) added. The code for my SSCCE is extremely short/simple, so I don't know why this effect is happening.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DelayTest
{
public static void main(String[] args)
{
JLabel label = new JLabel("DELAY TEST");
label.setHorizontalAlignment(JLabel.CENTER);
label.setPreferredSize(new Dimension(400, 60));
JFrame frame = new JFrame("Delay Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I know that this effect does not happen if I comment out label.setPreferredSize(new Dimension(400,60));, so though it may simply be a correlation & not a causation, I'm guessing somehow PreferredSizes have to do with it. But, why?
ALSO, this effect occurs even if I create the GUI in a separate Runnable thread apart from the main thread. Although clearly the effect is related to the order of thread execution, I do not believe that specific factor is the cause.
Upon startup:
About 1 second later:
The likely delay is caused by the need for the system to initialize the synchronize the Event Dispatching Thread with the native system before it can render content.
You should make sure that your UI is initialised and shown from within the context of the Event Dispatching Thread, which should make the initial startup more synchronised...
Take a look at Initial Threads for more details
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestDelay {
public static void main(String[] args) {
new TestDelay();
}
public TestDelay() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel("Delay Test");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.BOLD, 24f));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

How to show only JLabel hiding JFrame or any lower level container

I want to show JLabel but want to hide JFrame border and other lower level containers like JPanel.
It just JLabel displayed on the screen.
I tried window transparency but following piece of code hides everything if trying to work with window opacity.
On decreasing windowOpacity , even JLabel becomes blurred. I tried with JPanel as well but couldn't get exact output.
I want this behaviour in jdk1.6 only
I want the JLabel content to be visible properly without any opacity impact but backbround must be purely transparent.
public class TEST {
public static void main(String[] args) {
JFrame frame = new JFrame("Sanjaal Corps - Windows On Top Demo!");
frame.setSize(400, 100);
frame.setLocation(100, 150);
com.sun.awt.AWTUtilities.setWindowOpacity(frame,0.4f);
frame.setUndecorated(true);
frame.add(new JLabel("TESTING"));
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
}
I tried with solution provided
http://www.dreamincode.net/forums/topic/140041-make-a-jpanel-transparent-to-see-the-desktop-behind/
But the problem here is if we minimize or maximize the window , then a constant color being set, So found its not the best solution or may say the Perfect one.
Assuming I understand your requirements correctly...
I typically add a transparent panel to the Window. This means that, generally, the transparency properties of the Window don't then effect the child components, for example...
Generally speaking, there are now two ways to make a window transparent.
Under Java 7, you simply make it's background color transparent.
Under Java 6 (update 10+), you need to use the unofficial com.sun.AWTUtilities class
...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.Method;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class TransparentWindow02 {
public static void main(String[] args) {
new TransparentWindow02();
}
public TransparentWindow02() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
setOpaque(frame, false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setOpaque(false);
setLayout(new BorderLayout());
setBorder(new LineBorder(Color.RED));
JLabel label = new JLabel("Click me if you can see me");
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
SwingUtilities.windowForComponent(TestPane.this).dispose();
}
});
add(label);
}
}
public static void setOpaque(Window window, boolean opaque) {
String version = System.getProperty("java.runtime.version");
if (version.startsWith("1.7")) {
window.setBackground(new Color(0, 0, 0, 0));
} else {
try {
Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
if (awtUtilsClass != null) {
Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
method.invoke(null, window, opaque);
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
}
Assuming you want to show the foreground, of the label (nothing else) that is its text/icon, you would set the frame's opacity to false:
com.sun.awt.AWTUtilities.setWindowOpaque(frame, false);
The usual caveat against using com.sun.** classes, which unfortunately is the only way to reach transparent windows prior to java7

Is it possible to perform some action BEFORE a JFrame is minimized?

In Swing, there are several ways to capture the event of minimizing a frame (iconifying), but the event happens when the frame is ICONIFIED which means after the frame becomes invisible from the screen.
Now I wish to run some code before disappearance of the frame -- immediately when I click the taskbar button.
In other words, do something when the JFrame is "about to" (NOT AFTER) be minimized. Is it possible to do this?
Use WindowStateListener, and call WindowEvent#getNewState() and check against Frame.ICONIFIED.
Here is an example:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
};
frame.add(panel);
frame.addWindowStateListener(new WindowAdapter() {
#Override
public void windowStateChanged(WindowEvent we) {
if (we.getNewState() == Frame.ICONIFIED) {
System.out.println("Here");
}
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
Create your own JFrame and override setExtendedState method.
public class MyFrame extends JFrame{
....
setExtendedState(JFrame.ICONIFIED);
....
#Override
public void setExtendedState(int state) {
// your code
super.setExtendedState(state);
};
}
Answer to the question "Is it possible to perform some action BEFORE a JFrame is minimized?"
I would say no unfortunately, I checked the native code for openjdk (windows) for frame and window that sends these events to java-space. And as I understand it, it is a callback from the windows API VM_SIZE message. And the SIZE_MINIMIZED is sent when "The window has been minimized" and is not getting any messages before the actual minimization.

How to change the image of a JButton?

I'm working on a memory game program. I have 30 JButtons on a JPanel. When the user is clicking and finds a match (meaning two buttons with the same image) I want to change the image on the JButton to a different image. However this does not happen while the program is running.
How can I do this?
I was doing this:
cards[i].setIcon(cardBack);
where cardBack is an ImageIcon that I already have.
you can use this code:
Icon i=new ImageIcon("image.jpg");
jButton1.setIcon(i);
and copy your image (image.jpg) to your project folder!
Use a JToggleButton. More specifically, use the setIcon and setSelectedIcon methods. Using this approach, you'll avoid reinventing the wheel.
Example:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
final class JToggleButtonDemo {
public static final void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static final void createAndShowGUI(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout()); // For presentation purposes only.
final JToggleButton button = new JToggleButton(UIManager.getIcon("OptionPane.informationIcon"));
button.setSelectedIcon(UIManager.getIcon("OptionPane.errorIcon"));
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Categories