如何将重复背景图像设置为JPanel?

时间:2014-05-01 07:23:36

标签: java swing graphics background

我想设置一个在JPanel的整个宽度上重复的图像,就像我们将背景图像应用到CSS中的DIV一样。如何在JPanel中获得它?

1 个答案:

答案 0 :(得分:4)

Swing不提供开箱即用的功能,因此您需要自己动手...

整个过程相对简单,

for (y = 0 to containerHeight) do
    for (x = 0 to containerWidth) do
        drawImage(tile, x, y)

有趣的部分是知道在哪里以及如何应用它。看看:

有关您需要了解的各个部分的详细信息。

示例

所以用这个作为瓷砖......

Tile

我能够产生这个......

tiled

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class PaintTitle {

    public static void main(String[] args) {
        new PaintTitle();
    }

    public PaintTitle() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage tile;

        public TestPane() {
            try {
                tile = ImageIO.read(getClass().getResource("/tile.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int tileWidth = tile.getWidth();
            int tileHeight = tile.getHeight();
            for (int y = 0; y < getHeight(); y += tileHeight) {
                for (int x = 0; x < getWidth(); x += tileWidth) {
                    g2d.drawImage(tile, x, y, this);
                }
            }
            g2d.dispose();
        }
    }

}