如何设置重复背景图像一个JPanel?(How to set repeating backgroun

2019-10-20 01:13发布

我想设置像我们应用背景图像在CSS一个DIV整个JPanel的全宽度重复的图像。 我如何获得在摆动的一个JPanel?

Answer 1:

摇摆不提供此功能开箱即用,所以你需要自己做...

整个过程是相对简单的,

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

有趣的部分是要知道在何处以及如何使用它。 看一眼:

  • 执行自定义绘制
  • 2D图形
  • 读/加载图像

有关各部分的详细信息,你需要知道的。

因此,使用这种作为瓷砖...

我是能够生产这种...

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

}


文章来源: How to set repeating background image to a JPanel?