Hows to open an .bmp/.jpeg image using Java - java

I am working on a JFrame/panel that will contain a button. When the user clicks the button, I want an image (which will be stored in the computer hard disk beforehand) to open on the front screen.
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//here i want a code that will somehow open the image from a given directory
}});
Any suggestions on how to go about this ? I have to tell where the image is stored and trigger a virtual 'double click' for the image to pop up on the front screen. Is that even possible using java to synchronize such computer functions?

I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try {
// this is a new frame, where the picture should be shown
final JFrame showPictureFrame = new JFrame("Title");
// we will put the picture into this label
JLabel pictureLabel = new JLabel();
/* The following will read the image */
// you should get your picture-path in another way. e.g. with a JFileChooser
String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
/* until here */
// add the image as ImageIcon to the label
pictureLabel.setIcon(new ImageIcon(img));
// add the label to the frame
showPictureFrame.add(pictureLabel);
// pack everything (does many stuff. e.g. resizes the frame to fit the image)
showPictureFrame.pack();
//this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work.
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
showPictureFrame.setVisible(true);
}
});
} catch (IOException ex) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(ex.getMessage());
}

I think this will work ...
Code:
process = new ProcessBuilder("mspaint","yourFileName.jpeg").start();
This will open your image file with mspaint.....
and also use *Java Advanced Imaging (JAI)*

Try this code
try
{
// the line that reads the image file
BufferedImage image;
// work with the image here ...
image = ImageIO.read(new File("C://Users//Neo//Desktop//arduino.jpg"));
jLabel1.setIcon(new ImageIcon(image));
}
catch (IOException e)
{
// log the exception
// re-throw if desired
}

I'm not sure but try this...
try
{
JLabel picture=new JLabel();
ImageIcon ic=new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("C:\\Users\\Desktop\\xyz.jpg")));
picture.setIcon(ic);
}
catch(Exception)
{
}

Related

Trouble with display of image in NetBeans JFrame

I have trouble with my IT class project in NetBeans and jFrame. When I set the background image, there is a weird rectangle, after changing it via menu bar and menu item. There is no jPanel or other components that could cover it.
This is how I set the background:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
Graphics x= this.getGraphics();
Image img = null;
try
{img = ImageIO.read(new File("noga1.jpg"));
x.drawImage(img, 0, 0, rootPane);}
catch (Exception e) {}
}
And that's what we can see after performing an action:

Add a button menu to javahelp

