How to capture trayicon.displayMessage() mouse click on the tooltip baloon - java

Hi, I am trying to show more detailed information after a user clicks on the message balloon tooltip.
However, I can't find how to capture that event.
Is this possible to do?

1) Is possible to listening MouseClickEvents by add ActionListener to the TrayIcon, then Message body listening for MouseClicked
2) (not asked directly) but I can't to give you an answer listening if message was closed by close button, and Message gone away from screen same way, but without catch any event(s)
3) looks like as this Java TrayIcon message close button should be only one solutions, because API doesn't implements another methods,
import java.awt.*;
import java.awt.event.*;
public class FullTray {
private static class ShowMessageListener implements ActionListener {
private TrayIcon trayIcon;
private String title;
private String message;
private TrayIcon.MessageType messageType;
ShowMessageListener(TrayIcon trayIcon, String title, String message, TrayIcon.MessageType messageType) {
this.trayIcon = trayIcon;
this.title = title;
this.message = message;
this.messageType = messageType;
}
public void actionPerformed(ActionEvent e) {
trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Message Clicked");
}
});
trayIcon.displayMessage(title, message, messageType);
}
}
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
if (SystemTray.isSupported()) {
final SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("gifIcon.gif");
PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup);
MenuItem item = new MenuItem("Error");
item.addActionListener(new ShowMessageListener(trayIcon, "Error Title", "Error", TrayIcon.MessageType.ERROR));
popup.add(item);
item = new MenuItem("Warning");
item.addActionListener(new ShowMessageListener(trayIcon, "Warning Title", "Warning", TrayIcon.MessageType.WARNING));
popup.add(item);
item = new MenuItem("Info");
item.addActionListener(new ShowMessageListener(trayIcon, "Info Title", "Info", TrayIcon.MessageType.INFO));
popup.add(item);
item = new MenuItem("None");
item.addActionListener(new ShowMessageListener(trayIcon, "None Title", "None", TrayIcon.MessageType.NONE));
popup.add(item);
item = new MenuItem("Close");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
}
});
popup.add(item);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println("Can't add to tray");
}
} else {
System.err.println("Tray unavailable");
}
}
};
EventQueue.invokeLater(runner);
}
private FullTray() {
}
}

