简体   繁体   English

无法使用GridBagLayout将JLabel替换为其他JLabel

[英]Cannot replace JLabels with other JLabels using GridBagLayout

I have a program that displays a 4x4 grid of squares through a GridBagLayout layout manager. 我有一个程序可以通过GridBagLayout布局管理器显示4x4的正方形网格。 16 JLabels which all contain a square.gif are displayed. 显示全部包含square.gif的16个JLabel。 When one of the rectangles is clicked, it is supposed to be replaced with a JLabel that contains an image (eg, such as a hat). 单击其中一个矩形时,应该将其替换为包含图像(例如帽子)的JLabel。 So, the image takes the place of the rectangle that is clicked on. 因此,图像取代了被单击的矩形。

However, what happens at the moment is that the rectangle that is clicked only gets replaced sometimes. 但是,此刻发生的是,有时仅替换了所单击的矩形。 Other times, the rectangle disappears but the image does not replace it. 其他时间,矩形消失,但图像不会替代它。 Other times, the image displays in a rectangle that has been clicked previously but only after clicking a different rectangle. 有时,图像显示为一个矩形,该矩形先前已被单击,但仅在单击另一个矩形后才显示。 I have placed the most relevant code below. 我在下面放置了最相关的代码。

public void displayGrid() {


    c.gridx = 0;
    c.gridy = 0;

    try {
        squareImage = ImageIO.read(this.getClass().getResource("stimulus(0).gif"));  //line 37

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JLabel squareLabel = new JLabel(new ImageIcon(squareImage));

    for(int i = 0; i < 16; i++){
        c.gridx = i % 4;
        c.gridy = i / 4;
        squareLabel = new JLabel(new ImageIcon(squareImage));
        squareLabels[i] = squareLabel;
        panel.add(squareLabels[i], c);
        squareLabels[i].addMouseListener(this);

        System.out.println(c.gridx + "" + c.gridy);

    }

    panel.validate();

}

public void mousePressed(MouseEvent e) {

    for(int i = 0; i < squareLabels.length; i++){
        if(e.getSource() == squareLabels[i]){
            //JLabel removedLabel = squareLabels[i];
            c.gridx = (i/4);
            c.gridy = (i%4);
            panel.remove(squareLabels[i]);
            panel.revalidate();
            panel.repaint();
            panel.add(stimuliLabels[0], c);
            panel.validate();

        }
    }

}

In the mousePressed() method, I have attempted to write code that determines the JLabel that is pressed, gets the GridBagConstraints of that JLabel, removes the JLabel that is clicked on, and then replaces that JLabel with the new JLabel with the given GridBagConstraints. 在mousePressed()方法中,我尝试编写代码来确定按下的JLabel,获取该JLabel的GridBagConstraints,删除被单击的JLabel,然后使用给定的GridBagConstraints将JLabel替换为新的JLabel。 However, as I have already said, the program is not working as planned, and I don't know why. 但是,正如我已经说过的那样,该程序无法按计划运行,我也不知道为什么。

Thank you for taking the time to read this. 感谢您抽出时间来阅读。 Any help would be appreciated. 任何帮助,将不胜感激。

Why would you want to swap JLabels? 您为什么要交换JLabel? JLabels are built to hold Icons, usually ImageIcons, and if you want to swap images, best to leave the JLabels in place, and simply swap the ImageIcon that it displays which is easily done by calling setIcon(...) . JLabel的构建是为了容纳图标(通常是ImageIcons),如果要交换图像,最好将JLabel留在原处,并简单地交换它显示的ImageIcon,这可以通过调用setIcon(...)轻松完成。 This is much easier than what you're trying to do, and this works with the library, not against it as you're trying to do. 这比您要尝试的要容易得多,并且可以与库一起使用,而不是像您尝试的那样与之相反。

public void mousePressed(MouseEvent e) {
    // assuming that only JLabels are given this MouseListener:
    JLabel label = (JLabel) e.getSource();
    label.setIcon(desiredNewIcon);
}

For example, from my answer to a similar question : 例如,根据我对类似问题的回答

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class RandomChessMen extends JPanel {
   // for this example I get a sprite sheet that holds several sprite images in it
   // the images can be found here: https://stackoverflow.com/questions/19209650
   private static final String IMAGE_PATH = "http://i.stack.imgur.com/memI0.png";
   private static final int LABEL_COUNT = 2;
   private static final int ICON_COLUMNS = 6;
   private Random random = new Random();

   public RandomChessMen() throws IOException {
      URL url = new URL(IMAGE_PATH);
      BufferedImage largeImg = ImageIO.read(url);
      setLayout(new GridLayout(1, 0));

      // break down large image into its constituent sprites and place into ArrayList<Icon>
      int w = largeImg.getWidth() / ICON_COLUMNS;
      int h = largeImg.getHeight() / LABEL_COUNT;
      for (int i = 0; i < LABEL_COUNT; i++) {
         final List<Icon> iconList = new ArrayList<>();
         int y = (i * largeImg.getHeight()) / LABEL_COUNT;
         // get 6 icons out of large image
         for (int j = 0; j < ICON_COLUMNS; j++) {
            int x = (j * largeImg.getWidth()) / ICON_COLUMNS;
            // get subImage
            BufferedImage subImg = largeImg.getSubimage(x, y, w, h);
            // create ImageIcon and add to list
            iconList.add(new ImageIcon(subImg));
         }

         // create JLabel
         final JLabel label = new JLabel("", SwingConstants.CENTER);
         int eb = 40;
         label.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));

         // get random index for iconList
         int randomIndex = random.nextInt(iconList.size());
         Icon icon = iconList.get(randomIndex); // use index to get random Icon
         label.setIcon(icon); // set label's icon
         label.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
               Icon secondIcon = label.getIcon();
               // so we don't repeat icons
               while (label.getIcon() == secondIcon) {
                  int randomIndex = random.nextInt(iconList.size());
                  secondIcon = iconList.get(randomIndex);
               }
               label.setIcon(secondIcon);
            }
         });
         // add to GUI
         add(label);
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("RandomImages");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      try {
         frame.getContentPane().add(new RandomChessMen());
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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