In my program, I'm using javahelp with helpbroker: all the swing components of the window are automatically generated and positioned.
I would like custom the helpbroker to add a button bar at the bottom of the window like in the image.
What is the easiest way to do it ?
Thanks
The only way to add a help button is to Embed the javahelp in a JFrame:
public class vmHelp {
public static void main(String args[]) {
JHelp helpViewer = null;
String title = "";
try {
// Get the classloader of this class.
ClassLoader cl = vmHelp.class.getClassLoader();
// Use the findHelpSet method of HelpSet to create a URL referencing the helpset file.
// Note that in this example the location of the helpset is implied as being in the same
// directory as the program by specifying "jhelpset.hs" without any directory prefix,
// this should be adjusted to suit the implementation.
String lHelpSetFile = "APP.hs";
URL url = HelpSet.findHelpSet(cl, lHelpSetFile);
if (url == null) {
System.err.println("URL is null, maybe the help set file is wrong: " + lHelpSetFile + ". Look at vmHelp.java");
return;
}
// Create a new JHelp object with a new HelpSet.
HelpSet h = new HelpSet(cl, url);
title = h.getTitle();
helpViewer = new JHelp(h);
// Set the initial entry point in the table of contents.
helpViewer.setCurrentID("top");
} catch (Exception e) {
System.err.println(e.getMessage());
}
// Create a new frame.
JFrame frame = new JFrame();
// Set it's size.
frame.setSize(1000, 800);
// Add the created helpViewer to it.
frame.getContentPane().add(helpViewer);
// Set a default close operation.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(title);
// Make the frame visible.
frame.setVisible(true);
}
}
After we can customize the JFrame as we want, it is easy to add a south panel with a close button.
To make all the help buttons listen our javahelp:
pButton.addActionListener(helpAction(pHelpId));
with helpAction that displays our JFrame
Think also to handle keyboard shortcuts, like the helpbroker:
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
pComponent.registerKeyboardAction(helpAction(pHelpId), KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
To open the help at the wanted section:
helpViewer.setCurrentID("top");
"top" corresponds to tag in the .jhm file

Loading images from jar files (Using Eclipse IDE)

I've got a simple swing application with a JFrame that holds various components. On the JFrame I have a custom toolbar class that extends JPanel. On the JPanel I plan on adding buttons with image icons. My directory structure is as follows:
Project/src/gui (Package holds source files for application)
Project/src/images (Package holds a jar file jlfgr-1_0.jar with button icons and /or individual images files)
The issue is that I want to avoid copying the individual image files to the images package. I'd rather somewhow just load the images directly from the jar file. I've got private method that returns the appropriate icon. This method works, for example if I drag an image file to the images package and call:
button.setIcon(createIcon("/images/Save16.gif"));
private ImageIcon createIcon(String path) {
URL url = getClass().getResource(path);
ImageIcon icon = new ImageIcon(url);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
return icon;
I know this is basic, but how can I get my images directly from the jar file in my current setup?
Thanks.
You can read the image from the stream, thanks to javax.imageio.ImageIO:
private ImageIcon createIcon(String path) {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
ImageIcon icon = new ImageIcon(image);
return icon;
}
This is another way. The images are at location src/images
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(this.getClass().getResource("images/Picture2.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
try {
myPicture = ImageIO.read(this.getClass().getResource("images/broken_image.jpg"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
panel.add(picLabel);

How to get resources working in runnable jar?

I have a Image Icon in my Jframe.I am using a Image in it.When i export into a Runnable Jar.The Image is Not displayed.
String iPath = "res/images/Mobile.png";
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, 315, 610);
InputStream stream = (InputStream) getClass().getResourceAsStream(iPath);
JLabel mobileImageLabel;
mobileImageLabel = new JLabel(new ImageIcon(iPath));
//mobileImageLabel = new JLabel(new ImageIcon(ImageIO.read(stream)));
// mobileImageLabel = new JLabel(new ImageIcon(AppFrame.class.getResource(iPath)));
mobileImageLabel.setBounds(0, 0, 315, 610);
mobileImageLabel.setVisible(true);
layeredPane.add(mobileImageLabel, Integer.valueOf(0));
I googled & found the getResourceAsStream method.But it seems to throw NullPointerException.
So Help me in the Right Direction :)
Thanks for your Help ...
Note
The Method i Tried has been Commented
To set a image in a button I did this:
JButton yourButton = new JButton("text button");
try {
yourButton.setIcon(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png"))));
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
You must have the images inside your project like this:
In your case, the answer I think is to do this:
new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/icon-for-your-button.png")))
Try to replace
String iPath = "res/images/Mobile.png";
By
String iPath = "C:/..../res/images/Mobile.png";
Whenever you are working with images try to put the complete path for the image. So when you will generate your .jar file and try to run it from different place(may be possible that you want the jar should be run from desktop) you will get all the images.

No refreshing, every time the same Image

Basically, I am trying to create an app, that displays images.
filename variable is a path to an image that I want to display. After I start an app, an Image is displayed, but then, when I remove the image from a hard drive (or change other image to the filename name) I don't get any other Image, just the same as before.
public static void main(final String[] args) {
String filename = "C:\\temp\\1.jpeg";
JFrame frame = new JFrame();
frame.getContentPane().add(new JLabel(new ImageIcon(filename)));
frame.pack();
frame.setVisible(true);
// Mouse Listener is only to display another JFrame after mouseClicked event
frame.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
main(args);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
});
}
The image is cached. You need to force it to reload by doing either:
// This works using ImageIO
imageLabel.setIcon( new ImageIcon(ImageIO.read( new File(imageName) ) ) );
// Or you can flush the image
ImageIcon icon = new ImageIcon(imageName);
icon.getImage().flush();
imageLabel.setIcon( icon );
If this is all the code there is, and you are moving files around on the OS, your application will not pick up the changes.
The image has been loaded and will always be told to draw the same way.
You could use a WatchService to watch for changes on the file (I think) or just periodically check to see if the file has changed.
That behaviour you are trying to achieve seems a bit unusual. If that is what you want to do you could set a timer that triggers an event periodically (every "n" seconds or whatever is appropriate), deletes the image icon object and adds a new one. Don't forget to call "pack()" at the end.

Categories

Resources