RadioButtonMenuItem for java.awt.Menu - java

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.

Related

How can we output to inputstream

I am trying to make a on-screen keyboard for Windows using Java.
The result I am looking for is somewhat similar to the tablet PC
input panel (Touch Keyboard Mode) on Windows 7 except that mine will
be Bengali.
But I cannot figure out how to send data from the program (when the
user presses the on-screen buttons) such that it can serve as
input for another program (say, a text editor).
This link seems useful but I cannot understand it.
How can I achieve this?
My current code is:
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.border.Border;
import javax.swing.*;
public class Bengali extends JFrame {
private JMenuBar menuBar;
private JButton[][] buttons;
private int i,j;
private String hex;
//Constructor
public Bengali(){
this.setTitle("GUI_project");
this.setSize(1600,140);
//menu generate method
generateMenu();
this.setJMenuBar(menuBar);
//pane with null layout
JPanel contentPane = new JPanel(null);
contentPane.setPreferredSize(new Dimension(1600,140));
contentPane.setBackground(new Color(192,192,192));
buttons=new JButton[4][32];
for(i=0;i<4;i++)
{
for(j=0;j<32;j++)
{
buttons[i][j]=new JButton();
buttons[i][j].setBounds(0+50*j,0+35*i,50,35);
buttons[i][j].setBackground(new Color(214,217,223));
buttons[i][j].setForeground(new Color(0,0,0));
buttons[i][j].setEnabled(true);
buttons[i][j].setFont(new Font("sansserif",0,12));
hex = "u"+Integer.toHexString(i+2432);
buttons[i][j].setText(hex);
buttons[i][j].setVisible(true);
//Set methods for mouse events
//Call defined methods
buttons[i][j].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
but(evt,i,j);
}
});
//adding components to contentPane panel
contentPane.add(buttons[i][j]);
}
//adding panel to JFrame and seting of window position and close operation
this.add(contentPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
}
//Method mouseClicked for buttons[i][j]
private void but (MouseEvent evt,int i,int j)
{
//TODO
}
//method for generate menu
public void generateMenu()
{
menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu tools = new JMenu("Tools");
JMenu help = new JMenu("Help");
JMenuItem open = new JMenuItem("Open ");
JMenuItem save = new JMenuItem("Save ");
JMenuItem exit = new JMenuItem("Exit ");
JMenuItem preferences = new JMenuItem("Preferences ");
JMenuItem about = new JMenuItem("About ");
file.add(open);
file.add(save);
file.addSeparator();
file.add(exit);
tools.add(preferences);
help.add(about);
menuBar.add(file);
menuBar.add(tools);
menuBar.add(help);
}
public static void build(){
System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Bengali();
}
});
}
}
The GUI is somewhat ready. Made using SimpleGUI extension for BlueJ.
You can use PipedInputStream and PipedOutputStream classes.
Whenever an event has occurred you have to write to the output stream and you should have a listener for input stream. You may have run these in two different threads.
example snippet:
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
You should start the listener thread first in case if you don't want to lose any data.
This can very easily be done with the Robot class. You have to simulate key presses (and not "write to any input stream" as this cannot work).
This post's accepted answer describes this very well:
Press a key with Java

How to correctly use repaint() and revalidate()?

