FileChooser.showOpenDialog showing default java icon on top of the frame - java

I have created a FileChooser in my swing application. when I click on open ,the open dialog box showing default image(java) on top of the frame instead of custom image which i was set for my JFrame.
Sample Code:
JFileChooser filec=new JFileChooser();
int fileval=filec.showOpenDialog(myjframe);
I found some times it is working fine.please help me on this.

You can set the image in the parent JFrame of the JFileChooser which will be reflected in the dialog:
Image image = ImageIO.read(getClass().getResource("MyImage.png"));
myjframe.setIconImage(image);

It seems to work reliably here with this SSCCE. Does this code work reliably where you are?
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class FileChooserIcon {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Image image =
new BufferedImage(32,32,BufferedImage.TYPE_INT_RGB);
JFrame f = new JFrame("Demo");
f.setIconImage(image);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
f.pack();
f.setSize(600,400);
f.setVisible(true);
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(f);
}
};
SwingUtilities.invokeLater(r);
}
}

JFrame f = new JFrame("Edit Configure File");
//Use first two ways getting error: non-static method getClass() cannot be referenced from a static context
//(1) Image image = ImageIO.read(getClass().getResource("images/ctx.Icon"));
//f.setIconImage(image);
//(2) f.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/ctx.PNG")));
//(3) Use third way. It works for me
f.setIconImage(new ImageIcon("images/ctx.PNG").getImage());

Related

How change the image of open Dialog box and how to customize Dialog box in swing?

When I open file that show the dialog box, I need to change Java image and add my own image. How to customize dialog box?
For example, I need to add the Encoding to the dialog box and how to add different type of files to Files of type dropdown box. For Example, i add text, java, html to Files of type box.
Here is my code,
FileDialog fd = new FileDialog(OpenExample.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
To provide an icon for a file chooser or dialog, set an icon for the parent frame.
import java.awt.image.BufferedImage;
import javax.swing.*;
public class FileChooserIcon {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
// see nice icons in chooser!
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {}
JLabel ui = new JLabel("Big Space");
ui.setBorder(new javax.swing.EmptyBorder(40, 200, 40, 200));
JFrame f = new JFrame("Show file chooser icon");
f.setIconImage(new BufferedImage(
20, 20, BufferedImage.TYPE_INT_RGB));
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(ui);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(f); // use frame icon!
}
};
SwingUtilities.invokeLater(r);
}
}
.. how to add different type of files to Files of type dropdown box? For example: add text, java, html to Files of type box.
See How to Use File Choosers: FileChooserDemo2 which offers a file filter for Just Images..

Doesn't show dialog

import java.awt.*;
import java.awt.event.*;
import java.lang.*;
public class Party {
public static void main(String[] args){
System.out.printf("Start\n");
Frame f = new Frame();
Label l = new Label("Party over here!");
Button b = new Button("You bet") ;
Button C = new Button("Shoot me");
Panel p = new Panel();
p.add(l);
System.out.printf("End\n");
}
}
Why don't I get the dialog? Something missing in the example?
public static void main(String[] args){
System.out.printf("Start\n");
Frame f = new Frame();
Label l = new Label("Party over here!");
Button b = new Button("You bet") ;
Button C = new Button("Shoot me");
Panel p = new Panel();
p.add(l);
f.add(p);
f.add(b);
f.add(c);
f.setVisible(true);//<-- make it visible...
System.out.println("End");
}
I think you need to read some more basics about the java GUI, good luck.
The book, in that example, comments, after, new Panel() line:
//more code here...
That means that the code is non necessarily functional.
By adding a line f.setVisible(true); you should see it.
Add to your code:
f.setVisible(true);
Well it seems you have made a frame, and a label and a button, and put something on a panel. But did you show the frame?
Use f.setVisible(true);
And if you want to use a frame I suggest you use JFrame.
But you specified you wanted a dialog to show up, and this is how you do so:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
Look here for more info on dialogs:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#overview

Displaying an image in Java Swing

