Tray icon simply not showing in java - java

I've been trying all day to get my tray icon added, but it doesnt work. I have the icon file stored within the netbeans src/myproject/
I have tried a gazillion different paths, even direct ones to my files, but none seem to work. I'm pretty sure something in my code doesnt work, I simply can't see it.
public void createSystemTrayIcon() {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
Image img = Toolkit.getDefaultToolkit().getImage("smallicon.ico");
PopupMenu popup = new PopupMenu();
final MenuItem menuExit = new MenuItem("Quit");
MouseListener mouseListener =
new MouseListener() {
public void mouseClicked(MouseEvent e) {
show();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
};
ActionListener exitListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime r = Runtime.getRuntime();
System.out.println("Exiting...");
r.exit(0);
}
};
menuExit.addActionListener(exitListener);
popup.add(menuExit);
final TrayIcon trayIcon = new TrayIcon(img, "ESOLeaderboards", popup);
ActionListener actionListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayIcon.displayMessage("ESOLeaderboards ","version: EU 1.0",
TrayIcon.MessageType.INFO);
}
};
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(actionListener);
trayIcon.addMouseListener(mouseListener);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println("TrayIcon could not be added.");
}
} else {
// System Tray is not supported
}
}

Toolkit.getDefaultToolkit().getImage("smallicon.ico"); supports only JPG, PNG and GIF images.
It doesn't support ico images. Use another image.

In windows 10, I've been able to view a 16 pixels PNG in the tray this way:
final URL resource = getClass().getResource("icon16.png");
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(resource), "Application v0.1 tooltip");
It's "expected" that other OSes would down-scale a big icon, but I haven't tested it.

The standard method of embedding images (and any other non-class resources) is to just put them in a package in the project, e.g. if you project is using com.myproject.myapp, then create a package (just a folder, really) images (under myapp) and put you image files there.
Access to those images (resources) is gained by using the ClassLoader methods getResource(name) and/or getResourceAsStream(name). For simplicity to get the right ClassLoader instance many prefer to also create a class (e.g. "Images") in that same package and define static constants there to access the resources by name (as simple as Images.CONSTANT_NAME). Project structure may look like this:
com.myproject.myapp
images
Images.class
MyImage1.png
In the images class, constants can be defined either for the resource handle or the resources themselves:
public final static URL MY_IMAGE_1 = Images.class.getResource("MyImage1.png");
(The URL could then be passed to Toolkit). If an eager load of everything is desired/feasible the loaded images themselves:
public final static Image MY_IMAGE_1 = loadImage("MyImage1.png");
private static Image loadImage(String name) {
URL url = Images.class.getClassLoader().getResource(name);
Image img = Toolkit.getDefaultToolkit().getImage(url);
// possible hack to force pre-loading of (toolkit) image in next line
// new ImageIcon(img);
return img;
}
Obviously I omitted all error handling from the examples, loading methods should include detailed error handling and reporting (logging/System.out and/or throwing appropiate exceptions) when something goes wrong.
These approaches will work in IDE as well as after creating a jar file for the program.

Related

ImageIcon not rendering for animation

