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.
Related
I have a problem that the windows cannot pop-up window which setting on the timer. The code below the Block. How can I resolve the problem? Can someone tell me. I very much appreciate it.
I want to get my fortunes to show on the poping window.
When I try this code first, It seems successful, But once. I had never change the code, but it does not work.
I am trying to restart my computer, and I had twice but failed too.
My computer is a system of Windows 10 X64
package systemTray;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.Timer;
/**
* This program demonstrates the system tray API.
* #version 1.02 2016-05-10
* #author Cay Horstmann
*/
public class SystemTrayTest
{
public static void main(String[] args)
{
SystemTrayApp app = new SystemTrayApp();
app.init();
}
}
class SystemTrayApp
{
public void init()
{
final TrayIcon trayIcon;
if (!SystemTray.isSupported())
{
System.err.println("System tray is not supported.");
return;
}
SystemTray tray = SystemTray.getSystemTray();
Image image = new ImageIcon(getClass().getResource("cookie.png")).getImage();
PopupMenu popup = new PopupMenu();
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(event -> System.exit(0));
popup.add(exitItem);
trayIcon = new TrayIcon(image, "Your Fortune", popup);
trayIcon.setImageAutoSize(true);
trayIcon.addActionListener(event ->
{
trayIcon.displayMessage("How do I turn this off?",
"Right-click on the fortune cookie and select Exit.",
TrayIcon.MessageType.INFO);
});
try
{
tray.add(trayIcon);
}
catch (AWTException e)
{
System.err.println("TrayIcon could not be added.");
return;
}
//get fortunes to show
final List<String> fortunes = readFortunes();
// I want to pop up window to show message with the timer.
Timer timer = new Timer(10000, event ->
{
int index = (int) (fortunes.size() * Math.random());
trayIcon.displayMessage("Your Fortune", fortunes.get(index),
TrayIcon.MessageType.INFO);
});
timer.start();
}
}
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.
I've created a calculator using AWT Frames. I wanna know how to add a tray-icon to my Cal. I can only use AWT not Swing.
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().createImage("pathToImage"));
final SystemTray tray = SystemTray.getSystemTray();
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
Found at this page http://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html
You should also check if SystemTray is supported before using the following snippet
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
//..
}
Note that SystemTray is from package java.awt as per your request.
I want to create a JFrame instance and on the click of its minimize button, I would like to hide it to the System Tray which is usually the taskbar of windows.
I'd come to know that by using SystemTray class in java.awt package I can do so but neither I'm getting any tutorial on it nor any working program example.
I'd asked this question here to either get the link to tutorial site for SystemTray class or if any body knows how to trap the window minimizing event, a working example.
The WindowListener interface and JFrame's addWindowListener() method should help you determine when the frame has been minimised.
This will trap the window minimized event and will create a tray icon. It will also remove the window from the taskbar and it will add a listener on the tray icon so that a mouseclick would restore the window. The code is a bit scrappy but should be good enough for your learning purposes:
public class Qwe extends JFrame {
public static void main(String[] args) {
final Qwe qwe = new Qwe();
qwe.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == ICONIFIED) {
try {
final TrayIcon trayIcon = new TrayIcon(new ImageIcon("/usr/share/icons/gnome/16x16/emotes/face-plain.png").getImage());
trayIcon.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
qwe.setVisible(true);
SystemTray.getSystemTray().remove(trayIcon);
}
});
SystemTray.getSystemTray().add(trayIcon);
qwe.setVisible(false);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
});
qwe.setSize(200, 200);
qwe.setVisible(true);
}
}
best way would be create follows
1) SystemTray
2) add JPopopMenu to the SystemTray's Icon
3) set DefaultCloseOperation for TopLevelContainer (in your case JFrame)
by using WindowListener setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
in other cases always works setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
notice don't forget declare System.exit(1) to the SystemTray's JpopupMenu, from JMenuItem or another Action/Event, because in this form currenet JVM never gone from Native OS until PC power-off or restart
private void windowStateChanged(java.awt.event.WindowEvent evt) {
// Use getExtendedstate here.
}
WindowStateListener docs
Frame.getExtendedState() docs
frame.addWindowListener(new WindowAdapter() {#Override
public void windowIconified(WindowEvent e) {}
});
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.