我在画一些图片时遇到了一点小问题。我使用一个JDialog来显示背景,使用一个单独的类来显示卡片(使用精灵)。
背景显示良好,但JPanel不显示。
这是我的代码:
public Main(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
//Call the board to draw cards
Board plateau = new Board();
this.add(plateau);
}
/**
* Paint the background
*
* @param g
*/
@Override
public void paint(Graphics g) {
try {
Graphics2D g2 = (Graphics2D) g;
this.background_image = ImageIO.read(new File(this.background));
Graphics2D big = this.background_image.createGraphics();
Rectangle rectangle = new Rectangle(0, 0, 20, 20);
g2.setPaint(new TexturePaint(this.background_image, rectangle));
Rectangle rect = new Rectangle(0, 0, this.getWidth(), this.getHeight());
g2.fill(rect);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}以及应该抽牌的班级:
@Override
public void paint(Graphics g) {
try {
this.image = ImageIO.read(new File("Ressources/images/cardsprite.gif"));
//4 lines
for (int i = 0; i < 4; i++) {
//13 rows
for (int j = 0; j < 13; j++) {
//Split one card
BufferedImage temp = this.image.getSubimage(j * this.CARD_WIDTH,
i * this.CARD_HEIGHT, this.CARD_WIDTH, this.CARD_HEIGHT);
g.drawImage(temp, j * this.CARD_WIDTH,
i * this.CARD_HEIGHT, this);
}
}
} catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}如果我将卡片绘制类放入主绘制方法中,它就会工作得很好。
我漏掉了什么吗?
谢谢
发布于 2013-11-27 20:31:45
本质上,您正在打破油漆链,这是防止您的“主要”类画任何它的孩子。
首先看一下AWT和Swing中的绘画,了解油漆过程的概况。
您也不应该覆盖paint,而是应该从扩展JComponent的东西中重写JComponent。
有关更多细节,请查看表演定制绘画。
基本上,您应该创建一个“背景”面板,它负责绘制背景,然后添加负责在其上绘制卡片的组件,确保它是透明的(setOpaque(false)),这样背景就会显示出来。
如果您没有做任何动态效果,您甚至可以为背景窗格提供一个JLabel。
您应该避免在任何可能耗时的paintXxx方法中执行任何操作,比如加载图像。油漆工艺应该优化,让它运行得尽可能快.
https://stackoverflow.com/questions/20252416
复制相似问题