I have tried to look at other topics with similar question like mine, and most of those solutions appear to point to fixing the classpath for images... so, I tried those by changing the classpath to absolute and using class get resource, but it still won't render the images. I have a suspicion that it has to do with the main method. I don't completely understand how that method works since I copied the source code somewhere online. I am using the Eclipse editor, and I already had put the image files alongside the Flap class file.
package wing;
import java.awt.*;
import javax.swing.*;
public class Flap extends JComponent implements Runnable {
Image[] images = new Image[2];
int frame = 0;
public void paint(Graphics g) {
Image image = images[frame];
if (image != null) {
// Draw the current image
int x = 0;
int y = 0;
g.drawImage(image, x, y, this);
}
}
public void run() {
// Load the array of images
images[0] = new ImageIcon(this.getClass().getResource("/Wing/src/wing/wing1.png"));
images[1] = new ImageIcon(this.getClass().getResource("/Wing/src/wing/wing2.png"));
// Display each image for 1 second
int delay = 10000; // 1 second
try {
while (true) {
// Move to the next image
frame = (frame+1)%images.length;
// Causes the paint() method to be called
repaint();
// Wait
Thread.sleep(delay);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
Flap app = new Flap();
// Display the animation in a frame
JFrame frame = new JFrame();
frame.getContentPane().add(app);
frame.setSize(800, 700);
frame.setVisible(true);
(new Thread(app)).start();
}
}
ImageIcon is not an Image :
images[0] = new ImageIcon(this.getClass().getResource("/Wing/src/wing/wing1.png")).getImage();
The application never ends, in main :
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
if isn't there any another JComponent(s) added to the public class Flap extends JComponent implements Runnable {
put Image as Icon to the JLabel
use Swing Timer instead of Runnable#Thread (required basic knowledge about Java and Threads too)
if there is/are another JComponent(s) added to the public class Flap extends JComponent implements Runnable {
don't use paint() use paintComponent() for Swing JComponents
use Swing Timer instead of Runnable#Thread (required basic knowledge about Java and Threads too)
in both cases load image as local variable, don't reload images forever
in both cases you have invoke Swing GUI from InitialThread
The resource name "/Wing/src/wing/wing1.png" looks suspicious: it means to locate a resource in the "/Wing/src/wing/" directory, which is most likely not where the resource actually is. Try "/wing/wing1.png" (similarly for the others)
The reason is that the src folder contains the source, which will be converted to classes. So "src/wing/Flap.java" will have the class path "/wing/Flap.class"; similarly for resources (depending on how you are packaging them).
Also, make sure the resource is indeed where you expect it to be (e.g. next to the Flap.class file in the output directory), otherwise the class loader will not find it.

What kind of popup "Safe To Remove Hardware" in Windows

i am working on a java project and i want to display a message in popup like the popup of "Safe To Remove Hardware" occurred in the windows when we click on the Eject icon for USB Drives.
I want show my message in the same kind of popup using java code.
Use the SystemTray class.
To create an icon with a tooltip, use something like this:
SystemTray tray = SystemTray.getSystemTray();
TrayIcon icon = new TrayIcon(....);
icon.setToolTip("I have finished my work");
icon.setActionListener(this);
tray.add(trayIcon);
Then in the class that displays the tooltip, implement the ActionListener interface to be informed when the user clicks on the icon and/or the tooltip (that's what the setActionListener() is for)
For more details refer to the Javadocs of SystemTray, TrayIcon and ActionListener
You simply need to use the displayMessage(...) method of the TrayIcon class.
Try your hands on this code, is this what you wanted :
import java.awt.*;
import java.net.URL;
import javax.swing.*;
public class BalloonExample
{
private void createAndDisplayGUI()
{
TrayIcon trayIcon = new TrayIcon(createImage(
"/image/caIcon.png", "tray icon"));
SystemTray tray = SystemTray.getSystemTray();
try
{
tray.add(trayIcon);
}
catch (AWTException e)
{
System.out.println("TrayIcon could not be added.");
return;
}
trayIcon.displayMessage("Balloon", "My First Balloon", TrayIcon.MessageType.INFO);
}
//Obtain the image URL
protected static Image createImage(String path, String description) {
URL imageURL = BalloonExample.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new BalloonExample().createAndDisplayGUI();
}
});
}
}
Have a look at my question here. Basically that tooltip is a Balloon tip and you can use ShellNotifyIcon to create one.

No refreshing, every time the same Image

Basically, I am trying to create an app, that displays images.
filename variable is a path to an image that I want to display. After I start an app, an Image is displayed, but then, when I remove the image from a hard drive (or change other image to the filename name) I don't get any other Image, just the same as before.
public static void main(final String[] args) {
String filename = "C:\\temp\\1.jpeg";
JFrame frame = new JFrame();
frame.getContentPane().add(new JLabel(new ImageIcon(filename)));
frame.pack();
frame.setVisible(true);
// Mouse Listener is only to display another JFrame after mouseClicked event
frame.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
main(args);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
The image is cached. You need to force it to reload by doing either:
// This works using ImageIO
imageLabel.setIcon( new ImageIcon(ImageIO.read( new File(imageName) ) ) );
// Or you can flush the image
ImageIcon icon = new ImageIcon(imageName);
icon.getImage().flush();
imageLabel.setIcon( icon );
If this is all the code there is, and you are moving files around on the OS, your application will not pick up the changes.
The image has been loaded and will always be told to draw the same way.
You could use a WatchService to watch for changes on the file (I think) or just periodically check to see if the file has changed.
That behaviour you are trying to achieve seems a bit unusual. If that is what you want to do you could set a timer that triggers an event periodically (every "n" seconds or whatever is appropriate), deletes the image icon object and adds a new one. Don't forget to call "pack()" at the end.

how to set icon for JFrame window and tray

I would like to show my own icon instead of the Java cup in the window.
Also when minimized, I would like to display, my own image. How will I be able to do so?
And where should I position my image relative to the source file?
[UPDATE]
I tried but no luck
TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().createImage("image/accounting.gif"));
//setIconImage();
SystemTray tray = SystemTray.getSystemTray();
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
Also i tried
TrayIcon trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));
But seriously doubt createImage( and even if it is Object don't know what to import.
Regards,
Regarding your TrayIcon issue, you can refer below for a solution:
public static void createSystemTrayIcon() {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(
System.getenv("MY_PROGRAM_HOME") + "game.ico"
);
PopupMenu popup = new PopupMenu();
final MenuItem menuExit = new MenuItem("Quit");
MouseListener mouseListener =
new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
};
ActionListener exitListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime r = Runtime.getRuntime();
System.out.println("Exiting...");
r.exit(0);
}
};
menuExit.addActionListener(exitListener);
popup.add(menuExit);
final TrayIcon trayIcon = new TrayIcon(image, "My program", popup);
ActionListener actionListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayIcon.displayMessage(
"My program ",
"version: blahblah",
TrayIcon.MessageType.INFO
);
}
};
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(actionListener);
trayIcon.addMouseListener(mouseListener);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println("TrayIcon could not be added.");
}
} else {
// System Tray is not supported
}
}
Use JFrame.setIconImage()
An example using setIconImages() : (same applies for setIconImage())
public MyFrame() {
initComponents(); //Added by Netbeans
List<Image> icons = new ArrayList();
icons.add(new ImageIcon(getClass().getResource("/com/example/icons/16/app.png")).getImage());
icons.add(new ImageIcon(getClass().getResource("/com/example/icons/32/app.png")).getImage());
this.setIconImages(icons);
}
The clue is in using the "getImage()" in order to return the Image (as ImageIcon can not be used directly in setIconImages() ).
I havent written about tray icon but Finally I found the main issue in setting the jframe icon. Here is my code. It is similar to other codes but here are few things to mind the game.
this.setIconImage(new ImageIcon(getClass().getResource("Icon.png")).getImage());
1) Put this code in jframe WindowOpened event
2) Put Image in main folder where all of your form and java files are created e.g.
src\ myproject\ myFrame.form
src\ myproject\ myFrame.java
src\ myproject\ OtherFrame.form
src\ myproject\ OtherFrame.java
src\ myproject\ Icon.png
3) And most important that name of file is case sensitive that is icon.png won't work but Icon.png.
this way your icon will be there even after finally building your project.

Hows to open an .bmp/.jpeg image using Java

I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?
I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}
I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*
Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}
I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}

Categories

Resources