how to display a image on click of a button using LWUIT

355 Views Asked by At

I am trying to write a application using LWUIT where I want a image to be displayed on click of a button. I have the following code. But I get an exception if the button is clicked twice. Please help me display the image without giving any exception.

        final Form f = new Form("Static TAF");

        Button TrackMe = new Button("TrackMe");

        Image TrackMeicon = null;
        TrackMeicon = Image.createImage("/hello/follow.jpeg");
        final Label TrackMeLabel = new Label(TrackMeicon);    

        TrackMe.addActionListener(new ActionListener()
        {

        public void actionPerformed(ActionEvent ae) 
        {
                 System.out.println("Removing the previous Images");
                 f.addComponent(TrackMeLabel); 
        }
        });

Please Help

3

There are 3 best solutions below

3
On

When you are clicking the button for the first time, image is added to the form. When you are clicking for the second time, that image already exists in the form. So, it will throw "Component already exists" exception.

Your action listener should be

TrackMe.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae) {
              System.out.println("Removing the previous Images");
              f.removeComponent(TrackMeLabel); 
              f.addComponent(TrackMeLabel); 
      }
});
1
On
TrackMe.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent ae) {
          System.out.println("Removing the previous Images");
          final Label TrackMeLabel = new Label(TrackMeicon); 
          f.removeAll();
          f.addComponent(TrackMeLabel); 
  }

});

0
On

If you want yo add only one image you can use this:

....

TrackMe.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent ae) {
          if(!f.containes(TrackMeLabel))
             f.addComponent(TrackMeLabel); 
  }

if you want some imges you need something like that:

....

 TrackMe.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae) {
               Image TrackMeicon = null;
               TrackMeicon = Image.createImage("/hello/follow.jpeg");
               Label TrackMeLabel = new Label(TrackMeicon);   
               f.addComponent(TrackMeLabel); 
      }