我有一种方法可以设置JPanel
的"纹理",但是它抛出了一个NullPointerException
,我不知道为什么。
方法:
void setTexutre(Image tileImage) {
Graphics g = panel.getGraphics();
int width = (int) getBounds().getWidth();
int height = (int) getBounds().getHeight();
int imageW = tileImage.getWidth(panel);
int imageH = tileImage.getHeight(panel);
for (int x5 = 0; x5 < width; x5 += imageW) {
for (int y5 = 0; y5 < height; y5 += imageH) {
g.drawImage(tileImage, x5, y5, panel);
}
}
panel.paint(g);
}
当我调用"g.drawImage(tileImage, x5, y5, panel);"时,会抛出NullPointerException
是真实的图像,我已经检查过了。在上面的方法中,panel
被定义为一个新的JPanel
,并且在我不调用该方法时正常初始化。
感谢您的任何帮助!
- 不要使用
Graphics g = panel.getGraphics();
- 永远不要打电话给
panel.paint(g);
有关在 Swing/AWT 中绘画如何工作的更多详细信息,请参阅在 AWT 中绘画和摆动和执行自定义绘画。
getGraphics
可能会返回null
(甚至记录为这样说),你永远不应该依赖它,这不是自定义绘画的工作方式。 相反,您应该重写组件paintComponent
方法,并在其中执行自定义绘制。
您不控制绘制过程,也不应直接调用paint
,Swing 使用被动渲染算法,这意味着当RepaintManager
决定需要重新绘制组件时,组件会临时更新。 这意味着,即使你可以让你当前的代码工作,当RepaintManager
决定重新绘制panel
的那一刻,你渲染的所有内容都会丢失......
以下是我用于其他任何人查看此问题的类。
package i.am.not.posting.the.real.pack.name;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class TiledPanel extends JPanel {
private BufferedImage tileImage;
public TiledPanel(BufferedImage tileImage) {
this.tileImage = tileImage;
}
protected void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
int imageW = tileImage.getWidth();
int imageH = tileImage.getHeight();
// Tile the image to fill our area.
for (int x = 0; x < width; x += imageW) {
for (int y = 0; y < height; y += imageH) {
g.drawImage(tileImage, x, y, this);
}
}
}
}
只需创建一个 TilePanel 对象即可正确平铺图像。