Even though this topic isn't exactly recent, I figured I'd share my solution since this kind of thing doesn't really change.
How To Use
To use this code, just create the 1 public class and the 2 public interfaces.
Now create an instance of the CustomTrayIcon class and call the addToSystemTray() method, once you're done initializing it.
Anytime you want to show a notification bubble, call the showBubbleNotification(...) method.
To remove this tray icon, just call the removeFromSystemTray() method.
CustomTrayIcon
This class is the base which does all of the heavy lifting.
package com.samples;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* This class can be used to create an icon in the {#link SystemTray}, providing
* the current operating system supports the {#link SystemTray}. <br />
* <br />
* <b><u>Userful Methods</u>:</b>
* <ul>
* <li>
* Use the {#link CustomTrayIcon#addToSystemTray() addToSystemTray()} method to
* add this {#link CustomTrayIcon} to the {#link SystemTray}. <br />
* </li>
* <li>
* Use the {#link CustomTrayIcon#removeFromSystemTray() removeFromSystemTray()}
* method to remove this {#link CustomTrayIcon} from the {#link SystemTray}. <br />
* </li>
* <li>
* Use the
* {#link CustomTrayIcon#showBubbleNotification(String, String, MessageType, CustomTrayIconNotificationBubbleClickEvent)
* showBubbleNotification(String, String, MessageType,
* CustomTrayIconNotificationBubbleClickEvent)} method to show a bubble notification to
* the user. <br />
* </li>
* <li>
* Use the {#link CustomTrayIcon#setClickDetectionDelay_override(int)
* setClickDetectionDelay_override(int)} method to override the default delay to
* be used when detecting if a user performed a single/double/triple click.</li>
* </ul>
*
* #author Matthew Weiler
* */
public abstract class CustomTrayIcon extends TrayIcon implements CustomTrayIconMouseInterface
{
/* PRIVATE CONSTANTS */
/**
* This will be used as the millisecond delay between clicks to detect
* single or double clicks. <br />
* <br />
* <b><u>Default Value</u>:</b> 300
* */
private static final int DEFAULT_CLICK_DETECTION_DELAY = 300;
/**
* This will be used to ensure that we can synchronize the click counter
* changes.
* */
private static final Object clickLock = new Object();
/* PRIVATE VARIABLES */
/**
* This will store the override value to be used in-place of the
* {#link CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY CLICK_DETECTION_DELAY}
* default value.
*
* #see CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY
* */
private int clickDetectionDelay_override = -1;
/**
* This will store the {#link CustomTrayIconNotificationBubbleClickEvent} which
* should be executed the next time that an {#link ActionEvent} is fired by
* the user clicking a notification bubble.
* */
private CustomTrayIconNotificationBubbleClickEvent newBubbleAction = null;
/**
* This will be used to keep track of which click was responsible for the
* current click timer.
* */
private long clickOwnerIndex = 0L;
/**
* This will be used to keep track of how many clicks occurred in the
* current click detection cycle.
* */
private int clickCounter = 0;
/* CONSTRUCTORS */
/**
* This will create a new instance of a {#link CustomTrayIcon}.
*
* #param image
* The {#link Image} to display as the icon in the notification
* tray.
* */
public CustomTrayIcon(final Image image)
{
super(image);
this.postCreateTasks();
}
/**
* This will create a new instance of a {#link CustomTrayIcon}.
*
* #param image
* The {#link Image} to display as the icon in the notification
* tray.
* #param tooltip
* The string to be used as tooltip text; if the value is null no
* tooltip is shown.
* */
public CustomTrayIcon(final Image image, final String tooltip)
{
super(image, tooltip);
this.postCreateTasks();
}
/**
* This will create a new {#link CustomTrayIcon}. <br />
* The {#link CustomTrayIcon}
* */
public CustomTrayIcon(final Image image, final String tooltip, final PopupMenu popup)
{
super(image, tooltip, popup);
this.postCreateTasks();
}
/* PUBLIC METHODS */
/**
* This will determine if the current operating system supports
* {#link SystemTray}.
*
* #see SystemTray#isSupported()
*
* #return <code>true</code> if the current operating system supports
* {#link SystemTray}; <code>false</code> otherwise.
* */
public static boolean isSystemTraySupported()
{
return SystemTray.isSupported();
}
/**
* This method will add this {#link CustomTrayIcon} to {#link SystemTray} . <br />
* <br />
* <i>this method may return <code>false</code> if the current operating
* system does not have or support a {#link SystemTray}</i>
*
* #return <code>true</code> if this {#link CustomTrayIcon} was added;
* <code>false</code> otherwise.
* */
public boolean addToSystemTray()
{
// Ensure that the current operating system supports
// the SystemTray.
if (CustomTrayIcon.isSystemTraySupported())
{
try
{
// Add this CustomTrayIcon to the SystemTray.
SystemTray.getSystemTray().add(this);
return true;
}
catch (AWTException e)
{
// ignore
}
}
return false;
}
/**
* This method will remove this {#link CustomTrayIcon} from the
* {#link SystemTray}.
* */
public void removeFromSystemTray()
{
SystemTray.getSystemTray().remove(this);
}
#Override
public void displayMessage(final String caption, final String text, final MessageType messageType)
{
this.newBubbleAction = null;
super.displayMessage(caption, text, messageType);
}
/**
* This method will show a bubble notification near the
* {#link CustomTrayIcon}.
*
* #see TrayIcon#displayMessage(String, String, MessageType)
*
* #param title
* The title to be displayed in the bubble notification.
* #param message
* The message to be displayed in the bubble notification.
* #param messageType
* The type of {#link MessageType} which will denote the style of
* the bubble notification.
* #param actionOnClick
* The {#link CustomTrayIconNotificationBubbleClickEvent} which should be
* fired when the user clicks the bubble notification.
*
* #throws NullPointerException
* If both caption and text are <code>null</code>.
* */
public void displayMessage(final String title, final String message, final MessageType messageType, final CustomTrayIconNotificationBubbleClickEvent actionOnClick)
{
this.showBubbleNotification(title, message, messageType, actionOnClick);
}
/**
* This method will show a bubble notification near the
* {#link CustomTrayIcon}.
*
* #see TrayIcon#displayMessage(String, String, MessageType)
*
* #param title
* The title to be displayed in the bubble notification.
* #param message
* The message to be displayed in the bubble notification.
* #param messageType
* The type of {#link MessageType} which will denote the style of
* the bubble notification.
*
* #throws NullPointerException
* If both caption and text are <code>null</code>.
* */
public void showBubbleNotification(final String title, final String message, final MessageType messageType)
{
this.showBubbleNotification(title, message, messageType, null);
}
/**
* This method will show a bubble notification near the
* {#link CustomTrayIcon}.
*
* #see TrayIcon#displayMessage(String, String, MessageType)
*
* #param title
* The title to be displayed in the bubble notification.
* #param message
* The message to be displayed in the bubble notification.
* #param messageType
* The type of {#link MessageType} which will denote the style of
* the bubble notification.
* #param actionOnClick
* The {#link CustomTrayIconNotificationBubbleClickEvent} which should be
* fired when the user clicks the bubble notification.
*
* #throws NullPointerException
* If both caption and text are <code>null</code>.
* */
public void showBubbleNotification(final String title, final String message, final MessageType messageType, final CustomTrayIconNotificationBubbleClickEvent actionOnClick)
{
this.newBubbleAction = actionOnClick;
super.displayMessage(title, message, messageType);
}
/* GETTERS & SETTERS */
/**
* This will get the override value to be used in-place of the
* {#link CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY CLICK_DETECTION_DELAY}
* default value.
*
* #see CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY
*
* #return The override value to be used in-place of the
* {#link CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY
* CLICK_DETECTION_DELAY} default value.
* */
public int getClickDetectionDelay_override()
{
return this.clickDetectionDelay_override;
}
/**
* This will set the override value to be used in-place of the
* {#link CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY CLICK_DETECTION_DELAY}
* default value.
*
* #see CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY
*
* #param clickDetectionDelay_override
* The override value to be used in-place of the
* {#link CustomTrayIcon#DEFAULT_CLICK_DETECTION_DELAY
* CLICK_DETECTION_DELAY} default value.
* */
public void setClickDetectionDelay_override(final int clickDetectionDelay_override)
{
this.clickDetectionDelay_override = clickDetectionDelay_override;
}
/* PRIVATE METHODS */
/**
* This method will return the delay to have between each click when
* determining if the user performed a single/double/triple click.
*
* #return The delay to have between each click when determining if the user
* performed a single/double/triple click.
* */
private int getClickDetectionDelay()
{
if (this.clickDetectionDelay_override > 0)
{
return this.clickDetectionDelay_override;
}
return CustomTrayIcon.DEFAULT_CLICK_DETECTION_DELAY;
}
/**
* This method will be executed as the constructors last task. <br />
* <br />
* <i>this method will set some attributes on this {#link CustomTrayIcon} and
* apply the appropriate listeners</i>
* */
private void postCreateTasks()
{
this.setImageAutoSize(true);
this.applyCustomListeners();
}
/**
* This will apply the various listeners to this {#link CustomTrayIcon}
* object.
* */
private void applyCustomListeners()
{
// Add an ActionListener which will fire when the user
// clicks a bubble notification.
this.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if (CustomTrayIcon.this.newBubbleAction != null)
{
CustomTrayIcon.this.newBubbleAction.button1_click();
CustomTrayIcon.this.newBubbleAction = null;
}
}
});
// Add a MouseListener on this CustomTrayIcon which will
// fire when the user interacts with this CustomTrayIcon
// using their mouse.
this.addMouseListener(new MouseListener()
{
#Override
public void mouseReleased(MouseEvent arg0)
{
// NOT SUPPORTED BY TrayIcon
}
#Override
public void mousePressed(MouseEvent arg0)
{
// NOT SUPPORTED BY TrayIcon
}
#Override
public void mouseExited(MouseEvent arg0)
{
}
#Override
public void mouseEntered(MouseEvent arg0)
{
}
#Override
public void mouseClicked(MouseEvent arg0)
{
// Clear the bubble notification action as any open
// bubbles should be popped/closed when this interaction
// occurs.
CustomTrayIcon.this.newBubbleAction = null;
// If this MouseEvent was triggered by mouse button 1
// being clicked... then continue.
if (arg0.getButton() == MouseEvent.BUTTON1)
{
long tmp_clickOwnerIndex = 0L;
// Ensure that only one thread can modify the click owner index
// at any given time.
synchronized (CustomTrayIcon.clickLock)
{
// Increase the click owner index so that only the very
// last click can fire an event.
CustomTrayIcon.this.clickOwnerIndex++;
// Store the current value of the click owner index
tmp_clickOwnerIndex = CustomTrayIcon.this.clickOwnerIndex;
}
// Extract the click owner index, which was obtained in a
// thread-safe way, into a final variable so we can access it
// below.
final long tmp_clickOwnerIndex_final = tmp_clickOwnerIndex;
// Launch a new Thread which will sleep for a pre-determined
// period of time to catch the delay of a double/triple click.
(new Thread()
{
int tmp_clickCounter = 0;
public void run()
{
// Ensure that only one thread can modify the click
// counter at any given time.
synchronized (CustomTrayIcon.clickLock)
{
// Increase the number of active clicks that occurred
// during the current detection cycle.
CustomTrayIcon.this.clickCounter++;
// Extract the total number of active clicks that occurred
// during the current detection cycle up to this point.
tmp_clickCounter = CustomTrayIcon.this.clickCounter;
}
try
{
// Sleep for the pre-determined multiple click detection
// time.
// This ensures that we give the use enough time to
// actually perform multiple clicks.
Thread.sleep(CustomTrayIcon.this.getClickDetectionDelay());
}
catch (InterruptedException e)
{
// ignore
}
// Ensure that only one thread can modify the click owner index
// at any given time.
synchronized (CustomTrayIcon.clickLock)
{
// If this click was the last click since the appropriate
// delay, then it's clear that this click should be
// processed.
if (CustomTrayIcon.this.clickOwnerIndex == tmp_clickOwnerIndex_final)
{
// If only one click occurred during the allocated delayed
// time, then fire a button 1 click.
if (tmp_clickCounter == 1)
{
CustomTrayIcon.this.button1_click();
}
// If two clicks occurred during the allocated delayed
// time, then fire a button 2 click.
else if (tmp_clickCounter == 2)
{
CustomTrayIcon.this.button1_doubleClick();
}
// If three clicks occurred during the allocated delayed
// time, then fire a button 3 click.
else if (tmp_clickCounter == 3)
{
CustomTrayIcon.this.button1_tripleClick();
}
}
// Decrease the click owner index which will reset the
// click stack.
CustomTrayIcon.this.clickCounter--;
}
}
}).start();
}
// If this MouseEvent was triggered by mouse button 2
// being clicked... then continue.
else if (arg0.getButton() == MouseEvent.BUTTON2)
{
// Ensure that only one thread can modify the click owner index
// at any given time.
synchronized (CustomTrayIcon.clickLock)
{
// Increase the click owner index so that only the very
// last click can fire an event.
CustomTrayIcon.this.clickOwnerIndex++;
}
CustomTrayIcon.this.button2_click();
}
// If this MouseEvent was triggered by mouse button 3
// being clicked... then continue.
else if (arg0.getButton() == MouseEvent.BUTTON3)
{
// Ensure that only one thread can modify the click owner index
// at any given time.
synchronized (CustomTrayIcon.clickLock)
{
// Increase the click owner index so that only the very
// last click can fire an event.
CustomTrayIcon.this.clickOwnerIndex++;
}
CustomTrayIcon.this.button3_click();
}
}
});
}
}
CustomTrayIconMouseInterface
This interface is used to externalize various user interactions via the mouse.
package com.samples;
import javax.swing.Popup;
/**
* This interface contains several methods which can be fired when a user
* interacts with the {#link CustomTrayIcon} using their mouse.
*
* #author Matthew Weiler
* */
public interface CustomTrayIconMouseInterface
{
/**
* This method will be fired when the user clicks, with mouse button 1, this
* {#link CustomTrayIcon}.
* */
public void button1_click();
/**
* This method will be fired when the user double-clicks, with mouse button
* 1, this {#link CustomTrayIcon}.
* */
public void button1_doubleClick();
/**
* This method will be fired when the user triple-clicks, with mouse button
* 1, this {#link CustomTrayIcon}.
* */
public void button1_tripleClick();
/**
* This method will be fired when the user clicks, with mouse button 2, this
* {#link CustomTrayIcon}.
* */
public void button2_click();
/**
* This method will be fired when the user clicks, with mouse button 3, this
* {#link CustomTrayIcon}. <br />
* <br />
* <i>if a {#link Popup} menu is assigned to this {#link CustomTrayIcon}, it
* will still popup regardless of any actions taken by this method</i>
* */
public void button3_click();
}
CustomTrayIconNotificationBubbleClickEvent
This interface is used to externalize the interaction with the notification bubble.
package com.samples;
/**
* This interface contains several methods which can be fired when a user
* interacts with a bubble notification using their mouse.
*
* #author Matthew Weiler
* */
public interface CustomTrayIconNotificationBubbleClickEvent
{
/**
* This method will be fired when the user clicks, with mouse button 1, this
* bubble notification.
* */
public void button1_click();
}

Related

How to add keyboard shortcuts to actions in java

I am working on a java image editing applet that has an undo/redo action. How do I add a keyboard shortcut to the undo menu so that when command + z (mac) or ctrl + z (windows) is pressed the undo action is triggered? I have read through action and keybinding java tutorials but I am still confused about how to implement keyboard shortcuts. Thanks
public class EditActions {
/** A list of actions for the Edit menu. */
protected ArrayList<Action> actions;
/**
* Create a set of Edit menu actions
*/
public EditActions() {
actions = new ArrayList<Action>();
actions.add(new UndoAction("Undo", null, "Undo", Integer.valueOf(KeyEvent.VK_Z)));
actions.add(new RedoAction("Redo", null, "Redo", Integer.valueOf(KeyEvent.VK_Y)));
}
/**
* Create a menu contianing the list of Edit actions.
* #return The edit menu UI element.
*/
public JMenu createMenu() {
JMenu editMenu = new JMenu("Edit");
for (Action action: actions) {
editMenu.add(new JMenuItem(action));
}
return editMenu;
}
/**
* Action to undo an {#link ImageOperation}.
* #see EditableImage#undo()
*/
public class UndoAction extends ImageAction {
/**
* Create a new undo action.
*
* #param name The name of the action (ignored if null).
* #param icon An icon to use to represent the action (ignored if null).
* #param desc A brief description of the action (ignored if null).
* #param mnemonic A mnemonic key to use as a shortcut (ignored if null).
*/
UndoAction(String name, ImageIcon icon, String desc, Integer mnemonic) {
super(name, icon, desc, mnemonic);
}
/**
* Callback for when the undo action is triggered.
*
* This method is called whenever the UndoAction is triggered.
* It undoes the most recently applied operation.
*
* #param e The event triggering this callback.
*/
public void actionPerformed(ActionEvent e) {
target.getImage().undo();
target.repaint();
target.getParent().revalidate();
}
}

setText on JRadioButton dynamically

I have one JInternalframe in which there are many JRadioButton and JLabel. I want to Retrive Data from Database and display on this JRadioButton and JLabel
Since there can be any numbers of row in Database which will be fetched.
I had successfullly Fetched the data from database but not able to set it on JRadioButton and JLabel
void setData(String s1, String s2, String s3, int cnt) {
//Setting JRadioButton and JLabel Coding Part Here
}
In above function in Variable s1,s2,s3 data exist which i want to Display and in Variable cnt there is value of counter which increment on resultset.next()
Can anyone give me some tips on how to display data on JRadiobutton and JLabel
JRadioButton Variale name is something like BT1,BT2,BT3... So i tried
Since the data is dynamic the GUI should be dynamic as well.
Consider the following example:
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class GuiRow {
/** jRadioButton */
private JRadioButton jRadioButton;
/** studentIdLabel */
private JLabel studentIdLabel;
/** nameLabel */
private JLabel nameLabel;
/** courseLabel */
private JLabel courseLabel;
/**
* Constructs a new instance.
*
* #param studentIdtext
* #param nameText
* #param courseText
*/
public GuiRow(String studentIdtext, String nameText, String courseText) {
this.setjRadioButton(new JRadioButton(""));
// TODO configure radio button
this.setStudentIdLabel(new JLabel(studentIdtext));
this.setNameLabel(new JLabel(nameText));
this.setCourseLabel(new JLabel(nameText));
}
/**
* Get jRadioButton.
*
* #return jRadioButton
*/
public JRadioButton getjRadioButton() {
return this.jRadioButton;
}
/**
* Set jRadioButton.
*
* #param jRadioButton
*/
public void setjRadioButton(JRadioButton jRadioButton) {
this.jRadioButton = jRadioButton;
}
/**
* Get studentIdLabel.
*
* #return studentIdLabel
*/
public JLabel getStudentIdLabel() {
return this.studentIdLabel;
}
/**
* Set studentIdLabel.
*
* #param studentIdLabel
*/
public void setStudentIdLabel(JLabel studentIdLabel) {
this.studentIdLabel = studentIdLabel;
}
/**
* Get nameLabel.
*
* #return nameLabel
*/
public JLabel getNameLabel() {
return this.nameLabel;
}
/**
* Set nameLabel.
*
* #param nameLabel
*/
public void setNameLabel(JLabel nameLabel) {
this.nameLabel = nameLabel;
}
/**
* Get courseLabel.
*
* #return courseLabel
*/
public JLabel getCourseLabel() {
return this.courseLabel;
}
/**
* Set courseLabel.
*
* #param courseLabel
*/
public void setCourseLabel(JLabel courseLabel) {
this.courseLabel = courseLabel;
}
}
This is a simple Object to create and organize a row in your container (probably JPanel, right?)
When you are parsing the resultset you need to build a list of such objects and an add the data in there.
Here is a simple example on how to parse and display the data, which you can split into 2 or more methods and place them in the appropriate entities:
int resultsetSize = resultset.getFetchSize();
//init the list
List<GuiRow> guiRowList = new ArrayList<GuiRow>(resultsetSize);
while (resultset.next()) {
//get the column values
String id = resultset.getString("studentId");
String name = resultset.getString("studentName");
String course = resultset.getString("course");
//create the the entry
GuiRow guiRow = new GuiRow(id, name, course);
//add it to the list
guiRowList.add(guiRow);
}
//now that you have a nice list of rows add them one by one to the container
JPanel container = new JPanel(new GridLayout(resultsetSize, 4));
//further container configuration could be done here ...
for (GuiRow row : guiRowList) {
container.add(row.getjRadioButton());
container.add(row.getStudentIdLabel());
container.add(row.getNameLabel());
container.add(row.getCourseLabel());
}

how can i read class properties (members) in lexicographic order on java?

im trying to build input dialog using swt.
i want to read my class properties and make the dialog window on specified order or even lexicographic order. i'll keep my class properties in linkedhahmap\treemap.
example:
public class MazeProperties {
/** Maze Name. */
private String MazeName;
/** Number of rows in maze. */
private int x;
/** The Floors. */
private int y;
/** Number of columns in maze. */
private int z;
public MazeProperties(String mazeName, int rows, int floors, int columns) {
MazeName = mazeName;
Rows = rows;
Floors = floors;
Columns = columns;
}
public class ClassInputDialog extends Dialog{
/** The shell. */
Shell shell;
/** the generic class. */
private Class<?> template;
/** Property Descriptors give me the ability to see what properties the class contains - and has generic functionalities for setters and getters for fields!. */
PropertyDescriptor[] descs;
/** I wanna have a robust connection between a property to a text box - that way upon pressing OK I could know what class property was written in it.
*
*/
HashMap<PropertyDescriptor,Text> txtMap=new LinkedHashMap<PropertyDescriptor,Text>();
//TreeMap<String,Text> txtMapOrderName=new TreeMap<String,Text>();
//Map<PropertyDescriptor, Text> txtMap = Collections.synchronizedMap(new LinkedHashMap<PropertyDescriptor, Text>());
/** The bonus demanded that this dialog will support all given classes
* but what happens when a class has an enum? a whole new story with combo-boxes and once again I wanna have a connection between the class field enum to the String that was selected in the form.
*
*/
HashMap<PropertyDescriptor,String> enumMap=new **HashMap<PropertyDescriptor,String>();**
/** This is the reference of the instance I will return.
*
*/
private Object input;
/** Ct'r for people that don't know a thing about SWT.
* #param parent - Shell
* #param template - The Class to create form to
*/
public ClassInputDialog(Shell parent,Class<?> template) {
this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL,template);
}
/**
* Ct'r with SWT style.
*
* #param parent - Shell
* #param style - SWT style
* #param template - The Class to create form to
*/
public ClassInputDialog(Shell parent, int style,Class<?> template) {
super(parent, style);
this.template=template;
descs=PropertyUtils.getPropertyDescriptors(template);
setText("Set Properties");
}
/**
* Gets the input.
*
* #return the input
*/
public Object getInput() {
return input;
}
/**
* Sets the input.
*
* #param input the new input
*/
public void setInput(Object input) {
this.input = input;
}
/** Here the window layout is set and the main loop event happens. When window closes User's input is returned.
* #return The user's input
*/
public Object open() {
this.shell = new Shell(getParent(), getStyle());
shell.setText(getText());
createContents(shell);
shell.pack();
shell.open();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
//display.dispose();
return input;
}
/** Creates Window content and layout - sets Labels, Text boxes and combo boxes nicely.
* #param shell - window's parent
*/
private void createContents(final Shell shell) {
shell.setLayout(new GridLayout(2, true));
for(**PropertyDescriptor propDesc: descs**)
if(!propDesc.getName().equals("class"))
{
if(!propDesc.getPropertyType().isEnum())
{
Label label = new Label(shell, SWT.NONE);
label.setText(propDesc.getName());
GridData data = new GridData();
data.horizontalSpan = 2;
label.setLayoutData(data);
final Text text = new Text(shell, SWT.BORDER);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
text.setLayoutData(data);
txtMap.put(propDesc, text);
// txtMapOrderName.put(propDesc.getDisplayName(), text);
System.out.println(propDesc.getDisplayName());
}
else
{
Label label = new Label(shell, SWT.NONE);
label.setText(propDesc.getName());
GridData data = new GridData();
data.horizontalSpan = 2;
label.setLayoutData(data);
final Combo combo = new Combo(shell, SWT.DROP_DOWN);
String[] toCombo=new String[propDesc.getPropertyType().getEnumConstants().length];
for(int i=0;i<propDesc.getPropertyType().getEnumConstants().length;i++)
toCombo[i]=propDesc.getPropertyType().getEnumConstants()[i].toString();
combo.setItems(toCombo);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
combo.setLayoutData(data);
combo.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent arg0) {
enumMap.put(propDesc, combo.getText());
}
#Override
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
}
}
the output is not as the class properties order, it's something like
y
mazeName
x
z
If you want to map keys to values in a deterministic, predictable order, you should store them in a TreeMap, taking care that the key class implements Comparator. If it doesn't, you must implement your own Comparator and pass it as a parameter to the TreeMap constructor.
In your case, if you want PropertyDescriptor as key, you must implement your own Comparator to compare PropertyDescriptor objects.

How to create a moveable SWT shell without title bar/ close button?

If I create a new shell using the following code:
shell = new Shell( Display.getDefault(), SWT.RESIZE);
Then this gives me a shell without a title bar or minimize / maximize buttons, which is what I want. I'm able to resize this window to any size, which works great. But the problem is, the window is fixed in its place, and I cannot move it by dragging it around.
If I add either SWT.CASCADE or SWT.CLOSE, this gives me the title bar and close button, which I don't want, but moreover, it puts a limit on how small the window can be resized, i.e I can't resize it horizontally past a certain limit.
How can I make the window moveable without the close button / title bar? If there's no native way in SWT to do it, can I do it by listening for a mouse drag event and manually setting the location of the shell? If so, how would I get the mouse coordinates from the movement of the mouse?
Help would be appreciated. Thanks!
You need use own listeners. Below code should help:-
public class Demo {
static Boolean blnMouseDown=false;
static int xPos=0;
static int yPos=0;
public static void main(final String[] args) {
Display display=new Display();
final Shell shell = new Shell( Display.getDefault(), SWT.RESIZE);
shell.open();
shell.addMouseListener(new MouseListener() {
#Override
public void mouseUp(MouseEvent arg0) {
// TODO Auto-generated method stub
blnMouseDown=false;
}
#Override
public void mouseDown(MouseEvent e) {
// TODO Auto-generated method stub
blnMouseDown=true;
xPos=e.x;
yPos=e.y;
}
#Override
public void mouseDoubleClick(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
shell.addMouseMoveListener(new MouseMoveListener() {
#Override
public void mouseMove(MouseEvent e) {
// TODO Auto-generated method stub
if(blnMouseDown){
shell.setLocation(shell.getLocation().x+(e.x-xPos),shell.getLocation().y+(e.y-yPos));
}
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.close();
}
}
This is my implementation:
/**
* Class to allow user to move a shell without a title.
*
* #author Laurent Muller
* #version 1.0
*/
public class MoveShellListener implements Listener {
/*
* the parent shell
*/
private final Shell parent;
/*
* the mouse down location
*/
private Point ptMouseDown;
/**
* Creates a new instance of this class.
*
* #param parent
* the shell to handle.
*/
public MoveShellListener(final Shell parent) {
if (parent == null) {
SWT.error(SWT.ERROR_NULL_ARGUMENT);
}
if (parent.isDisposed()) {
SWT.error(SWT.ERROR_WIDGET_DISPOSED);
}
// copy and add listener
this.parent = parent;
addControl(parent);
}
/**
* Adds the given control to the list of listened controls. If the given
* control is an instance of {#link Composite}, the children controls are
* also added.
*
* #param control
* the control to add.
*/
public void addControl(final Control control) {
// check control
if (isDisposed(control) || control.getShell() != parent) {
return;
}
// add listeners
control.addListener(SWT.MouseDown, this);
control.addListener(SWT.MouseUp, this);
control.addListener(SWT.MouseMove, this);
// children
if (control instanceof Composite) {
final Control[] children = ((Composite) control).getChildren();
for (final Control child : children) {
addControl(child);
}
}
}
/**
* Adds the given controls to the list of listened controls. If one of the
* given controls is an instance of {#link Composite}, the children controls
* are also added.
*
* #param controls
* the controls to add.
*/
public void addControls(final Control... controls) {
if (controls != null) {
for (final Control control : controls) {
addControl(control);
}
}
}
/**
* {#inheritDoc}
*/
#Override
public void handleEvent(final Event e) {
switch (e.type) {
case SWT.MouseDown:
onMouseDown(e);
break;
case SWT.MouseUp:
onMouseUp(e);
break;
case SWT.MouseMove:
onMouseMove(e);
break;
}
}
/**
* Removes the given control to the list of listened controls. If the given
* control is an instance of {#link Composite}, the children controls are
* also removed.
*
* #param control
* the control to remove.
*/
public void removeControl(final Control control) {
// check control
if (control == parent || isDisposed(control)
|| control.getShell() != parent) {
return;
}
// remove listeners
control.removeListener(SWT.MouseDown, this);
control.removeListener(SWT.MouseUp, this);
control.removeListener(SWT.MouseMove, this);
// children
if (control instanceof Composite) {
final Control[] children = ((Composite) control).getChildren();
for (final Control child : children) {
removeControl(child);
}
}
}
/**
* Removes the given controls to the list of listened controls. If one of
* the given controls is an instance of {#link Composite}, the children
* controls are also removed.
*
* #param controls
* the controls to remove.
*/
public void removeControls(final Control... controls) {
if (controls != null) {
for (final Control control : controls) {
removeControl(control);
}
}
}
/**
* Checks if the given control is null or disposed.
*
* #param control
* the control to verify.
* #return true if the control is null or
* disposed.
*/
private boolean isDisposed(final Control control) {
return control == null || control.isDisposed();
}
/**
* Handles the mouse down event.
*
* #param e
* the event data.
*/
private void onMouseDown(final Event e) {
if (e.button == 1) {
ptMouseDown = new Point(e.x, e.y);
}
}
/**
* Handles the mouse move event.
*
* #param e
* the event data.
*/
private void onMouseMove(final Event e) {
if (ptMouseDown != null) {
final Point location = parent.getLocation();
location.x += e.x - ptMouseDown.x;
location.y += e.y - ptMouseDown.y;
parent.setLocation(location);
}
}
/**
* Handles the mouse up event.
*
* #param e
* the event data.
*/
private void onMouseUp(final Event e) {
ptMouseDown = null;
}
}

Extending a Class by Adding a Button

This is probably an elementary question. However, I have completed reading the 12th Chapter of Java Programming for the Absolute Beginner and have approached the Challenges section. I cannot quite get the progam to display a labeled button with the extended class.
The specification states:
Extend the JPRButton3D class to create a button that displays a label just like
the AWT Button class you're so familiar with by now. As an extra test, override
the isFocusable() method so that your button class can be traversed and make sure you
paint some special graphic to make it obvious when your button has focus.
How can I edit my code of LabelButton3D and LabelButton3DTest to accomplish this task?
An answer to this specification can potentially aid many new Java programmers in extending their own classes.
Thank you very much for your time and cooperation reagrding this matter.
HERE IS THE CODE FOR JPRButton3D:
package jpr.lightweight;
import java.awt.*;
import java.awt.event.*;
/**
* A lightweight 3D Button class that fires actions when clicked.
* When it is enabled it appears {#link #RAISED RAISED}, when
* it is pressed it appears {#link #SUNK SUNK}, and when it is
* not enabled, it appears {#link #FLAT FLAT}.
*/
public class JPRButton3D extends JPRRectComponent3D {
private boolean pressed;
/**
* This <code>JPRButton3D</code>'s <code>ActionListener</code>.
*/
protected ActionListener actionListener;
private String actionCommand;
/**
* Constructs a new <code>JPRButton3D</code> with minimum size
*/
public JPRButton3D() {
this(ABSOLUTE_MIN_WIDTH, ABSOLUTE_MIN_HEIGHT, 1);
}
/**
* Constructs a new <code>JPRButton3D</code> with the given dimensions.
* #param wide the width
* #param high the height
*/
public JPRButton3D(int wide, int high) {
this(wide, high, 1);
}
/**
* Constructs a new <code>JPRButton3D</code> with the given dimensions
* and border magnitude.
* #param wide the width
* #param high the height
* #param border_magnitude the border's magnitude
*/
public JPRButton3D(int wide, int high, int border_magnitude) {
super(wide, high, RAISED, border_magnitude);
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
public void processMouseEvent(MouseEvent e) {
if (isEnabled() & e.getModifiers() == MouseEvent.BUTTON1_MASK) {
switch(e.getID()) {
case MouseEvent.MOUSE_PRESSED:
pressed = true;
current_appearance = SUNK;
repaint();
break;
case MouseEvent.MOUSE_EXITED:
if (pressed) {
pressed = false;
current_appearance = RAISED;
repaint();
}
break;
case MouseEvent.MOUSE_RELEASED:
if (pressed) {
current_appearance = RAISED;
repaint();
if (actionListener != null) {
actionListener.actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, actionCommand,
e.getModifiers()));
}
}
break;
}
}
super.processMouseEvent(e);
}
/**
* Adds the specified <code>ActionListener</code>
* #param listener <code>ActionListener</code> to add
*/
public void addActionListener(ActionListener listener) {
actionListener = AWTEventMulticaster.add(actionListener, listener);
}
/**
* Removes the specified <code>ActionListener</code>
* #param listener <code>ActionListener</code> to remove
*/
public void removeActionListener(ActionListener listener) {
actionListener = AWTEventMulticaster.remove(actionListener,
listener);
}
/**
* Sets the action command associated with action events.
* #param command The action command.
*/
public void setActionCommand(String command) {
actionCommand = command;
}
/**
* Gets the action command associated with action events.
* #return the action command
*/
public String getActionCommand() {
return actionCommand;
}
/**
* Enables or disables this <code>JPRButton3D</code>.
* #param b <code>true</code> to enable, <code>false</code> to disable
*/
public void setEnabled(boolean b) {
if (b) current_appearance = RAISED;
else current_appearance = FLAT;
repaint();
super.setEnabled(b);
}
}
HERE IS MY CODE FOR LabelButton3DTest (to extend JPRButton3D):
import java.awt.*;
import java.awt.event.*;
import jpr.lightweight.JPRButton3D;
public class LabelButton3DTest extends GUIFrame {
LabelButton3D[] b;
String s;
public LabelButton3DTest() {
super("LabelButton3D Test");
setLayout(new FlowLayout());
b = new LabelButton3D[1];
b[0] = new LabelButton3D("Favorite Button");
b[0] = new LabelButton3D(75, 35, 1);
add(b[0]);
pack();
setVisible(true);
}
public static void main(String args[]) {
new LabelButton3DTest();
}
}
HERE IS MY CODE FOR LabelButton3D:
public class LabelButton3D extends JPRButton3D {
public LabelButton3D(String label) {
}
public LabelButton3D(int wide, int high, int border_magnitude) {
super(wide, high, border_magnitude);
}
}

Categories