public class MinesweeperMenu extends MinesweeperPanel{
private JPanel picture = new JPanel();
private JButton play = new JButton("Play");
private JButton highScores = new JButton("High Score and \nStatistics");
private JButton changeMap = new JButton("Create Custom \nor Change Map");
private JButton difficulty = new JButton("Custom or\nChange Difficulty");
private JButton user = new JButton("Change User");
Image img;
public MinesweeperMenu()
{
// Set Layout for the menu
LayoutManager menuLayout = new BoxLayout(menu, BoxLayout.Y_AXIS);
menu.setLayout(menuLayout);
// Set Layout for the window
LayoutManager windowLayout = new BorderLayout();
window.setLayout(windowLayout);
// Add buttons to the panels
menu.add(play);
menu.add(highScores);
menu.add(changeMap);
menu.add(difficulty);
menu.add(user);
// Add picture to the frame
try{
File input = new File("./setup/images/MineMenuPicture.jpg");
img = ImageIO.read(input);
}
catch(IOException ie)
{
System.out.println(ie.getMessage());
}
// Add action listeners
changeMap.addActionListener(new ChangeMapListener());
}
public void paintComponent(Graphics g)
{
// POSITION OF THE PICTURE
int x = 650;
int y = 585;
g.drawImage(img, x, y, null);
}
public void displayFrame()
{
// Display Frame
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public static void main(String[] args)
{
MinesweeperMenu menu = new MinesweeperMenu();
window.pack();
menu.displayFrame();
window.repaint();
}
}
public class MinesweeperPanel extends JFrame{
public static final Color COLOR_KEY = new Color(220, 110, 0);
// Initialize all the objects
public static JFrame window = new JFrame("Minesweeper++");
public static JPanel menu = new JPanel();
// Close the current window
public static void close()
{
window.setVisible(false);
window.dispose();
}
}
I can't get my image to display in the frame. I've tried everything, but I'm getting the impression it's a mistake that I'm not realizing since I am new to Java Swing. Any help would be greatly appreciated.
You're making things difficult for yourself by having a very confusing program structure, and I suggest that you simplify things a lot.
For one, there's no need for your current MinesweeperMenu class to extend MinesweeperPanel, and for the latter class to extend JFrame. Then you have a static JFrame somewhere else -- that's too many JFrames, and to boot, you're trying to display your image in one JFrame but showing the other one that doesn't have the picture. Your program needs just one JFrame and it should probably be created, stuffed with its contents, packed and displayed in one place, not scattered here and there as you're doing.
You're trying to display the picture in a paintComponent override, but this method will never get called since your class extends JFrame (eventually) and JFrame doesn't have this method. You're using the right method, but the class should be extending JPanel, and you should have an #Override annotation above the paintComponent method block to be sure that you're actually overriding a parent method.
You should get rid of all static everything in this program. The only thing static here should be the main method and perhaps some constants, but that's it.
There are more errors here, and I have too little time to go over all of them. Consider starting from the beginning, starting small, getting small bits to work, and then adding them together.
For instance, first create a very small program that tries to read in an image into an Image object, place it in a ImageIcon, place the ImageIcon into a JLabel, and display the JLabel in a JOptionPane, that simple, just to see if you can read in images OK, for example, something like this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class TestImages {
// *** your image path will be different *****
private static final String IMG_PATH = "src/images/image01.jpg";
public static void main(String[] args) {
try {
BufferedImage img = ImageIO.read(new File(IMG_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(null, label);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Then when you've done this, see if you can now create a JPanel that shows the same Image in its paintComponent method, and display this JPanel in a JOptionPane.
Then create a JFrame and display the image-holding JPanel in the JFrame.
Through successive iterations you'll be testing concepts, correcting mistakes and building your program.
File input = new File("./setup/images/MineMenuPicture.jpg");
If MineMenuPicture.jpg is an application resource, it should be in a Jar and accessed by URL obtained from Class.getResource(String).

How to put an image icon, which is taken with JFileChooser, on a label?

Hey there, i have just tried to put an image that is taken with JFileChooser on a label; but it did not work the way i want to. Here is the code that i tried;
import java.io.*;
import javax.swing.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
ImageIcon icon = new ImageIcon(file.getName());
JLabel label = new JLabel(icon);
// JLabel label2 = new JLabel("try try catch it");
panel.add(label);
// panel.add(label2);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Any suggestion?
Close.
You will notice that when you look at file.getName() you see that it will give you the name of the file that you selected. You're looking for the path instead of the name of the file.
See if you can look in the API for File for how to get the path.
You should be using file.getPath() instead of file.getName(). You should also be doing your painting work in the EDT.

Loading animated gif from JAR file into ImageIcon

I'm trying to create a ImageIcon from a animated gif stored in a jar file.
ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
The image loads, but only the first frame of the animated gif. The animation does not play.
If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:
ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
How can I load an animated gif into an ImageIcon from a jar file?
EDIT: Here is a complete test case, why doesn't this display the animation?
import javax.imageio.ImageIO;
import javax.swing.*;
public class AnimationTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AnimationTest test = new AnimationTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
});
}
public AnimationTest() {
super();
try {
JLabel label = new JLabel();
ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
label.setIcon(imageIcon);
imageIcon.setImageObserver(label);
add(label);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This reads gif animation from inputStream
InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));
You have to use getClass().getResource(imgName); to get a URL to the image file. Check out this tutorial from Real's HowTo.
EDIT: Once the image is loaded you have to set the ImageObserver property to get the animation to run.
Since this thread was just linked from a more current thread that had little to do with animated GIFs but got dragged OT, I thought I'd add this trivial source that 'works for me'.
import javax.swing.*;
import java.net.URL;
class AnimatedGifInLabel {
public static void main(String[] args) throws Exception {
final URL url = new URL("http://i.stack.imgur.com/OtTIY.gif");
Runnable r = new Runnable() {
public void run() {
ImageIcon ii = new ImageIcon(url);
JLabel label = new JLabel(ii);
JOptionPane.showMessageDialog(null, label);
}
};
SwingUtilities.invokeLater(r);
}
}
Hopefully it's not too late for this.
I managed to get the animated gif inside my JPanel this way:
private JPanel loadingPanel() {
JPanel panel = new JPanel();
BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layoutMgr);
ClassLoader cldr = this.getClass().getClassLoader();
java.net.URL imageURL = cldr.getResource("img/spinner.gif");
ImageIcon imageIcon = new ImageIcon(imageURL);
JLabel iconLabel = new JLabel();
iconLabel.setIcon(imageIcon);
imageIcon.setImageObserver(iconLabel);
JLabel label = new JLabel("Loading...");
panel.add(iconLabel);
panel.add(label);
return panel;
}
Some points of this approach:
1. The image file is within the jar;
2. ImageIO.read() returns a BufferedImage, which doesn't update the ImageObserver;
3. Another alternative to find images that are bundled in the jar file is to ask the Java class loader, the code that loaded your program, to get the files. It knows where things are.
So by doing this I was able to get my animated gif inside my JPanel and it worked like a charm.

Categories