Image Overlay on GridLayout in Java

Is it possible for one set of images to be a "background image" in a gridlayout, and the other images to be a "content" gridlayout?

If not, what is the best way to do this?

+3
source share
2 answers

Is it possible to change the background image with the rest?

Yes, it drawImage()can scale to the full size of the container, as shown here .

Is it possible to set the background image of each cell?

Yes, getSubimage()useful in this context, as shown here .

+4
source

, . JPanel, GridLayout. , JPanel paintComponent. , , false. JLabels, .

: :

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class OverLayImages extends JPanel {
   public static final String BACKGROUND_URL = "http://duke.kenai.com/misc/Bullfight.jpg";
   public static final String CELL_URL = "http://duke.kenai.com/iconSized/penduke-transparent.gif";
   private static final int ROWS = 3;
   private static final int COLS = 4;
   private BufferedImage backgroundImage;
   private BufferedImage cellImage;

   public OverLayImages() throws MalformedURLException, IOException {
      backgroundImage = ImageIO.read(new URL(BACKGROUND_URL));
      cellImage = ImageIO.read(new URL(CELL_URL));
      ImageIcon cellIcon = new ImageIcon(cellImage);
      setBackground(Color.white);

      setPreferredSize(new Dimension(backgroundImage.getWidth(), backgroundImage.getHeight()));

      setLayout(new GridLayout(ROWS, COLS));
      for (int i = 0; i < ROWS; i++) {
         for (int j = 0; j < COLS; j++) {
            JLabel label = new JLabel(cellIcon);
            add(label);
         }
      }
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (backgroundImage != null) {
         g.drawImage(backgroundImage, 0, 0, null);
      }
   }

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

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
+6

All Articles