Dil*_*dra 1 java graphics swing background
我想设置一个在 JPanel 的整个宽度上重复的图像,就像我们将背景图像应用到 CSS 中的 DIV 一样。我如何获得 JPanel 的摆动?
Swing 不提供开箱即用的此功能,因此您需要自己完成...
整体流程比较简单,
for (y = 0 to containerHeight) do
for (x = 0 to containerWidth) do
drawImage(tile, x, y)
Run Code Online (Sandbox Code Playgroud)
有趣的部分是知道在哪里以及如何应用它。看一眼:
有关您需要了解的各个部分的详细信息。
例子
所以用它作为瓷砖......

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

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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3153 次 |
| 最近记录: |