I am working on task tray Icon in java, I like to open a popup Menu using left click same popup Menu as I open on right click, and please help me with a quick response.
Thanks in advance...
here is the code working for right click need to show same popup on left click...
don't forget to place any image # "src/img" folder with name "titleImg.jpg"
Just run this... it is a working example but i have to show same popup using left click
i have checked the Mouse Listener, it listen the left click on tray icon but how to show popup menu using that ???
package com.abc.dao;
import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
public class MyTaskTray {
public static void main(String arg[]){
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon =
new TrayIcon(Toolkit.getDefaultToolkit().getImage(new java.io.File("").getAbsolutePath()+"/bin/img/titleImg.jpg"), "Library Drop");
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");
//Add components to pop-up menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);
trayIcon.setPopupMenu(popup);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
}
}
What you actually lack is a parent component to show your PopupMenu. One way to achieve this, is to use an "invisible" frame (actually it is visible but with 0-bounds and undecorated, so you can't see it) like this:
import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;
public class MyTaskTray {
public static void main(String arg[]) throws MalformedURLException {
final Frame frame = new Frame("");
frame.setUndecorated(true);
// Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
new URL("http://home.comcast.net/~supportcd/Icons/Java_Required.jpg")), "Library Drop");
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
final PopupMenu popup = createPopupMenu();
trayIcon.setPopupMenu(popup);
trayIcon.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
frame.add(popup);
popup.show(frame, e.getXOnScreen(), e.getYOnScreen());
}
}
});
try {
frame.setResizable(false);
frame.setVisible(true);
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
}
protected static PopupMenu createPopupMenu() {
final PopupMenu popup = new PopupMenu();
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");
// Add components to pop-up menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);
return popup;
}
}
As of Java 1.7, you can add the following line to remove the application bar from the taskbar:
frame.setType(Type.UTILITY);
you can add ActionListener to the TrayIcon, mouse double_click can showing JOptionPane
trayIcon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
}
});
I think you are looking for a MouseListener which you will add to your TrayIcon and will activate when a button on the mouse is clicked,moved etc. To get it to operate for left clicks only have a look at the ButtonMasks on MouseEvent (BUTTON1) being for left mouse clicks.
You could read the official tutorial at http://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html or check out http://weblogs.java.net/blog/ixmal/archive/2006/05/using_jpopupmen.html for a solution to use a jpopuomenu instead
This should work:
trayIcon.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(null, "This shows after a left-click on tray icon");
}
});
Override any other methods if you want a different kind of event (not just the click event from the example above).
Related
I want to write a tray icon via JavaFx, but I only find that can write by awt.
Is there any way that can write it use JavaFx?
It will look like these tray icons from Windows 10:
If this is to be believed, JavaFX will feature tray icons in a future update. Till then stick to AWT. Keep track of the development using this thread on the JDK bug system. Hope this helps.
If you'd prefer to not use AWT directly, I've created a small project FXTrayIcon which translates JavaFX MenuItems to AWT MenuItems and abstracts away all of the ugly AWT bits. It's at least a small help until JavaFX supports this natively.
See it on my GitHub page
You can't with pure JavaFX, but you can use AWT with JavaFX:
import javafx.application.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.*;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
import java.text.*;
import java.util.*;
// Java 8 code
public class JavaFXTrayIconSample extends Application {
// one icon location is shared between the application tray icon and task bar icon.
// you could also use multiple icons to allow for clean display of tray icons on hi-dpi devices.
private static final String iconImageLoc =
"http://icons.iconarchive.com/icons/scafer31000/bubble-circle-3/16/GameCenter-icon.png";
// application stage is stored so that it can be shown and hidden based on system tray icon operations.
private Stage stage;
// a timer allowing the tray icon to provide a periodic notification event.
private Timer notificationTimer = new Timer();
// format used to display the current time in a tray icon notification.
private DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
// sets up the javafx application.
// a tray icon is setup for the icon, but the main stage remains invisible until the user
// interacts with the tray icon.
#Override public void start(final Stage stage) {
// stores a reference to the stage.
this.stage = stage;
// instructs the javafx system not to exit implicitly when the last application window is shut.
Platform.setImplicitExit(false);
// sets up the tray icon (using awt code run on the swing thread).
javax.swing.SwingUtilities.invokeLater(this::addAppToTray);
// out stage will be translucent, so give it a transparent style.
stage.initStyle(StageStyle.TRANSPARENT);
// create the layout for the javafx stage.
StackPane layout = new StackPane(createContent());
layout.setStyle(
"-fx-background-color: rgba(255, 255, 255, 0.5);"
);
layout.setPrefSize(300, 200);
// this dummy app just hides itself when the app screen is clicked.
// a real app might have some interactive UI and a separate icon which hides the app window.
layout.setOnMouseClicked(event -> stage.hide());
// a scene with a transparent fill is necessary to implement the translucent app window.
Scene scene = new Scene(layout);
scene.setFill(Color.TRANSPARENT);
stage.setScene(scene);
}
/**
* For this dummy app, the (JavaFX scenegraph) content, just says "hello, world".
* A real app, might load an FXML or something like that.
*
* #return the main window application content.
*/
private Node createContent() {
Label hello = new Label("hello, world");
hello.setStyle("-fx-font-size: 40px; -fx-text-fill: forestgreen;");
Label instructions = new Label("(click to hide)");
instructions.setStyle("-fx-font-size: 12px; -fx-text-fill: orange;");
VBox content = new VBox(10, hello, instructions);
content.setAlignment(Pos.CENTER);
return content;
}
/**
* Sets up a system tray icon for the application.
*/
private void addAppToTray() {
try {
// ensure awt toolkit is initialized.
java.awt.Toolkit.getDefaultToolkit();
// app requires system tray support, just exit if there is no support.
if (!java.awt.SystemTray.isSupported()) {
System.out.println("No system tray support, application exiting.");
Platform.exit();
}
// set up a system tray icon.
java.awt.SystemTray tray = java.awt.SystemTray.getSystemTray();
URL imageLoc = new URL(
iconImageLoc
);
java.awt.Image image = ImageIO.read(imageLoc);
java.awt.TrayIcon trayIcon = new java.awt.TrayIcon(image);
// if the user double-clicks on the tray icon, show the main app stage.
trayIcon.addActionListener(event -> Platform.runLater(this::showStage));
// if the user selects the default menu item (which includes the app name),
// show the main app stage.
java.awt.MenuItem openItem = new java.awt.MenuItem("hello, world");
openItem.addActionListener(event -> Platform.runLater(this::showStage));
// the convention for tray icons seems to be to set the default icon for opening
// the application stage in a bold font.
java.awt.Font defaultFont = java.awt.Font.decode(null);
java.awt.Font boldFont = defaultFont.deriveFont(java.awt.Font.BOLD);
openItem.setFont(boldFont);
// to really exit the application, the user must go to the system tray icon
// and select the exit option, this will shutdown JavaFX and remove the
// tray icon (removing the tray icon will also shut down AWT).
java.awt.MenuItem exitItem = new java.awt.MenuItem("Exit");
exitItem.addActionListener(event -> {
notificationTimer.cancel();
Platform.exit();
tray.remove(trayIcon);
});
// setup the popup menu for the application.
final java.awt.PopupMenu popup = new java.awt.PopupMenu();
popup.add(openItem);
popup.addSeparator();
popup.add(exitItem);
trayIcon.setPopupMenu(popup);
// create a timer which periodically displays a notification message.
notificationTimer.schedule(
new TimerTask() {
#Override
public void run() {
javax.swing.SwingUtilities.invokeLater(() ->
trayIcon.displayMessage(
"hello",
"The time is now " + timeFormat.format(new Date()),
java.awt.TrayIcon.MessageType.INFO
)
);
}
},
5_000,
60_000
);
// add the application tray icon to the system tray.
tray.add(trayIcon);
} catch (java.awt.AWTException | IOException e) {
System.out.println("Unable to init system tray");
e.printStackTrace();
}
}
/**
* Shows the application stage and ensures that it is brought ot the front of all stages.
*/
private void showStage() {
if (stage != null) {
stage.show();
stage.toFront();
}
}
public static void main(String[] args) throws IOException, java.awt.AWTException {
// Just launches the JavaFX application.
// Due to way the application is coded, the application will remain running
// until the user selects the Exit menu option from the tray icon.
launch(args);
}
}
code source
To make a system tray try following code:
Original document link: https://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
URL url = System.class.getResource("/images/new.png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
final TrayIcon trayIcon = new TrayIcon(image);
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");
//Add components to pop-up menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);
trayIcon.setPopupMenu(popup);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
Example system tray image in Windows 10
To invoke method of Javafx from awt event handler you may follw the following way:
yourAwtObject.addActionListener(e -> {
Platform.runLater(() -> primaryStage.show());
});
i made it. JavaFX with AWT. I have one example of a application that shows and hides when you make left clic. i really hope works for you
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainApp2 extends Application {
int stateWindow = 1;
#Override
public void start(final Stage stage) throws Exception {
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
URL url = System.class.getResource("/image/yourImage.png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
//image dimensions must be 16x16 on windows, works for me
final TrayIcon trayIcon = new TrayIcon(image, "application name");
final SystemTray tray = SystemTray.getSystemTray();
//Listener left clic XD
trayIcon.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
if (event.getButton() == MouseEvent.BUTTON1) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (stateWindow == 1) {
stage.hide();
stateWindow = 0;
} else if (stateWindow == 0) {
stage.show();
stateWindow = 1;
}
}
});
}
}
});
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
stage.setTitle("Hello man!");
Button btn = new Button();
btn.setText("Say 'Hello man'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello man!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
stage.setScene(new Scene(root, 300, 250));
Platform.setImplicitExit(false);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
I'm trying to use a few JDialogs inside my form JPanel to notify the user of incorrect data and form submission.
I'm just a bit confused with the JDialog constructor. I'd want to link the dialog to the panel (only because that's where it's created), but obviously the only owner parameters that are allowed are top level Frames (which I don't think I can access from the JPanel), or a Dialog (which I can't see helping me).
I could pass a reference for the Frame down to the JPanel, but isn't that a bit strange design wise? Or am I misunderstanding the class, or just more generally where the JDialog should be instantiated?
Hope I've made myself clear, I can make a sscce if it helps. Thanks.
the only owner parameters that are allowed are top level Frames (which I don't think I can access from the JPanel
You can access the parent frame of the panel by using:
Window window = SwingUtilities.windowForComponent( yourPanelHere );
Then just use the window as the owner of the dialog.
JComponent.getTopLevelAncestor gives you the owner of the JPanel:
Returns the top-level ancestor of this component (either the
containing Window or Applet), or null if this component has not been
added to any container.
You can try it:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class DialogTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
public void run() {
DialogFrame frame = new DialogFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* Frame contains menu. When we choose menu "File-> About" JDialog will be shown
*/
class DialogFrame extends JFrame {
public DialogFrame() {
setTitle("DialogTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// Add About & Exit.
// Choose About - > About
JMenuItem aboutItem = new JMenuItem("About");
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (dialog == null) //if not
{
dialog = new AboutDialog(DialogFrame.this);
}
dialog.setVisible(true); // to show dialog
}
});
fileMenu.add(aboutItem);
// When Exit
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
fileMenu.add(exitItem);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private AboutDialog dialog;
}
/*
* Modal dialog waits on click
*/
class AboutDialog extends JDialog {
public AboutDialog(JFrame owner) {
super(owner, "About DialogTest", true);
// Mark with HTML centration
add(new JLabel(
"<html><h1><i>Все о Java</i></h1><hr>"
+ "Something about java and JDialog</html>"),
BorderLayout.CENTER);
// When push "ok" dialog window will be closed
JButton ok = new JButton("ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
// Button ОК down of panel
JPanel panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH);
setSize(260, 160);
}
}
In my java AWT (not Swing) application I use java.awt.MenuBar.
And I need use different checkboxes and radiobuttons inside the menu items.
I found java.awt.CheckboxMenuItem and successfully use it.
MenuBar menuBar = new MenuBar();
Menu menuSettings = new Menu("Settings");
Menu menuSettingsMenuGrid = new Menu("Grid");
CheckboxMenuItem menuCheckboxShowGrid = new CheckboxMenuItem("Show");
CheckboxMenuItem menuCheckboxHotspots = new CheckboxMenuItem("Hotspots");
menuSettingsMenuGrid.add(menuCheckboxShowGrid)
menuSettingsMenuGrid.add(menuCheckboxHotspots)
menuSettings.add(menuSettingsMenuGrid);
menuBar.add(menuSettings);
mApplicationFrame.setMenuBar(menuBar);
But I can't find RadioButton. But I really need to use it in awt Menu. What can help me?
But I can't find RadioButton. But I really need to use it in awt Menu. What can help me?
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AWTMenuSample {
public static void main(String args[]) {
Frame frame = new Frame("AWT Menu");
MenuBar bar = new MenuBar();
Menu menu = new Menu("Settings");
ActionListener actionPrinter = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
System.out.println("Action [" + e.getActionCommand() + "] performed!\n");
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
MenuItem menuItemShow = new MenuItem("Show");
menuItemShow.addActionListener(actionPrinter);
menu.add(menuItemShow);
MenuItem menuItemHotspots = new MenuItem("Hotspots");
menuItemHotspots.addActionListener(actionPrinter);
menu.add(menuItemHotspots);
bar.add(menu);
frame.setMenuBar(bar);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
You can write your own algorithm to group actions in ActionListener event.
I want to write a tray icon via JavaFx, but I only find that can write by awt.
Is there any way that can write it use JavaFx?
It will look like these tray icons from Windows 10:
If this is to be believed, JavaFX will feature tray icons in a future update. Till then stick to AWT. Keep track of the development using this thread on the JDK bug system. Hope this helps.
If you'd prefer to not use AWT directly, I've created a small project FXTrayIcon which translates JavaFX MenuItems to AWT MenuItems and abstracts away all of the ugly AWT bits. It's at least a small help until JavaFX supports this natively.
See it on my GitHub page
You can't with pure JavaFX, but you can use AWT with JavaFX:
import javafx.application.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.*;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.net.URL;
import java.text.*;
import java.util.*;
// Java 8 code
public class JavaFXTrayIconSample extends Application {
// one icon location is shared between the application tray icon and task bar icon.
// you could also use multiple icons to allow for clean display of tray icons on hi-dpi devices.
private static final String iconImageLoc =
"http://icons.iconarchive.com/icons/scafer31000/bubble-circle-3/16/GameCenter-icon.png";
// application stage is stored so that it can be shown and hidden based on system tray icon operations.
private Stage stage;
// a timer allowing the tray icon to provide a periodic notification event.
private Timer notificationTimer = new Timer();
// format used to display the current time in a tray icon notification.
private DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
// sets up the javafx application.
// a tray icon is setup for the icon, but the main stage remains invisible until the user
// interacts with the tray icon.
#Override public void start(final Stage stage) {
// stores a reference to the stage.
this.stage = stage;
// instructs the javafx system not to exit implicitly when the last application window is shut.
Platform.setImplicitExit(false);
// sets up the tray icon (using awt code run on the swing thread).
javax.swing.SwingUtilities.invokeLater(this::addAppToTray);
// out stage will be translucent, so give it a transparent style.
stage.initStyle(StageStyle.TRANSPARENT);
// create the layout for the javafx stage.
StackPane layout = new StackPane(createContent());
layout.setStyle(
"-fx-background-color: rgba(255, 255, 255, 0.5);"
);
layout.setPrefSize(300, 200);
// this dummy app just hides itself when the app screen is clicked.
// a real app might have some interactive UI and a separate icon which hides the app window.
layout.setOnMouseClicked(event -> stage.hide());
// a scene with a transparent fill is necessary to implement the translucent app window.
Scene scene = new Scene(layout);
scene.setFill(Color.TRANSPARENT);
stage.setScene(scene);
}
/**
* For this dummy app, the (JavaFX scenegraph) content, just says "hello, world".
* A real app, might load an FXML or something like that.
*
* #return the main window application content.
*/
private Node createContent() {
Label hello = new Label("hello, world");
hello.setStyle("-fx-font-size: 40px; -fx-text-fill: forestgreen;");
Label instructions = new Label("(click to hide)");
instructions.setStyle("-fx-font-size: 12px; -fx-text-fill: orange;");
VBox content = new VBox(10, hello, instructions);
content.setAlignment(Pos.CENTER);
return content;
}
/**
* Sets up a system tray icon for the application.
*/
private void addAppToTray() {
try {
// ensure awt toolkit is initialized.
java.awt.Toolkit.getDefaultToolkit();
// app requires system tray support, just exit if there is no support.
if (!java.awt.SystemTray.isSupported()) {
System.out.println("No system tray support, application exiting.");
Platform.exit();
}
// set up a system tray icon.
java.awt.SystemTray tray = java.awt.SystemTray.getSystemTray();
URL imageLoc = new URL(
iconImageLoc
);
java.awt.Image image = ImageIO.read(imageLoc);
java.awt.TrayIcon trayIcon = new java.awt.TrayIcon(image);
// if the user double-clicks on the tray icon, show the main app stage.
trayIcon.addActionListener(event -> Platform.runLater(this::showStage));
// if the user selects the default menu item (which includes the app name),
// show the main app stage.
java.awt.MenuItem openItem = new java.awt.MenuItem("hello, world");
openItem.addActionListener(event -> Platform.runLater(this::showStage));
// the convention for tray icons seems to be to set the default icon for opening
// the application stage in a bold font.
java.awt.Font defaultFont = java.awt.Font.decode(null);
java.awt.Font boldFont = defaultFont.deriveFont(java.awt.Font.BOLD);
openItem.setFont(boldFont);
// to really exit the application, the user must go to the system tray icon
// and select the exit option, this will shutdown JavaFX and remove the
// tray icon (removing the tray icon will also shut down AWT).
java.awt.MenuItem exitItem = new java.awt.MenuItem("Exit");
exitItem.addActionListener(event -> {
notificationTimer.cancel();
Platform.exit();
tray.remove(trayIcon);
});
// setup the popup menu for the application.
final java.awt.PopupMenu popup = new java.awt.PopupMenu();
popup.add(openItem);
popup.addSeparator();
popup.add(exitItem);
trayIcon.setPopupMenu(popup);
// create a timer which periodically displays a notification message.
notificationTimer.schedule(
new TimerTask() {
#Override
public void run() {
javax.swing.SwingUtilities.invokeLater(() ->
trayIcon.displayMessage(
"hello",
"The time is now " + timeFormat.format(new Date()),
java.awt.TrayIcon.MessageType.INFO
)
);
}
},
5_000,
60_000
);
// add the application tray icon to the system tray.
tray.add(trayIcon);
} catch (java.awt.AWTException | IOException e) {
System.out.println("Unable to init system tray");
e.printStackTrace();
}
}
/**
* Shows the application stage and ensures that it is brought ot the front of all stages.
*/
private void showStage() {
if (stage != null) {
stage.show();
stage.toFront();
}
}
public static void main(String[] args) throws IOException, java.awt.AWTException {
// Just launches the JavaFX application.
// Due to way the application is coded, the application will remain running
// until the user selects the Exit menu option from the tray icon.
launch(args);
}
}
code source
To make a system tray try following code:
Original document link: https://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
URL url = System.class.getResource("/images/new.png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
final TrayIcon trayIcon = new TrayIcon(image);
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");
//Add components to pop-up menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);
trayIcon.setPopupMenu(popup);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
Example system tray image in Windows 10
To invoke method of Javafx from awt event handler you may follw the following way:
yourAwtObject.addActionListener(e -> {
Platform.runLater(() -> primaryStage.show());
});
i made it. JavaFX with AWT. I have one example of a application that shows and hides when you make left clic. i really hope works for you
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainApp2 extends Application {
int stateWindow = 1;
#Override
public void start(final Stage stage) throws Exception {
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
URL url = System.class.getResource("/image/yourImage.png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
//image dimensions must be 16x16 on windows, works for me
final TrayIcon trayIcon = new TrayIcon(image, "application name");
final SystemTray tray = SystemTray.getSystemTray();
//Listener left clic XD
trayIcon.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
if (event.getButton() == MouseEvent.BUTTON1) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (stateWindow == 1) {
stage.hide();
stateWindow = 0;
} else if (stateWindow == 0) {
stage.show();
stateWindow = 1;
}
}
});
}
}
});
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
stage.setTitle("Hello man!");
Button btn = new Button();
btn.setText("Say 'Hello man'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello man!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
stage.setScene(new Scene(root, 300, 250));
Platform.setImplicitExit(false);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Does anyone have any example code to make a draggable menu?
I am new to Java and I am trying to find a way to make a menu that is draggable with the mouse. Like a lot of programs have. You can drag the top menu bar around the screen so that you can drop it in other locations. I think that Java can do this as well because I have seen some applications that I think were written in Java do this very same thing.
Question: How do I create a draggable menu in a JFrame in Java?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
public class MyExample extends JFrame {
public MyExample() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit");
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0); //exit the system
}
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
setTitle("My Menu");
setSize(300, 100);
setLocationRelativeTo(); //I tried draggable
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyExample e = new MyExample();
e.setVisible(true);
}
}
I want to be able to drag the menu from the top of the JFrame to another location out of the window and leave it there. I have used Toolbar and that worked good but I was trying to see if this can be done with a menu. If you look at any software application the usually is a grabable area right next tot he File location. This you can click and drag around the area.
ImageIcon icon = new ImageIcon(getClass().getResource("10cd.jpg"));
JMenu file1 = new JMenu("File");
file1.setMnemonic(KeyEvent.VK_F);
JMenu file2 = new JMenu("Open");
file2.setMnemonic(KeyEvent.VK_F);
JMenu file3 = new JMenu("A");
file3.setMnemonic(KeyEvent.VK_F);
JMenu file4 = new JMenu("B");
file4.setMnemonic(KeyEvent.VK_F);
JMenu file5 = new JMenu("C");
file5.setMnemonic(KeyEvent.VK_F);
JMenu file6 = new JMenu("D");
file6.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem1a = new JMenuItem("File 1"/*, icon*///);
/*eMenuItem1a.setMnemonic(KeyEvent.VK_E);
eMenuItem1a.setToolTipText("Exit application");
JMenuItem eMenuItem1b = new JMenuItem("File 2"/*, icon*///);
/* eMenuItem1b.setMnemonic(KeyEvent.VK_E);
eMenuItem1b.setToolTipText("Exit application");
JMenuItem eMenuItem1c = new JMenuItem("File 3"/*, icon*///);
/* eMenuItem1c.setMnemonic(KeyEvent.VK_E);
eMenuItem1c.setToolTipText("Exit application");
JMenuItem eMenuItem2 = new JMenuItem("Exit"/*, icon*///);
/* eMenuItem2.setMnemonic(KeyEvent.VK_E);
eMenuItem2.setToolTipText("Exit application");
JMenuItem eMenuItem3 = new JMenuItem("Exit"/*, icon*///);
/*eMenuItem3.setMnemonic(KeyEvent.VK_E);
eMenuItem3.setToolTipText("Exit application");
JMenuItem eMenuItem4 = new JMenuItem("Exit"/*, icon*///);
/*eMenuItem4.setMnemonic(KeyEvent.VK_E);
eMenuItem4.setToolTipText("Exit application");
eMenuItem1a.addActionListener(new myListenerOne());
eMenuItem1b.addActionListener(new myListenerTwo());
eMenuItem1c.addActionListener(new myListenerThree());
eMenuItem2.addActionListener(new myListenerOne());
eMenuItem3.addActionListener(new myListenerTwo());
eMenuItem4.addActionListener(new myListenerThree());
file1.add(eMenuItem1a);
file1.add(eMenuItem1b);
file1.add(eMenuItem1c);
file2.add(eMenuItem2);
file3.add(eMenuItem3);
file4.add(eMenuItem4);
menubar.add(file1);
menubar.add(file2);
menubar.add(file3);
menubar.add(file4);
menubar.add(file5);
menubar.add(file6);
setJMenuBar(menubar);
//Actionlisteners below
class myListenerOne implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 1");
System.exit(0);
}
}
class myListenerTwo implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 2");
System.exit(0);
}
}
class myListenerThree implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 3");
System.exit(0);
}
}
Here is another menu example that I forgot to include this morning. Was sick and just didn't think about it actually. Anyway, what I was wondering was if the menu could be set to a movable menu, so that when you click on it and drag it that it can be moved to any where in the frame. I have seen this done on some java applications I have used but just haven't seen it in a while.
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.net.URL;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = imageName + ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Doug's Test ToolBarDemo!!!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
The following code adds a JToolBar to the frame. I like this because it is draggable but it looks different than a regular menu. I was more interested in if you could set a menu to draggable.
Try using a JToolBar if you don't want to create your own floating window.
http://docs.oracle.com/javase/tutorial/uiswing/components/toolbar.html