单击Jbutton后如何显示/隐藏附加到Jlabel的图像?

时间:2022-05-06 00:09:13

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.

我正在编写一个简单的游戏。在Jframe上,我添加了一个Jlabel,我在其上附加了一个图像。我还在Jframe上添加了一个Jbutton。

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

我希望当我点击Jbutton时,图像出现,然后在下一次点击图像隐藏。

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".

Eclipse在代码编辑器的左侧给出了一条错误消息,靠近数字行。它说“Actionbox无法解析为某种类型”。

How could I solve it?

我该怎么解决?

4 个解决方案

#1


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

我希望当我点击Jbutton时,图像出现,然后在下一次点击图像隐藏

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.

或者,不是将Icon设置为null,您可能希望有一个空白图标,这样每次显示图像时标签的大小都不会改变。

#2


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.

不要弄乱按钮的可见性,也不要将其作为最终的局部变量。对于这样的事情,标签应该是一个字段。将它放在您的GUI中并使其可见,因为如果它没有图标或文本,则不会显示任何内容。而是在按钮的ActionListener中,只需通过其setIcon(...)方法更改JLabel的ImageIcon。如果要显示图像,则传入图标,如果不想显示任何内容,则传入null。使JLabel成为类的字段,而不是最终的局部变量。

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,

关于你的代码,创建JButton的ActionListener的一种方法是使用匿名内部类而不是静态私有类。我还建议您可以在类的构造函数中读取图像,而不是每次按下按钮。例如,

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();
         }
      });
   }
}

#3


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

您应该注意,来自ActionListener外部的任何变量都必须是最终变量。这在很大程度上限制了您使用对象

#4


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

我通常使用set bounds(0,0,0,0);每当我想隐藏摇摆组件

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);
 } 
}

#1


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

我希望当我点击Jbutton时,图像出现,然后在下一次点击图像隐藏

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.

或者,不是将Icon设置为null,您可能希望有一个空白图标,这样每次显示图像时标签的大小都不会改变。

#2


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.

不要弄乱按钮的可见性,也不要将其作为最终的局部变量。对于这样的事情,标签应该是一个字段。将它放在您的GUI中并使其可见,因为如果它没有图标或文本,则不会显示任何内容。而是在按钮的ActionListener中,只需通过其setIcon(...)方法更改JLabel的ImageIcon。如果要显示图像,则传入图标,如果不想显示任何内容,则传入null。使JLabel成为类的字段,而不是最终的局部变量。

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,

关于你的代码,创建JButton的ActionListener的一种方法是使用匿名内部类而不是静态私有类。我还建议您可以在类的构造函数中读取图像,而不是每次按下按钮。例如,

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();
         }
      });
   }
}

#3


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

您应该注意,来自ActionListener外部的任何变量都必须是最终变量。这在很大程度上限制了您使用对象

#4


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

我通常使用set bounds(0,0,0,0);每当我想隐藏摇摆组件

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);
 } 
}