I want the user to be able to click a button and choose and image which'll be displayed on the screen.
This is the code I wrote. It doesn't seem to work:
uploadBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int retVal = fc.showOpenDialog(EditImage.this);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try{
Image img = ImageIO.read(file);
if(img==null){
//TODO: THE FILE IS NOT AN IMAGE. ERROR
}
ImageIcon ic = new ImageIcon(img);
JLabel imageLabel = new JLabel(ic);
imagePreview.add(imageLabel);
}
catch(IOException ex){
//TODO: THE FILE COULD NOT BE OPENED.
}
}
}
});
imagePreview is a JPanel that I've got somewhere on the screen.
What am I doing wrong?
agree with other answers here is required to call container.revalidate() and (there is an Image, then to required) container.repaint()
but this logics is wrong, you couldn't, why to add/remove JComponent for showing another Image, there no reason for, you can to switch betweens ImageIcons in JLabel - JLabel.setIcon(file)
and there is another issue, Images can increasing used JVM memory, you have to call Icon/ImageIcon.flush() before is added to JLabel.setIcon(a few times mentioned here)
Is imagePreview already visible when you add the JLabel to it? If so, you can't just add components to a visible container; you have to revalidate it.
call imagePreview.revalidate(); imagePreview.repaint() after imagePreview.add(imageLabel);, that needed if you add components to visible container.
Related
Is this the correct way to add an ImageIcon to a JLabel? It doesn't seem to be working when I call the second method.
What type should addCarIcon() be?
//return JLabel that is null
JLabel findEmptySpace()
{
return parkingSpace[emptySpaceNo()];
}
//set icon JLabel
void addCarIcon()
{
ImageIcon carIcon = new ImageIcon("car.png");
findEmptySpace().setIcon(carIcon);
}
//return JLabel that is null
JLabel findEmptySpace()
{
return parkingSpace[emptySpaceNo()];
}
//set icon JLabel
void addCarIcon()
{
// ImageIcon carIcon = new ImageIcon("car.png");
ImageIcon carIcon = new ImageIcon(getClass().getResource("car.png"), null);
findEmptySpace().setIcon(carIcon);
}
I do not reccomend to use ImageIcon(String filename) construction in case of problem, depending on file pakaging. It could work when you run it from IDE, and not work whe you run it from runnable jar.
P.S. Some time ago, I've created IconManager utils to use ico files instead of set of png files. You can test it, maybe it could be useful for you. (This is a link to GitHub: https://github.com/oleg-cherednik/IconManager)
I'm pulling my hair out on this one. Many questions like this here on SO, but I can't get it to work.
I'm trying to add an image to an existing JPanel. The problem is getting the image to be visible in the JPanel. The code runs, but the image is nowhere..
Here's my code:
private void loadImgBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fileChooser.getSelectedFile();
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
imagePnl2.add(picLabel);
imagePnl2.repaint();
imagePnl2.revalidate();
}
else
{
System.out.println("File access cancelled by user.");
}
}
In this question the problem was the missing revalidate(). But that makes no difference here.
What am I missing?
In this question the problem was the missing revalidate(). But that makes no difference here.
Order is important. The code should be:
panel.add(...);
panel.revalidate();
panel.repaint();
The revalidate() invokes the layout manager which in turn determines the components size and location. By default components have a size of (0, 0) so if you invoke repaint() first there is nothing to paint.
Also, an easier solution would be to just add an empty label to your panel when you create the GUI. Then when you want to add the image you can just do:
label.setIcon(...);
The setIcon() method automatically does the revalidate() and repaint() for you.
I am trying to add a JFileChooser to JPanel. Sometimes it works properly and sometimes it shows just the JPanel without the JFileChooser dialogue box. Now i actually don't know what to do . Can anyone help me please?
Here is my code(It is a method):
public File chooseFileFromComputer(){
methodPanel = new JPanel();
methodPanel.setLayout(null);
methodFrame = new JFrame();
methodFrame.setTitle("File Chooser");
methodFrame.setVisible(true);
BufferedImage removeJavaImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
methodFrame.setIconImage(removeJavaImage);
methodLabel = new JLabel("Choose a file: ");
methodLabel.setBounds(10, 10, 80, 20);
methodPanel.add(methodLabel);
fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setBounds(10, 35, 550, 500 );
fileChooser.setVisible(true);
add(fileChooser);
/**
* Action Events #********AE*******#
**/
fileChooser.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
selectedFile = fileChooser.getSelectedFile();
methodFrame.setVisible(false);
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
methodFrame.setVisible(false);
}
}
});
//End of Action Events #________AE_______#
methodPanel.add(fileChooser);
methodFrame.setContentPane(methodPanel);
methodFrame.setResizable(false);
methodFrame.setSize(600, 600);
methodFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
return selectedFile;
}
You are using a null layout and calling setBounds(...) on your components. While this may seem to a newbie the better way to create complex GUI's, it's a fallacy, and more you create Swing GUI's the more you learn to respect and use the layout managers and see that these creatures help immensely in creating flexible, beautiful and if need be, complex GUI's.
add your components to the JFrame, and only then call setVisible(true) on the JFrame.
It doesn't look like you should be using a JFrame at all if you are setting it visible and invisible. Perhaps you really want to use a JDialog or even a free standing JFileChooser dialog.
Edit
You are adding the JFileChooser to more than one container:
add(fileChooser); // ******************* here *************
fileChooser.addActionListener( new ActionListener(){
private File selectedFile;
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
selectedFile = fileChooser.getSelectedFile();
methodFrame.setVisible(false);
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
methodFrame.setVisible(false);
}
}
});
methodPanel.add(fileChooser); // ******** here *******
You can't do this. Only add it to one container, else it may not show correctly or show at all.
Edit 2
You're returning the wrong result from your method. You return the selectedFile variable, but do so before it is ever set since it is set by the ActionListener which is called long after this method returns.
Solution: again, don't use a JFrame here where a modal JDialog would work much better. If you used a modal dialog and returned after the ActionListener is done, your code would work.
Edit 3
But again for my money, I'd just use a JFileChooser as a modal dialog. For example:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose a File");
// don't use null in the method below but rather a reference to your current GUI
int response = fileChooser.showOpenDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println(file);
}
Your JPanel - methodPanel has null layout methodPanel.setLayout(null); try it with for example with FlowLayout
I don't know exactly about your class wherether extends jpanel or not , but you should add filechooser to methodPanel together with label. I tested your code is ok except actionPerform.
methodPanel.add(fielChooser);
I suggest, just try it.
I am writing a program that requires I have a button with an image over top of it, however, so far, I have not been able to get it to work. I have checked several other posts on this site, including How do I add an image to a JButton.
My Code:
public class Tester extends JFrame
{
public Tester()
{
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
setTitle("Image Test");
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton button = new JButton();
try
{
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
button.setIcon(new ImageIcon(img));
}
catch (IOException ex) {}
button.setBounds(100,100,100,100);
panel.add(button);
}
public static void main(String[] args)
{
Tester test = new Tester();
test.setVisible(true);
}
}
When this code runs, an error results: Exception in thread "main" java.lang.IllegalArgumentException: input == null! This error occurs at the line:
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
I don't think that this error is due to the file not being found by java code, as my Images folder is in the src folder (I am using Eclipse) as recommended by the above link.
Does anyone have any ideas to what the problem may be?
Thanks.
While using Eclipse, you don't keep your images into src folder instead you create a Source Folder for this purpose. Please refer to this link regarding how to add images to resource folder in Eclipse.
Use this to create the button.
JButton button = new JButton(new ImageIcon(getClass().getClassLoader()
.getResource("Images/BBishopB.gif")));
And what you are doing is setting the Image as the icon. This doesn't work because the setIcon() method requires objects which implement the Icon interface. Hope this helps.
Try putting a foward slash before the package name in getResource() like so:
Image img = ImageIO.read(getClass().getResource("/Images/BBishopB.gif"));
You can just find the image directly:
JButton jb = new JButton(new ImageIcon("pic.png")); //pic is in project root folder
//Tip: After placing the image in project folder, refresh the project in Eclipse.
OR if the image will be in a JAR, I usually create a function to do the retrieval for me so that I can re-use it.
public static ImageIcon retrieveIcon(String path){
java.net.URL imgUrl = 'classpackage'.'classname'.class.getResource(path);
ImageIcon icon = new ImageIcon(imgUrl);
return icon;
}
Then I'll do,
JButton jb = new JButton(retrieveIcon("/pic.png"));
Image img = ImageIO.read(getClass().getResource("Images\\BBishopB.gif"));
This line tries to do too much all at one time which makes it difficult to track down an error when you get one. I suggest splitting it up:
URL imgURL = getClass().getResource("Images\\BBishopB.gif");
Image img = ImageIO.read(imgURL);
Now you can use the Eclipse debugger to check the return value of imgURL, which is the most likely candidate for the NPE. Even though this doesn't tell you why you get an error message, it narrows down the problem considerably.
Hey All
I want to set a Background for my JWindow. I used setIconImage method in JWindow. but it's not working
How knows what the problem is?
public MainMenu() throws Exception {
try {
bg = ImageIO.read(new File("pics" + File.separator
+ "mainMenuBackground.jpg"));
content = new JWindow(this);
content.setIconImage(bg);
gs.setFullScreenWindow(content);
content.repaint();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.repaint();
} catch (Exception e) {
throw new Exception("Some files are unavailable");
}
}
This lines of code makes a Full-screen window with no background image. why?
How can i fix it?
The setIconImage is for the window icon, not for the background.
Try for instance setBackground. If you want some custom background image, you probably have to either override some paint(Graphics g) method, or set some content pane / add some component that paints the image.