I am new to JPanel and don't quite understand how to reset it. Once a picture is chosen and the user wants to select a new one, I want it to erase the old selected picture and paste the new one. But I'm not sure how. I've seen repaint() and revalidate() used, but I clearly don't know how to use it. So how do I accomplish this?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JRadioButtonMenuItem;
public class Menu extends JFrame {
JMenuBar menuBar;
ButtonGroup pictureGroup, problemsGroup;
BufferedImage picture1img, picture2img, picture3img;
JMenu choiceOfThreePictures, numberOfProblems;
JRadioButtonMenuItem picture1, picture2, picture3, fourProblems, nineProblems, sixteenProblems;
// /Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture1.jpg
// /Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture2.png
// /Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg
public Menu() {
// Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
// Create Picture choices on Menu Bar
choiceOfThreePictures = new JMenu("Picture Choices");
// Add Picture choices on Menu Bar
menuBar.add(choiceOfThreePictures);
// Create MenuItems onto Picture choices
pictureGroup = new ButtonGroup();
picture1 = new JRadioButtonMenuItem("Picture 1");
picture2 = new JRadioButtonMenuItem("Picture 2");
picture3 = new JRadioButtonMenuItem("Picture 3");
// Add Picture Choices to Picutre choices menu
choiceOfThreePictures.add(picture1);
pictureGroup.add(picture1);
choiceOfThreePictures.add(picture2);
pictureGroup.add(picture2);
choiceOfThreePictures.add(picture3);
pictureGroup.add(picture3);
// Create Number Of Problems on Menu Bar
numberOfProblems = new JMenu("Number Of Problems");
// Add Number Of problems on Menu Bar
menuBar.add(numberOfProblems);
// Create Menu Items onto Number Of problems
problemsGroup = new ButtonGroup();
fourProblems = new JRadioButtonMenuItem("4");
nineProblems = new JRadioButtonMenuItem("9");
sixteenProblems = new JRadioButtonMenuItem("16");
// Add Number Of problems onto menu
numberOfProblems.add(fourProblems);
problemsGroup.add(fourProblems);
numberOfProblems.add(nineProblems);
problemsGroup.add(nineProblems);
numberOfProblems.add(sixteenProblems);
problemsGroup.add(sixteenProblems);
// Start creating ActionListeners
picture1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Working");
try {
picture1img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture1.jpg"));
getContentPane().add(new JLabel(new ImageIcon(picture1img)));
revalidate();
repaint();
setVisible(true);
} catch (IOException e) {
System.out.println("Couldn't find image.");
}
}
});
picture2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Working");
try {
picture2img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture2.jpg"));
getContentPane().add(new JLabel(new ImageIcon(picture2img)));
revalidate();
repaint();
setVisible(true);
} catch (IOException e) {
System.out.println("Couldn't find image.");
}
}
});
picture3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Working");
try {
picture3img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg"));
getContentPane().add(new JLabel(new ImageIcon(picture3img)));
revalidate();
repaint();
setVisible(true);
} catch (IOException e) {
System.out.println("Couldn't find image.");
}
}
});
}
public static void main(String[] args) {
Menu mb = new Menu();
mb.setSize(900, 700);
mb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb.setVisible(true);
}
}
You are using it just fine, you can even remote repaint() call as revalidate is more then enought. The problem is, that you are adding new images but you are not removing previously added images from the contentPane that is why it is not switching.
So if you do
picture3img = ImageIO.read(new File("/Users/Administrator/Dropbox/Java/HW6Wilson/HW6Wilson/Picture3.jpg"));
getContentPane().removeAll(); // HERE IS IMPORTANT PART
getContentPane().add(new JLabel(new ImageIcon(picture3img)));
revalidate();
It will work
The better approach would be to hold single label as a "image display" and use setIcon(icon) on JLabel insteed of changing whole labels.

Java -- How to create a moveable menu [closed]

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

Fullscreen freezes after closing JOptionPane

package sample;
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.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class NewClass {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final JFrame frame = new JFrame();
final JDesktopPane d = new JDesktopPane();
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");
final JPanel panel = new JPanel();
panel.add(btn);
frame.add(panel);
final JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
System.out.println("File selected: " + chooser.getSelectedFile());
chooser.getFocusCycleRootAncestor().setVisible(false);
} else {
chooser.getFocusCycleRootAncestor().setVisible(false);
}
}
});
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showInternalOptionDialog(frame.getContentPane(), chooser, "Browse", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
}
});
}
}
This code looks weird for you, but thats the only way to preserve my full screen using GraphicsDevice. My problem is that, when I click the cancel or open button of the JFileChooser, my screen freezes using this code chooser.getFocusCycleRootAncestor().setVisible(false);. How can I close the JOPtionPane using internal dialog without freezing my screen or closing the whole screen.
you problem is not in
chooser.getFocusCycleRootAncestor().setVisible(false);
if you make these changes, your code will work flawlessly
just remove this part
JOptionPane.showInternalOptionDialog(frame.getContentPane(),chooser, "Browse",JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
and add this code instead
chooser.showOpenDialog(frame);
let me know if you have further concerns
The problem is, the program still thinks that there is a modal dialog open, which is restricting focus to the modal dialog...
Try changing your chooser's actionListener to something like this...
chooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container parent = chooser.getParent();
while (!(parent instanceof JOptionPane)) {
parent = parent.getParent();
}
JOptionPane op = (JOptionPane) parent;
op.setValue("done");
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) {
System.out.println("File selected: " + chooser.getSelectedFile());
} else {
}
}
});
This basically "tricks" the JOptionPane into thinking that the user has selected a value (which you've actually not provided anything for) and closes the dialog, returning control back to your application

Open popup(Menu) on task tray icon with left click using java

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).

Categories