Image in a JPopupMenu
How to put an image on the left corner of a JPopupMenu like the one in the Windows start menu ?
Glancing through the API, setBorder looks promising. You'll probably have to write your own Border.
Similar Messages
-
How to display non-URL-based thumbnail images in JTable
I'm trying to display thumbnail images as a tooltip popup for certain cells in a JTable. The thumbnail images are java image objects that have been retrieved dynamically as the result of a separate process--there is no associated URL. For this reason, I can't use the setToolTipText() method of the JTable.
My attempts to JTable's createToolTip() method also failed as it seems the ToolTipManager never calls this method for a JTable.
As a workaround, I've added a MouseMotionListener to the JTable that detects when the mouse is over the desired table cells. However, I'm not sure how to display the popup over the JTable. The only component that I can get to display over the JTable is a JPopupMenu, but I don't want to display a menu--just the image. Can anyone suggest a way to display a small popup image over the table?
Thanks.Thank You Rodney. This explains why my createToolTip() method wasn't being called, but unfortunately I'm no closer to my goal of displaying a true custom tooltip using a non-URL image rather than a text string. If I make a call to setToolTipText(), at any point, the text argument becomes the tooltip and everything I have tried in createToolTip() has no effect. However, as you pointed out, if I don't call setToolTipText(), the table is not registered with the tooltip manager and createToolTip() is never even called.
To help clarify, I have attached an SSCCE below. Please note that I use a URL image only for testing. In my actual application, the images are available only as Java objects--there are no URLs.
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.net.MalformedURLException;
public class Test {
static Object[][] data = {
{"Cell 0,0", "Cell 0,1"},
{"Cell 1,0", "Cell 1,1"}};
static String[] columnNames = {"Column 0", "Column 1"};
static JFrame frame;
static String testImageURLName = "http://l.yimg.com/k/omg/us/img/7c/0a/4009_4182164952.jpg";
static JTable testTable = new JTable(data, columnNames) {
public JToolTip createToolTip() {
System.out.println("testTable.createToolTip() called");
Image testImage = getTestImage();
// this.setToolTipText("Table ToolTip Text");
JLabel customTipLabel = new JLabel(new ImageIcon(testImage));
customTipLabel.setToolTipText("Custom ToolTip Text");
JToolTip parentTip = super.createToolTip();
parentTip.setComponent(customTipLabel);
return parentTip;
// This image is loaded from a URL only for test purposes!!!
// Ordinarily, the image object would come from the application
// and no URL would be available.
public static Image getTestImage() {
try {
URL iconURL = new URL(testImageURLName);
ImageIcon icon = new ImageIcon(iconURL);
return icon.getImage();
catch (MalformedURLException ex) {
JOptionPane.showMessageDialog(frame,
"Set variable \"testImageName\" to a valid file name");
System.exit(1);
return null;
public static void main(String[] args) throws Exception {
frame = new JFrame("Test Table");
frame.setSize(300, 100);
// Set tool tip text so that table is registered w/ tool tip manager
testTable.setToolTipText("main tooltip");
frame.getContentPane().add(testTable);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} -
Adding image to JDialog in Applet
Well.. I've decided to make my Applet load via a JDialog. Which I know is possible :). And to a start I'll make a very simple Applet in the JDialog, including a background picture, which I just can't add! So to make a long story short, I want an image in my JDialog, but my code gives me a nullPointerException during the Runtime.. Here's the exact Runtime error:
Exception in thread "main" java.lang.NullPointerException
at applet.<init>(applet.java:16)
at applet.main(applet.java:100)And here's my exact applet.java file:
import java.applet.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import javax.swing.plaf.metal.*;
public class applet extends Applet implements Runnable
private ImagePanel panel;
public applet()
panel.createGUI();
public void init()
public void run()
public void start()
Thread thread = new Thread(this);
thread.start();
public void stop()
public void destroy()
public void paint(Graphics g)
private class ImagePanel extends JPanel
BufferedImage buffered = null;
public ImagePanel(String name)
try
buffered = ImageIO.read(new File(name));
setPreferredSize(new Dimension(buffered.getWidth(), buffered.getHeight()));
} catch(IOException ioe)
ioe.printStackTrace();
public void paintComponent(Graphics g)
if (buffered == null)
g.drawString("No Image", 10, 40);
else
g.drawImage(buffered, 0, 0, null);
public void createGUI()
MetalLookAndFeel.setCurrentTheme(new BlackTheme());
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
JDialog dialog = new JDialog();
dialog.setTitle("Applet loading via. JDialog");
Container container = dialog.getContentPane();
ImagePanel panel = new ImagePanel("background.gif");
dialog.pack();
dialog.setSize(1000, 1000);
dialog.setVisible(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
public static void main(String[] args)
applet app = new applet();
}And I don't see any errors, but still.. Runtime error.. -.-' So a little bit of help would really be appretaiced!Okay I guess I spoke to soon.. :O Now I have no Runtime error but my JDialog is completly empty.. And my BlackTheme stopped working.. Not It's a blue theme instead..
Here take a look at my applet.java:
import java.applet.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import javax.swing.plaf.metal.*;
public class applet extends Applet implements Runnable
ImagePanel panel = new ImagePanel("background.gif");
public applet()
panel.createGUI();
public void init()
public void run()
public void start()
Thread thread = new Thread(this);
thread.start();
public void stop()
public void destroy()
public void paint(Graphics g)
private class ImagePanel extends JPanel
BufferedImage buffered = null;
public ImagePanel(String s)
try
buffered = ImageIO.read(new File(s));
setPreferredSize(new Dimension(buffered.getWidth(), buffered.getHeight()));
} catch(IOException ioe)
ioe.printStackTrace();
public void paintComponent(Graphics g)
if(buffered == null)
System.out.println("No image to display.");
else
g.drawImage(buffered, 0, 0, null);
public void createGUI()
MetalLookAndFeel.setCurrentTheme(new BlackTheme());
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
JDialog dialog = new JDialog();
dialog.setTitle("Applet loading via. JDialog");
Container container = dialog.getContentPane();
ImagePanel panel = new ImagePanel("background.gif");
dialog.pack();
dialog.setSize(1000, 1000);
dialog.setVisible(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
public static void main(String[] args)
applet app = new applet();
} -
Image Manipulation from Java to browser
Let me start by saying that I rarely ever post. I try only to do it after I scouring the internet and coming up empty-handed. I have a task that I think should be easy, but of course it is not.
I have an Applet with a JPopupMenu which contains a "Print" JMenuItem. When the item is clicked I use JavaScript via LiveConnect to open a new browser window. My intention is to screen scrape the original page (parse the HTML) and replace any "<OBJECT>" tag with an image of what the Applet is currently showing.
Why?
Well, printing from browsers is buggy at best. I have to support many different OSs and many different versions of Netscape and IE. Some systems can print the HTML page with Applets just fine. Others can do OK and some just crash at the thought.
How?
The idea is that if I recreate a snapshot of the page in a new browser window with images replacing the Applets then the broweser can print that page just fine.
Problem?
I create a BufferedImage in my Applet. The problem comes when I want to tell JavaScript to write the image to the new HTML file. I have seen examples of how this would be done in theory. Has anyone done this?
Background:
I want to use NO server side technologies (i.e. Servlet/JSP) and I do not want to have to sign any files or request any special permissions.
Is there another way to accomplish this goal???
Even if you don't have a good answer, I would appreciate any comments on the matter.
EricGenerate the image from that html page.What would be the best way to generate an image of the
browser rendered page? This is another issue I have
struggled with.Ok, using a JEditorPane it is possible to render a HTML Page. Like all other Swing components it inherits the paintComponent method from JComponent. Simply generate an offscreen image and get its graphics context. Now you can pass this Graphics object the paintComponent and you get an image of your HTML page.
Just make sure your offscreen image has the correct size. I guess this information is available from the JEditorPane.
Use a PixelGrabber to get the image data and scan itfor the area the
default.gif is placed.How would you use the PixelGrabber to find, or scan,
for a 'default.gif' or multiple 'default.gif's? This
too is an issue I have tried to wrap my mind around.This is the tricky part of it. Using the PixelGrabber you should get an array of pixel values. If you iterate thru this array it should be possible to find the pixel values of the default.gif (at least, if you choose a colr for your default.gif that does not appear in your HTML page incliding the other images).
Now you have to replace those pixels with the pixels you have generated for your applets.
Jörg -
JPopupMenu won't disappear after using it!
I'm using a JPopupMenu on a JTable. When I rightclick on a line in my table, I display a dialogbox to make some selections which you can close by clicking an OK button. The problem is, that when I close the dialog box the JPopupMenu won't go away. More exact: Parts of it persist on the screen, but it is more like a background image, since it then is no longer functional (menu items are not highlighted etc.). Does anybody know a workaround to this problem why the pop up menu doesn't go away after using it?
Have you tried firepopupMenuCacelled() ??
This is a method of JPopupmenu that notifies listeners that it hacs been cancelled.... ??
Or maybe a mouse removed listener event to close the JPopupMenu... ?? -
No success in placing background image in JComboBox drop-down!
Hi All! I have an urgent proble, which I was not able to resolve a full day and a half long!!! I want to place a background image in the dropdown (JPopupMenu) of a JComboBox. Not behind the Menu Items (I know how to do that), but behind the popup itself (the items will have a transparent background). I was surprised to find out that I cannot achieve this via UI delegates (seems paint takes place in JComponent), nor with simply subclassing JPopupMenu (because after I draw the image it is overwritten by a background rectangle). I beleive this is not an easy thing to acheive, but I would accept a complicated solution as well.
Can anyone help me?
Thanks, in advance!Try this for ideas. Change the filename to a valid image file on your machine.import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;
public class PictureCombo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PictureCombo().makeUI();
public void makeUI() {
Object[] data = {"One", "Two", "Three", "Four", "Five"};
JComboBox comboBox = new JComboBox(data);
comboBox.setUI(new PictureComboBoxUI());
comboBox.setRenderer(new PictureListCellRenderer());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(comboBox);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
class PictureComboBoxUI extends MetalComboBoxUI {
@Override
protected ComboPopup createPopup() {
return new PictureComboPopup(comboBox);
class PictureComboPopup extends BasicComboPopup {
Image image;
public PictureComboPopup(JComboBox comboBox) {
super(comboBox);
try {
image = ImageIO.read(new File("E:/Java/test.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
@Override
protected JList createList() {
JList retVal = new JList(comboBox.getModel()) {
@Override
public void processMouseEvent(MouseEvent e) {
if (e.isControlDown()) {
e = new MouseEvent((Component) e.getSource(), e.getID(), e.
getWhen(),
e.getModifiers() ^ InputEvent.CTRL_MASK,
e.getX(), e.getY(),
e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(),
e.isPopupTrigger(),
MouseEvent.NOBUTTON);
super.processMouseEvent(e);
@Override
protected void paintComponent(Graphics g) {
if (image != null) {
g.drawImage(image, 0, 0, comboBox);
super.paintComponent(g);
retVal.setOpaque(false);
return retVal;
class PictureListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
Color selBgColor = list.getSelectionBackground();
selBgColor = new Color(selBgColor.getRGB() & 0xA0FFFFFF, true);
setBackground(selBgColor);
setOpaque(isSelected);
return this;
}db -
Question about image loading problem
Dear Java Gurus,
I am writing a simple Java Applet application. Basically what it does is every 3 seconds, it tries to get an image from a server and display it (also based on the browser�s client size to do some resize of the image to fit the width of the browser�s client area). But frequently I got this kind of exceptions:
----------------------------- Exception 1 --------------------------------------
Uncaught error fetching image:
java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at sun.awt.image.PNGFilterInputStream.read(Unknown Source)
at java.util.zip.InflaterInputStream.fill(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.awt.image.PNGImageDecoder.produceImage(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
----------------------------- Exception 2 ------------------------------------------
sun.awt.image.PNGImageDecoder$PNGException: crc corruption
at sun.awt.image.PNGImageDecoder.getChunk(Unknown Source)
at sun.awt.image.PNGImageDecoder.getData(Unknown Source)
at sun.awt.image.PNGFilterInputStream.read(Unknown Source)
at java.util.zip.InflaterInputStream.fill(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.awt.image.PNGImageDecoder.produceImage(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
Which will cause the image goes to blank in the browser and also degreed down the performance, and I do not know where they are coming from. I tried to put try-catch blocks at possible method calls, but still it does not catch these kind exceptions.
---------------------------- My Source Code ----------------------------
import java.io.*;
import java.awt.*;
import java.net.*;
import java.util.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
// This is for Popup Menu
class PopupListener extends MouseAdapter
JPopupMenu popup;
PopupListener(JPopupMenu popupMenu)
popup = popupMenu;
public void mousePressed(MouseEvent e)
maybeShowPopup(e);
public void mouseClicked(MouseEvent e)
maybeShowPopup(e);
public void mouseReleased(MouseEvent e)
maybeShowPopup(e);
private void maybeShowPopup(MouseEvent e)
if (e.isPopupTrigger())
popup.show(e.getComponent(), e.getX(), e.getY());
// Image Component who contains the image and will be hosted in the ScrollPane
class ImageComponent extends JComponent
Image onscrImage;
Dimension comSize;
ImageComponent(Image image)
onscrImage = image;
setDoubleBuffered(true);
comSize = new Dimension(onscrImage.getWidth(null), onscrImage.getHeight(null));
setSize(comSize);
public synchronized void paint(Graphics g)
super.paint(g);
g.drawImage(onscrImage, 0, 0, this);
public Dimension getPreferredSize()
return comSize;
// Update the image with new image
public void setImage(Image img)
onscrImage = img;
comSize = new Dimension(onscrImage.getWidth(null), onscrImage.getHeight(null));
setSize(comSize);
// The main Applet hosted in the browser
public class MWRemotingApplet extends JApplet
//Media Tracker to manage the Image loading
MediaTracker medTracker;
Image my_Image;
// ScollPane who contains the image component
JScrollPane scrollPane;
ImageComponent imgComp;
// The applet base URL and image filename passed from htm who hosted the Applet
URL base;
String filename;
// Schedules getting the image
private java.util.Timer timer;
private int delay = 3000;
private boolean bFitToBrowser = false;
private int iVScrollbarWidth = 20;
// Popup Menu
JPopupMenu jPopupMenu;
JMenuItem popupMenuItem;
public void init()
// Set the layout to GridLayout then the it can fill in the Applet
setLayout(new GridLayout());
try
// getDocumentbase gets the applet path.
base = getCodeBase();
// Get the image file name from the parameter
filename = getParameter("filename");
catch (Exception e)
JOptionPane.showMessageDialog(null, "Failed to get the path and filename of the image!", "Message", 0);
return;
// Create the Media Tracker
medTracker = new MediaTracker(this);
// Download the image from the remote server
// If the image width is greater than the width of the current browser client area
// Resize the image to fit the width
// This is because for some reason, this will lead to image not refreshing
DownloadImage();
//Add the popup menu
jPopupMenu = new JPopupMenu();
popupMenuItem = new JMenuItem("Fit to Browser");
popupMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
bFitToBrowser = !bFitToBrowser;
if(bFitToBrowser)
popupMenuItem.setText("Original Size");
FitToBrowser();
else
popupMenuItem.setText("Fit to Browser");
DownloadImage();
if(my_Image != null)
imgComp.setImage(my_Image);
jPopupMenu.add(popupMenuItem);
// Create the image component
imgComp = new ImageComponent(my_Image);
//Add listener to the image component so the popup menu can come up.
MouseListener popupListener = new PopupListener(jPopupMenu);
imgComp.addMouseListener(popupListener);
// Create the scroll pane
scrollPane = new JScrollPane(imgComp);
scrollPane.setDoubleBuffered(true);
// Catch the resize event of the Applet
addComponentListener(new ComponentAdapter()
public void componentResized(ComponentEvent e)
super.componentResized(e);
if(bFitToBrowser)
FitToBrowser();
else
DownloadImage();
if(my_Image != null)
imgComp.setImage(my_Image);
//Add Components to the Applet.
add("Center", scrollPane);
validate();
// Start the timer to periodically download image
// from remote server
public void start()
timer = new java.util.Timer();
timer.schedule(new TimerTask()
//creates a timertask to schedule
// overrides the run method to provide functionality
public void run()
DownloadImage();
if(my_Image != null)
imgComp.setImage(my_Image);
, 0, delay);
public void stop()
timer.cancel(); //stops the timer
public synchronized void DownloadImage()
if(my_Image != null)
my_Image.flush();
my_Image = null;
try
my_Image = getImage(base, filename);
catch (Exception e)
my_Image = null;
return;
medTracker.addImage( my_Image, 0 );
try
medTracker.waitForAll();
if ( my_Image != null )
medTracker.removeImage(my_Image);
catch (InterruptedException e)
JOptionPane.showMessageDialog(null, "waitForAll failed while downloading the image!", "Message", 0);
catch(Exception e1)
System.out.println("Get Exception = " + e1.getMessage());
e1.printStackTrace();
if(bFitToBrowser)
FitToBrowser();
else if(my_Image.getWidth(null) > this.getSize().width)
FitToWidth();
// Resize the image to fit the browser width and height
public synchronized void FitToBrowser()
if(my_Image != null)
my_Image = my_Image.getScaledInstance(this.getSize().width - 5, this.getSize().height - 5, java.awt.Image.SCALE_SMOOTH);//java.awt.Image.SCALE_AREA_AVERAGING);//java.awt.Image.SCALE_SMOOTH);
medTracker.addImage( my_Image, 0 );
try
medTracker.waitForAll();
medTracker.removeImage(my_Image);
catch (InterruptedException e)
JOptionPane.showMessageDialog(null, "waitForAll failed!", "Message", 0);
catch (Exception e1)
System.out.println("Get Exception = " + e1.getMessage());
e1.printStackTrace();
// Resize the image to fit the browser width only
public synchronized void FitToWidth()
if(my_Image != null)
int fitHeight = (int)((this.getSize().width - iVScrollbarWidth)*(my_Image.getHeight(null)+0.0)/my_Image.getWidth(null));
my_Image = my_Image.getScaledInstance(this.getSize().width - iVScrollbarWidth, fitHeight, java.awt.Image.SCALE_SMOOTH);
medTracker.addImage( my_Image, 0 );
try
medTracker.waitForAll();
medTracker.removeImage(my_Image);
catch (InterruptedException e)
JOptionPane.showMessageDialog(null, "waitForAll failed!", "Message", 0);
catch (Exception e1)
System.out.println("Get Exception = " + e1.getMessage());
e1.printStackTrace();
}[url http://forum.java.sun.com/thread.jsp?thread=518979&forum=14]Please[url http://forum.java.sun.com/thread.jsp?thread=518977&forum=32] do[url http://forum.java.sun.com/thread.jsp?thread=518973&forum=37] not[url http://forum.java.sun.com/thread.jsp?thread=518978&forum=42] crosspost. Or [url http://forum.java.sun.com/thread.jsp?forum=7&thread=518976]double-post. Or post to the wrong forum. Or use non-sense subject.
-
JPopupMenu with JCheckBoxMenuItmes
Hi,
I have a JPopupMenu with JCheckBoxMenuItems and JMenuItems.
The default behaviour of the JPopupMenu is, that it closes on selection of a MenuItem. This behaviour is not really nice for the CheckBoxMenuItems !
Does anyone know a workaround?
Thanks,
ElkeI don't have a workaround, sorry. But I think thats not needed too. The behavior you don't seem to like, is consistent with every application I ever used.
When I click on a menuitem, the only actions I expect is that either the menu closes and a command is executed, or another pop-up menu appears where I make my choice.
If you had a menu that doesn't close when you select or deselect a CheckBoxMenuItem, how do you close that menu? I think a MenuItem "Close this menu" would not be appreciated by any user. I use CheckBoxes on menus sparingly, and only for actions that generate an immediate visual response. (For instance Grayscale Image vs. Colored Image).
If you want the user to have more control about options its better you create a small dialog with your choices and an accept/cancel set of buttons.
Sorry I couldn't help with your initial question. -
Implementing something akin to popup menu that shows image.
I have a situation where I want to display an image, or more accurately part of an image, in a popup below the component the user is on. For example, they might tab to or click on a JTextField and I want to have a popup with an image show up below it. If they move from that JTextField or hit a given key (ESC would be default) it will disappear. Furthermore, on top of all that the popup should not get focus, the focus should remain with the component (the JTextField in this case).
I briefly messed around with JPopupMenu but it's not working particularly well and I'm not sure it's well advised to use it for something that's not actually a menu and I ran into some weird cyclical event cycle when I tried to close it in focusLost. What's the appropriate way of going about this in Swing?Nevermind, I just discovered javax.swing.PopupFactory.
-
TrayIcon with PopupMenu or JPopupMenu ?
Hi. (Sorry for my english.)
I spent last 10 whole days digging menu things in TrayIcon with no success :((.
I have three questions.
I can make JPopupWindow above MS-Windows task bar ( SwingUtilities.windowForComponent( JPupupMenu ).window.setAlwaysOnTop( true ) ) , but how to get keyboard focus/input ????
Looking back to normal PopupMenu ... when it pop up -> it blocks Event Dispatch Thread (EDT) (even if I fire it manually .show() from new Thread , I also tryed install new EventQueue ).
How to make non-blocking PopupMenu ? How to pop up via .show() without "origin" ? ( MouseEvent of TrayIcon returns null in .getComponent() ).
I am using Java 6.0 b105 and u1 b03 at WinXP.
Does anybody know solutions ?
Thanks !
PS: I wrote a very simple example.
It changes tray icon and JPanel background every 0.5 second. The question is : is program continue to work when you popup tray icon menu (right click) ?
This is the last event that goes thru EventQueue after I right click tray icon, and before menu shows (and blocks everythig): java.awt.event.InvocationEvent[INVOCATION_DEFAULT,runnable=sun.awt.windows.WTrayIconPeer$1@128e20a,notifier=null,catchExceptions=false,when=1172501444578] on sun.awt.windows.WToolkit@1e0cf70
//====================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class IsTrayIconMenuBlocking3
public static void main( String[] args ) throws Exception
// --- JFrame & JPanel section
final JPanel jp = new JPanel();
JFrame jf = new JFrame();
jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
jf.add( jp );
jf.setSize( 300 , 300 );
jf.setVisible( true );
// --- menu item action
ActionListener itemExitAction = new ActionListener()
public void actionPerformed( ActionEvent e )
System.out.println( "item action: exit" );
System.exit( 0 );
// --- popup menu
PopupMenu pm = new PopupMenu( "Tray Menu" );
MenuItem mi = new MenuItem( "Exit" );
mi.addActionListener( itemExitAction);
pm.add( mi );
// --- system tray & tray icon
final TrayIcon ti = new TrayIcon( ((ImageIcon)UIManager.getIcon("OptionPane.questionIcon")).getImage() , "Tray Icon" , pm );
SystemTray st = SystemTray.getSystemTray();
ti.setImageAutoSize( true );
st.add( ti );
// --- color & icon changing loop
final Image[] trayIcons = new Image[3];
trayIcons[0] = ((ImageIcon)UIManager.getIcon("OptionPane.errorIcon")).getImage();
trayIcons[1] = ((ImageIcon)UIManager.getIcon("OptionPane.warningIcon")).getImage();
trayIcons[2] = ((ImageIcon)UIManager.getIcon("OptionPane.informationIcon")).getImage();
Runnable colorChanger = new Runnable()
private int counter = 0;
private int icon_no = 0;
public void run()
System.out.println( "Hello from EDT " + counter++ );
if( jp.getBackground() == Color.RED )
jp.setBackground( Color.BLUE );
else
jp.setBackground( Color.RED );
ti.setImage( trayIcons[icon_no++] );
if( icon_no == trayIcons.length ) icon_no = 0;
while( true )
javax.swing.SwingUtilities.invokeLater( colorChanger);
try{Thread.sleep( 500 );} catch ( Exception e ){}
//====================================Hi,
thanks for help.
I am closing this subject.
My solution can be found at http://forums.java.net/jive/thread.jspa?threadID=23466&tstart=0 .
( java.net Forums � Java Desktop Technologies � Swing & AWT � TrayIcon PopupMenu or JPopupMenu ? )
Bye ! -
JPopupMenu or mouseReleased problem
Java rookie here so bear with me. Trying out a swing popupmenu by right clicking I get:
java.lang.NullPointerException
at PresentingLife$MouseWatcher.mouseReleased(PresentingLife.java:580)
every time I release the mouse button in my jpanel and the popup menu never appears, but the cordinates do. I'm sure I'm missing something small.
Here's all the code that applies to:
JPopupMenu popup1 = new JPopupMenu();
popup1.setVisible(true);
JMenuItem item = new JMenuItem("Add Image");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK));
item.setMnemonic(KeyEvent.VK_I);
popup1.add(item);
item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addImageMenuItemActionPerformed(evt);
item = new JMenuItem("Add Text");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.CTRL_MASK));
item.setMnemonic(KeyEvent.VK_T);
popup1.add(item);
item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTextMenuItemActionPerformed(evt);
item = new JMenuItem("Delete Image");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, Event.CTRL_MASK));
item.setMnemonic(KeyEvent.VK_T);
popup1.add(item);
item.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteImageMenuItemActionPerformed(evt);
MouseListener mouser = new MouseWatcher();
jPanel4.addMouseListener(mouser);
addMouseListener(mouser);
private class MouseWatcher extends MouseAdapter
{ public void mouseClicked(MouseEvent e)
{ Graphics g = e.getComponent().getGraphics();
int x = e.getX(), y = e.getY();
if(e.getModifiers() == InputEvent.BUTTON3_MASK)
{ Font font = new Font("Serif", Font.ITALIC, 10);
g.setFont(font);
g.setColor(Color.red);
g.drawString("Right Click at:(" + x + "," + y + ")", x, y);
else // Other buttons.
{ g.drawString("Left Clickat:(" + x + "," + y + ")", x, y);
g.dispose();
public void mousePressed(MouseEvent e)
{ int x = e.getX(), y = e.getY();
if (e.isPopupTrigger())
{ popup1.show(e.getComponent(), x, y);
public void mouseReleased(MouseEvent e)
{ int x = e.getX(), y = e.getY();
if (e.isPopupTrigger())
{ popup1.show(e.getComponent(), x, y);
Thank YouIt looks to me like popup1 must be null. You must be redefining it in your 'MouseWatcher' class.
-
If image file not exist in image path crystal report not open and give me exception error problem
Hi guys my code below show pictures for all employees
code is working but i have proplem
if image not exist in path
crystal report not open and give me exception error image file not exist in path
although the employee no found in database but if image not exist in path when loop crystal report will not open
how to ignore image files not exist in path and open report this is actually what i need
my code below as following
DataTable dt = new DataTable();
string connString = "data source=192.168.1.105; initial catalog=hrdata;uid=sa; password=1234";
using (SqlConnection con = new SqlConnection(connString))
con.Open();
SqlCommand cmd = new SqlCommand("ViewEmployeeNoRall", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
FileStream fs = null;
fs = new FileStream("\\\\192.168.1.105\\Personal Pictures\\" + dr[0] + ".jpg", FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] imgbyte = new byte[fs.Length + 1];
imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)));
dr["Image"] = imgbyte;
fs.Dispose();
ReportDocument objRpt = new Reports.CrystalReportData2();
objRpt.SetDataSource(dt);
crystalReportViewer1.ReportSource = objRpt;
crystalReportViewer1.Refresh();
and exception error as belowFirst: I created a New Column ("Image") in a datatable of the dataset and change the DataType to System.Byte()
Second : Drag And drop this image Filed Where I want.
private void LoadReport()
frmCheckWeigher rpt = new frmCheckWeigher();
CryRe_DailyBatch report = new CryRe_DailyBatch();
DataSet1TableAdapters.DataTable_DailyBatch1TableAdapter ta = new CheckWeigherReportViewer.DataSet1TableAdapters.DataTable_DailyBatch1TableAdapter();
DataSet1.DataTable_DailyBatch1DataTable table = ta.GetData(clsLogs.strStartDate_rpt, clsLogs.strBatchno_Rpt, clsLogs.cmdeviceid); // Data from Database
DataTable dt = GetImageRow(table, "Footer.Jpg");
report.SetDataSource(dt);
crv1.ReportSource = report;
crv1.Refresh();
By this Function I merge My Image data into dataTable
private DataTable GetImageRow(DataTable dt, string ImageName)
try
FileStream fs;
BinaryReader br;
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + ImageName))
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + ImageName, FileMode.Open);
else
// if photo does not exist show the nophoto.jpg file
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + ImageName, FileMode.Open);
// initialise the binary reader from file streamobject
br = new BinaryReader(fs);
// define the byte array of filelength
byte[] imgbyte = new byte[fs.Length + 1];
// read the bytes from the binary reader
imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)));
dt.Rows[0]["Image"] = imgbyte;
br.Close();
// close the binary reader
fs.Close();
// close the file stream
catch (Exception ex)
// error handling
MessageBox.Show("Missing " + ImageName + "or nophoto.jpg in application folder");
return dt;
// Return Datatable After Image Row Insertion
Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP] -
Can you show at a glance which event images are in albums?
Say I had an event containing multiple similar but different images, is there a way to show in the grid view for example which images have already been used in one or more albums?
Would be handy to be able to select a 'show list of albums containing this image'dialogue box. I guess you could hide images you've used but that wouldn't work automatically, nor would any other tagging/rating.
Another approach would be to make albums containing everything in a given event, then move the images out of that album once used, just seems fiddly to me.
ACAC
Would be handy to be able to select a 'show list of albums containing this image'dialogue box.
Yes it would and many people have suggested tit. Add your voice to the chorus at iPhoto Menu -> Provide Apple Feedback.
A workaround - and it's no better - is to go to an album and select al, then give all those pics a keyword. Then in grid view you can see which pics have the keyword. (View -> Keywords)
Regards
TD -
Error while attaching a image in forms10g envion..
hi
i am getting this error while attaching a image in forms 10g enviornment.
ERROR>WUC-24 [URLDownload.pullFile()] Error reading URL http :// 10.80.50.222:7778/forms90/webutil/jacob.dll
regards
Geo.did you install jacob ? with the correct version number described in the installation-guides.
jacob is not an oracle tool, which normally is only useful for COM-commands against windows.
What did you do with the image? -
System Image Restore in Window 8.1
I have not been able to find a data migration application that works at cloning a Windows 8.1 hard drive to a new SSD. With that in mind I want to go about moving the contents, data and operating system from my working C: to a new SSD. I want
to go about it as if I have backed up my system, my C: drive has failed so I need to install a new drive and restore my data and operating system to the new drive. I can't seem to find any simple (this should be simple) straight forward way to do this
nor can I find any form of written instruction on how to go about this.
I would love to have someone articulate this. As it stands I have a fully operational intact C drive. I have completed a disk image to a second separate hard drive. I now want to restore that content to a third (SSD ) drive.
Where do I begin?There is a system backup tool called System Image Backup, follow these steps to conduct this:
Swipe in from the right edge of the screen, and then tap Search.
(If you're using a mouse, point to the upper-right corner of the screen, move the mouse pointer down, and then click Search.)
Enter File History in the search box, tap or click File History, and then click System Image Backup at the left part.
See the screenshot as below, you can backup it on local machine or a DVD or a network share folder:
Besides, I need to point out that this backup method will generate a vhd file, if you want to restore the system you need an DVD installation midia.
You cannot just restore a vhd file directly to the hard drive.
regards
v-yamliu
Maybe you are looking for
-
Locked out of an internal hard drive
I tried to go the repair disk permissions route in disk utilities, but all I get for the missing drive is an image that looks like a curled page. It will not highlight the repair disk utilities button when i click on the drive. I am stumped Any help
-
my phone was running really slow and i had to update the OS. when i did this, the phone when black so i tried the restore. when it's about to get done with the restore, a screen pops up on the itunes that says "unable to connect to Itunes, Error -980
-
Possible to set a system status that has been deleted again
Hi, In the status profile, we have mapped the user status 'Approved' to ' CFAP Approve". When we set the status of the transaction to 'approved', the system status of "TBAP To Be Approved" gets deleted in the system (this can be seen from the transa
-
2 effects at the same time on one Title.
Hello as the title already says, is this possible? Iam making an banner for my site. While a text is moving from left to right it should fade in and out. why can I only choose one effect? what do I have to change?, Iam using adobe cs5. If type of que
-
Problems formatting external 2TB HD??
Hey guys- new to the forum, not sure if this is the right location. I just bought a new WD Elements 2TB USB2.0 HD, and for some reason I can't format it as OS Extended Journaled. It errors out almost immediately, and only allows me to format it as FA