It seems like i'm not the only one with that question but I can't find an answer that solves the problem.
I created a Label and assign an Icon to it using WYSIWYG interface designer.
Now I want to change the icon dynamically during runtime.
The logic way would be like this (my first attempt) :
ImageIcon newIcon = new ImageIcon("SomePath");
jLabel1.setIcon(newIcon);
When I do this the Icon simply disapears from the interface so I googled it and someone said to "flush" the icon whatever this means I tried it :
ImageIcon newIcon = new ImageIcon("SomePath");
newIcon.getImage().flush();
jLabel1.setIcon(newIcon);
Still having the same problem.. The icon disapears.
What am I doing wrong ?
Update (Full Method) :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
attempted = myEngine.Attempt('q', word);
if(attempted)
{
this.jTextArea1.setText(myEngine.ChangeEncrypt('q', word, this.jTextArea1.getText()));
}
else
{
JOptionPane.showMessageDialog(null,"The Letter Q is not in the word", "Error",JOptionPane.WARNING_MESSAGE);
jButton1.setEnabled(false);
life ++;
ImageIcon newIcon = myEngine.UpdatePicture(life);
newIcon.getImage().flush();
jLabel1.setIcon(newIcon);
}
This is the UpdatePicture Method :
public ImageIcon UpdatePicture(int life)
{
ImageIcon emptyIcon = new ImageIcon();
if (life == 0)
{
ImageIcon iconZero = new ImageIcon("/hang0.gif");
return iconZero;
}
if (life == 1)
{
ImageIcon iconOne = new ImageIcon("/hang1.gif");
return iconOne;
}
if (life == 2)
{
ImageIcon iconTwo = new ImageIcon("/hang2.gif");
return iconTwo;
}
if (life == 3)
{
ImageIcon iconThree = new ImageIcon("/hang3.gif");
return iconThree;
}
if (life == 4)
{
ImageIcon iconFour = new ImageIcon("/hang4.gif");
return iconFour;
}
if (life == 5)
{
ImageIcon iconFive = new ImageIcon("/hang5.gif");
return iconFive;
}
if (life == 6)
{
ImageIcon iconSix = new ImageIcon("/hang6.gif");
return iconSix;
}
return emptyIcon;
}
Not sure the whole code was necessary but still it might help.
The life variable starts at 0.
I checked and in the UpdatePicture it hits the "/hang1.gif"; and returns it.
If the file is in your src folder then :
ImageIcon ii = new ImageIcon(getClass().getResource("/myFile.gif"));
You really should not put that slash before the name of your icon. It works like that.
I know this is an old question thread, but was having a hell of a time getting a icon replaced on a jLabel when my app was running. This is what finally fixed it:
I created a new folder in the source package named images and put the images in there.
In my Frame (main class) I added this below the initComponents method:
private void moreComponents() {
// get images for initial screen prompts (Skd2_startPanel, loading label1).
// StartPanel is a panel on the Frame that has the loading label on it))
try {
lcImage= new ImageIcon(ImageIO.read(getClass().getResource("/images/LC.png")));
clImage= new ImageIcon(ImageIO.read(getClass().getResource("/images/CL.png")));
} catch (IOException ex) {
Logger.getLogger(Skd2_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
LC and CL.png are the images I want as the label icons.
In a different class I added the following when I wanted the icon to change:
loadingLabel1.setIcon(lcImage); // or clImage as needed.
You'll need the following imports:
import java.util.logging.Logger;
import javax.imageio.ImageIO;
And add these two declarations just below the variables declarations:
static ImageIcon lcImage;
static ImageIcon clImage;
Hope this helps someone searching the web for an answer.
Related
I'm trying to get the image file path or file name of an ImageIcon. I've created a screen in my Java gui app, which contains properties for a custom JButton (extends JButton). From that screen I'm setting some of the main button properties, as if it is enabled, focusable and its ImageIcon. The problem is that as if now, whenever I use this button class, which is in every screen btw, I'm loading all possible images for ImageIcons when the exdened JButton class is used. That causes the screen to freeze before any of the components are shown, while the images are loaded from classpath. In order to change that, in the settings screen, where I hava a JComboBox, containing all images for icons, there, at least that's what I can think of, should be a way to get only the name of the chosen ImageIcon- image path.
The buttons properties are stored in a properties file and that's where I intend to store the .png images names if I can get to them. The idea is to set the image name and when the button is loaded to the screen to look for and load only the image it's supposed to.
Here is a snipet of the button class now; The images are way more, but for demo purposes, I think those are enough. I'd be very grateful if anyone can help with this matter.
public class CustomButton extends JButton {
static Properties FieldProp;
public CustomButton (String text, String name) {
FieldProp = new LoadProperties().loadMainProp();
this.setText(text);
this.setName(name);
Image imgdel=null;
Image imgsmbl=null;
Image imgsmrd=null;
Image imgsmgr=null;
Image imgadd=null;
Image imgauto=null;
Image imgauto1=null;
Image imgavail=null;
Image imgbarc=null;
Image imgdb=null;
Image imgdoc=null;
Image imgexc=null;
Image imgexc1=null;
try {
imgdel = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/delete.png")));
imgsmbl = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_blue.png")));
imgsmrd = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_red.png")));
imgsmgr = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/small_green.png")));
imgadd = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/add_plus.png")));
imgauto = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/automation.png")));
imgauto1 = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/automation1.png")));
imgavail = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/available.png")));
imgbarc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/barcode.png")));
imgdb = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/db.png")));
imgdoc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/doc.png")));
imgexc = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/excel.png")));
imgexc1 = ImageIO.read(Objects.requireNonNull(getClass().getResource("/img/import.png")));
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
}catch (Exception e) {
JOptionPane.showMessageDialog(null,e+"\n"+e.getMessage()+"\n"+ Arrays.toString(e.getStackTrace()),"",JOptionPane.ERROR_MESSAGE);
}
ImageIcon delIcon = new ImageIcon(imgdel);
ImageIcon blIcon = new ImageIcon(imgsmbl);
ImageIcon rdIcon = new ImageIcon(imgsmrd);
ImageIcon grIcon = new ImageIcon(imgsmgr);
ImageIcon addIcon = new ImageIcon(imgadd);
ImageIcon autoIcon = new ImageIcon(imgauto);
ImageIcon autoIcon1 = new ImageIcon(imgauto1);
ImageIcon availIcon = new ImageIcon(imgavail);
ImageIcon barcIcon = new ImageIcon(imgbarc);
ImageIcon dbIcon = new ImageIcon(imgdb);
ImageIcon docIcon = new ImageIcon(imgdoc);
ImageIcon excIcon = new ImageIcon(imgexc);
ImageIcon excIcon1 = new ImageIcon(imgexc1);
Object[] items =
{
noIcon,
delIcon,
blIcon,
rdIcon,
grIcon,
addIcon,
autoIcon,
autoIcon1,
availIcon,
barcIcon,
dbIcon,
docIcon,
excIcon,
excIcon1
};
try {
int iconPosition = Integer.parseInt(FieldProp.getProperty(this.getName() + "Icon"));
String iconProp = FieldProp.getProperty(this.getName() + "Icon");
if (!iconProp.equals("0")) {
this.setIcon((ImageIcon) items[iconPosition]);
}
}catch (Exception e){
e.printStackTrace();
}
try {
this.setEnabled((Boolean.parseBoolean(FieldProp.getProperty(this.getName() + "Enabled"))));
this.setFocusable((Boolean.parseBoolean(FieldProp.getProperty(this.getName() + "Focusable"))));
}catch(Exception e){}
package demo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*`enter code here`
* ComboBoxDemo.java uses these additional files:`enter code here`
* images/Bird.gif
* images/Cat.gif
* images/Dog.gif
* images/Rabbit.gif
* images/Pig.gif
*/
public class Demo extends JPanel
implements ActionListener {
JLabel picture;
#SuppressWarnings({ "rawtypes", "unchecked" })
public Demo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
//Create the combo box, select the item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings);
petList.setSelectedIndex(4);
petList.addActionListener(this);
//Set up the picture.
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
updateLabel(petStrings[petList.getSelectedIndex()]);
picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
//The preferred size is hard-coded to be the width of the
//widest image and the height of the tallest image + the border.
//A real program would compute this.
picture.setPreferredSize(new Dimension(177, 122+10));
//Lay out the demo.
add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Listens to the combo box. */
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
updateLabel(petName);
}
protected void updateLabel(String name) {
ImageIcon icon = createImageIcon("images/" + name + ".png");
picture.setIcon(icon);
picture.setToolTipText("A drawing of a " + name.toLowerCase());
if (icon != null) {
picture.setText(null);
} else {
picture.setText("Image not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Demo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Demo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is the code i have got from oracle but i don't know where it would need to pick images from because every time i create a source folder with images, it still wouldn't pick it up. Or if you could tell me which part of the code is picking the image up? I need to use same kinda code for my work.
ImageIcon icon = createImageIcon("images/" + name + ".png");
This line is providing image path which is images/name.png and value of name could be among these {"Bird", "Cat", "Dog", "Rabbit", "Pig"}
picture.setIcon(icon);
The above line is setting the icon to JLabel picture.
Create a folder named images in root directory of the project and put all .png images in images folder.
If you want to debug where the program fetches the files, you could use the following creating a File object and requesting it's absolute path.
Ideone
System.out.println(new File("images/Bird.png").getAbsolutePath()); // C:\... or /...
See: http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading
I finally found out where the problem lies, but I cannot understand why they way Oracle made the code doesn't work.
Go back to the original code published at
https://www.codetantra.com/java/jdk6.0/tutorial/uiswing/examples/components/ComboBoxDemoProject/src/components/ComboBoxDemo.java
You need to go to the folder where your project is. You will see:
bin
images
src
The images folder may have all the expected image files in it, but the program does not get to them somehow. Copy the gif files into the folder that holds bin, images, and src.
You will now see:
bin
images
src
Bird.gif
Cat.gif
and so forth.
Now go back and change Oracle's code:
// ImageIcon icon = createImageIcon("images/" + name + ".gif"); //This way does not work.
to
ImageIcon icon = createImageIcon(name + ".gif");
Create a folder named images in the same folder where your Demo.java is. And place your images there. The image names, according to your code, are "Bird.png", "Cat.png", "Dog.png", "Rabbit.png", "Pig.png".
So your project structure is something like this:
demo
src
└───demo
│ Demo.java
└───images
Bird.png
Cat.png
Dog.png
Rabbit.png
Pig.png
I hope someone can help me out. Iam trying to create a "countrycombobox" with icons in Java Swing. I found some stuff, but nothing did work for me. Maybe the problem is, that Iam still "new" to Java.
I just want it simple like this: http://www.zomex.com/libs/images/layout/whmcs-template-language-select-w-flags-eco.jpg
Just the flags in front of the countrys.
I would really appreciate a working example. I really wonder, that there is no standard option or a good code snippet(used Google a lot to find help here) for stuff like this.
I found a better example and wanna share my stuff with you. There is just one problem left, that I dont get it sized.
package view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CountryComboBox extends JPanel {
ImageIcon[] images;
String[] imgStrings = {"de"};
/*
* Despite its use of EmptyBorder, this panel makes a fine content
* pane because the empty border just increases the panel's size
* and is "painted" on top of the panel's normal background. In
* other words, the JPanel fills its entire background if it's
* opaque (which it is by default); adding a border doesn't change
* that.
*/
public CountryComboBox() {
super(new BorderLayout());
//Load the images and create an array of indexes.
images = new ImageIcon[imgStrings.length];
Integer[] intArray = new Integer[imgStrings.length];
for (int i = 0; i < imgStrings.length; i++) {
intArray[i] = new Integer(i);
images[i] = createImageIcon("/res/" + imgStrings[i] + ".png");
if (images[i] != null) {
images[i].setDescription(imgStrings[i]);
}
}
//Create the combo box.
JComboBox imgList = new JComboBox(intArray);
ComboBoxRenderer renderer= new ComboBoxRenderer();
imgList.setRenderer(renderer);
imgList.setMaximumRowCount(3);
//Lay out the demo.
add(imgList, BorderLayout.PAGE_START);
//setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = CountryComboBox.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
class ComboBoxRenderer extends JLabel
implements ListCellRenderer {
private Font uhOhFont;
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}
/*
* This method finds the image and text corresponding
* to the selected value and returns the label, set up
* to display the text and image.
*/
#Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
//Set the icon and text. If icon was null, say so.
ImageIcon icon = images[selectedIndex];
String img = imgStrings[selectedIndex];
setIcon(icon);
if (icon != null) {
setText(img);
setFont(list.getFont());
} else {
setUhOhText(img + " (no image available)",
list.getFont());
}
return this;
}
//Set the font and text when no image was found.
protected void setUhOhText(String uhOhText, Font normalFont) {
if (uhOhFont == null) { //lazily create this font
uhOhFont = normalFont.deriveFont(Font.ITALIC);
}
setFont(uhOhFont);
setText(uhOhText);
}
}
}
I call it in a JPanel with absolute layout:
JComponent newContentPane = new CountryComboBox();
newContentPane.setOpaque(true); //content panes must be opaque
newContentPane.setBounds(10, 75, 50, 26);
contentPane.add(newContentPane);
setBounds isnt working, just to get the right position. I cant size it with this.
Best regards
Acanis
First of all, I'd like to inform you all that I'm just a beginner and I've tried many thing without any success.
I've managed to make a JFrame then a JPanel and inside that JPanel, a JLabel with icon. I can retrieve the picture with the button JFileChooser, the picture is resized to fit the JLabel.
My project has exactly 5 files :
ImageFilter: used by LoadFiles
ImagePreview: used by LoadFiles
LoadFiles: JFileChooser class
NewJFrame
Utils: used by LoadFiles
I am using NetBeans IDE and the GUI Builder, I made my class LoadFiles(JFileChooser) so that I just have to drop the class on NewJFrame and the button appears on my JFrame, so that my program can be easily modified (Every class is a module, but yet only one which is LoadFiles) and there is nothing except the variable declared in my NewJFrame.
Here is how my program looks like:
And I want to add two buttons, Next and Previous to navigate between the pictures I already opened in my JLabel.
Class LoadFiles
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
public class LoadFiles extends JButton implements ActionListener {
JFileChooser jfc;
public LoadFiles() {
super("Load");
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (jfc == null) {
jfc = new JFileChooser(".");
jfc.addChoosableFileFilter(new ImageFilter());
jfc.setAcceptAllFileFilterUsed(false);
jfc.setAccessory(new ImagePreview(jfc));
}
jfc.setDialogTitle("test");
int result = jfc.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
System.out.println(file.getParent());
System.out.println(file.getName());
// Read image and place new file icon into preferred locations
BufferedImage newImage = null;
try {
newImage = ImageIO.read(file);
} catch(IOException ex) {
System.out.println("red error: " + ex.getMessage());
}
ImageIcon backgdIcon = new ImageIcon(newImage);
Image zoom = getScaledImage(backgdIcon.getImage(), 471, 189);
Icon iconScaled = new ImageIcon(zoom);
NewJFrame.jLabel1.setIcon(iconScaled);
} else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println(JFileChooser.CANCEL_OPTION);
}
}
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
} }
You can find here my program:
http://www.speedyshare.com/k6e5r/javaapplication29.7z
Please, could you help me?
Edit 1 - Thank you for your comments, I couldn't answer sooner. I will try what you are talking about both MadProgrammer and Andrew Thompson. I will get back to you later hoping I'll make it work.
I'll also remember for my next posts to make it better (MCVE).
Joop Eggen - I am not trying to make a preview icon in JFileChooser, I already have that. I want to be able to retrieve the last image i added to the JLabel with the Previous Button (not Preview). Thank you anyway for your reply.
Edit 2 - Thank's for your advices mbw, what I had in mind when I did that was thatI could use that classe in any application by just dropping it on a GUI and it could work everywhere by just chaning variable's name but you are right, it is not easy to communicate with the other conponent.
I wanted to do the less code possible in the JFrame, so it can be the most modular possible.
I will probably do like you're saying.
Edit 3 -
Finaly I succeeded,
I declare this in the class :
List<BufferedImage> images;
int currentImage = 0;
Then after I put the image in the BufferedImage
//bufferedimage dans la arraylist
if(images == null)
images = new ArrayList<BufferedImage>();
images.add(newImage);
currentImage = images.size() - 1;
And I did two methods
public void nextImage() {
if(images != null && images.get(currentImage + 1) != null )
{
ImageIcon backgdIcon = new ImageIcon(images.get(currentImage + 1));
Image zoom = getScaledImage(backgdIcon.getImage(), 471, 189);//taille en pixels
Icon iconScaled = new ImageIcon(zoom);
NewJFrame.jLabel1.setIcon(iconScaled);
}
}
public void prevImage() {
if(images != null && images.get(currentImage - 1) != null )
{
ImageIcon backgdIcon = new ImageIcon(images.get(currentImage - 1));
Image zoom = getScaledImage(backgdIcon.getImage(), 471, 189);//taille en pixels
Icon iconScaled = new ImageIcon(zoom);
NewJFrame.jLabel1.setIcon(iconScaled);
}
}
Thank you everyone for all your advices. Have a good day.
There are some good ideas in the comments, but I think it will be easier if you change the structure of your code.
If I were you, I would not create extend JButton and create a custom class for each button. It really complicates things, and makes it harder to pass information around the gui to different components that need it.
Instead, to make the code easier to read, I would create three JButtons in your JFrame with the netbeans gui builder: Load, next and previous. Then you can easily add an action event listener for each button and do the all the work in the JFrame. This also makes it really easy to keep a reference to all the loaded pictures for the next and previous button to use.
I have a simple portlet with a few components : 3 Button objects, 1 Slider, 1 MenuBar and a picture assigned to a Label (generated by servlet). Now when I switch between pictures for a Label (I have more of them), I want the picture Label to be placed at the old picture Label object's position:
My picture Label is in the left corner of the portlet. The Button objects, MenuBar, and the Slider are under the picture Label when I select another picture Label the new picture Label is being drawn under the other components (under the Button objects , MenuBar , Slider ) so the Button objects... are top and the picture Label is at the bottom of the portlet
for example, I change the background of the picture Label by selecting the color in the menu :
newItem1.addItem("Blue",new Command(){
public void menuSelected(MenuItem selectedItem){
if(pictureA.isVisible()){
pictureB.setVisible(false);
pictureC.setVisible(false);
window.removeComponent(pictureA);
pictureA= new Label("<img src=http://localhost:8888/portlet/KiviatDiagramm?background=blue", Label.CONTENT_XHTML);
window.addComponent(pictureA);
} else {
window.showNotification("", Notification.TYPE_WARNING_MESSAGE);
}
}
});
UPDATE :
I have switched from Label objects to embedded images (Embedded) (which is a lot better) I have tried to reassign the resource on the Embedded object with the new color but it doesn't work, here is what I've done :
public void init() {
URL PictureAUrl= null;
try {
pictureAUrl= new URL("http://localhost:8888/portlet/pictureA");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL PictureBUrl= null;
try {
pictureAUrl= new URL("http://localhost:8888/portlet/pictureB");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL pictureCUrl= null;
try {
pictureCUrl= new URL("http://localhost:8888/portlet/pictureC");
} catch (MalformedURLException e) {
e.printStackTrace();
}
final Embedded pictureA = new Embedded("", new ExternalResource(pictureAURL));
pictureA .setType(Embedded.TYPE_IMAGE);
final Embedded pictureB = new Embedded("", new ExternalResource(pictureBURL));
pictureB .setType(Embedded.TYPE_IMAGE);
final Embedded pictureC = new Embedded("", new ExternalResource(pictureCURL));
pictureC .setType(Embedded.TYPE_IMAGE);
newItem.addItem("ColorBlue", new Command(){
public void menuSelected(MenuItem selectedItem) {
if(!pictureA.equals(pictureB )){
Resource newPictureResource = new ExternalResource("http://localhost:8888/portlet/pictureA?background=blue");
newPictureResource.setType(Embedded.TYPE_IMAGE);
pictureA.setResource(newPictureResource);
}
else {
window.showNotification("Please select pictureA");
}
}
});
rickthomas is correct, you should use the replaceComponent method. I'm pretty sure that the main problem here is that after you have removed the picture, you call addComponent(pictureA) which actually adds the component to the end of the component list. If you don't have a reference to the old picture and it's the first component, then you can use this:
window.replaceComponent(window.getComponentIterator().next(), newPicture);
In addition to that, you don't have to write HTML to show images. You can use Embedded.
If the images are in your classpath, you can use the following:
Embedded newPicture = new Embedded("", new ClassResource("my-picture.png", myApplication));
newPicture.setType(Embedded.TYPE_IMAGE);
window.replaceComponent(oldPicture, newPicture);
If they are found somewhere else, use this:
URL url = new URL("http://localhost:8888/portlet/KiviatDiagramm?background=blue");
Embedded newPicture = new Embedded("", new ExternalResource(url));
newPicture.setType(Embedded.TYPE_IMAGE);
window.replaceComponent(oldPicture, newPicture);
This might solve your problem.
Looking at the Vaadin API javadoc,
I found this
public void replaceComponent(Component oldComponent,Component newComponent)
I haven't tested it... but it should work.