简体   繁体   中英

How to show/hide an image attached to a Jlabel after a Jbutton is clicked?

I'm new to programming world, and I need some help. I will try to be as clear as possible.

This is my current situation:

I'm programming a simple game. On a Jframe, I've added a Jlabel on which I attached an image. I've also added a Jbutton on the Jframe.

I would like that when I click on the Jbutton, the image appears and on the next click the image hides.

How could I do it?

Thanks in advance and excuse me for the possible english mistakes.

EDIT Following some instructions given by people, I've reached this point:

button.addActionListener(new Actionbox());

final class Actionbox implements ActionListener
{

   public void actionPerformed (ActionEvent e)
   {
      if (label.getIcon() == null)
         label.setIcon(new ImageIcon(myimage));
      else
         label.setIcon(null);
   } 
}

Eclipse is giving me an error message on the left side of the code editor, near the number lines. It says "Actionbox cannot be resolved to a type".

How could I solve it?

Don't fiddle with your button's visibility, and don't make it a final local variable. For something like this, the label should be a field. Place it in your GUI and leave it visible, since if it doesn't hold an icon or have text, nothing will show on it. Instead in your button's ActionListener, simply change the JLabel's ImageIcon via its setIcon(...) method. Pass in an Icon if you want to show an image and pass in null if you want to show nothing. Make your JLabel a field of the class, not a final local variable.

Regarding your code, one way to create your JButton's ActionListener is to use an anonymous inner class rather than a static private class. I'd also recommend reading in the image just once perhaps in your class's constructor and not each time the button is pressed. For example,

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial") // have GUI extend JPanel
public class ButtonSwapImageGui extends JPanel {
   private static final String IMAGE_PATH = "https://duke.kenai.com/iconSized/duke.gif";

   private Icon imageIcon;  // hold our image
   private Icon nullImageIcon;  //  hold a blank image as a placeholder
   private JLabel label = new JLabel("", SwingConstants.CENTER);

   // throw an exception if image can't be read
   public ButtonSwapImageGui() throws IOException {
      // read in an image from the internet
      URL imageUrl = new URL(IMAGE_PATH);
      BufferedImage image = ImageIO.read(imageUrl);

      // create a blank placeholder image the same size as 
      // the image read in from internet
      int width = image.getWidth();
      int height = image.getHeight();
      BufferedImage nullImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

      // create ImageIcon objects with images read in above
      imageIcon = new ImageIcon(image);
      nullImageIcon = new ImageIcon(nullImage);

      // set JLabel with the placeholder nullImageIcon
      label.setIcon(nullImageIcon);

      // create our button
      JButton button = new JButton("Swap Image");
      // add an anonymous inner class ActionListener to button
      button.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            // get the JLabel's Icon
            Icon currentIcon = label.getIcon();

            // if the Icon matches the null icon
            if (currentIcon == nullImageIcon) {
               // set label with image
               label.setIcon(imageIcon);
            } else {
               // otherwise the label is displaying the image
               // so now set label with the null (blank) icon
               label.setIcon(nullImageIcon);
            }
         }
      });
      // JPanel to hold our button
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(button);

      // set our GUI's layout to BorderLayout
      setLayout(new BorderLayout());

      // add the JLabel to the BorderLayout.CENTER position
      add(label, BorderLayout.CENTER);
      // add button JPanel to the bottom
      add(buttonPanel, BorderLayout.PAGE_END);
   }

   private static void createAndShowGui() {
      // declare our GUI JPanel
      ButtonSwapImageGui mainPanel = null;
      try {
         mainPanel = new ButtonSwapImageGui();
      } catch (IOException e) {
         // if we're here, the image could not be read in
         e.printStackTrace();
         System.exit(-1); // can't get image -- exit program
      }

      JFrame frame = new JFrame("GUI");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel); // add GUI to JFrame
      frame.pack(); // tell layout managers to layout components
      frame.setLocationRelativeTo(null); // center GUI
      frame.setVisible(true);  // display GUI
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

I would like that when I click on the Jbutton, the image appears and on the next click the image hides

add/remove an Icon from the label:

public void actionPerformed(ActionEvent e)
{
    if (label.getIcon() == null)
        label.setIcon(...);
    else
        label.setIcon( null );
}

Or instead of setting the Icon null, you may want to have a blank Icon so that the size of the label doesn't keep changing every time you show an image.

You can do something like this:

button.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    jLabel.setVisible(!jLabel.isVisible()); //Note! jLabel has to be a final variable.     
  }
}

You should note that any variables used inside coming from outside the ActionListener have to be final ones. This largely restricts you into working with objects

I usually use set bounds (0,0,0,0); whenever I want to hide swing components

button.addActionListener(new Actionbox());

final class Actionbox implements ActionListener
{

public void actionPerformed (ActionEvent e)
{
if (label.getIcon() == null) {
 label.setIcon(new ImageIcon(myimage));
  else{
     label.setIcon(null);
 } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM