我了解到,如果您重写
protected void paintComponent(Graphics g)
[您可以将图像绘制为扩展javax.swing.JPanel的类的背景。在我的代码中,我有2个相同类的实例,它们使用几乎完全相同的代码扩展了JPanel,只是在第二个JPanel中具有不同的位置和背景图像,而一个获得背景而另一个则没有。这是我的代码:
public class CardPanel extends JPanel {
private int x, y, width, height;
private BufferedImage background;
public CardPanel(int x, int y, int width, int height, BufferedImage background) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.background = background;
createCardPanel();
}
private void createCardPanel() {
setPreferredSize(new Dimension(width, height));
setMaximumSize(new Dimension(width, height));
setMinimumSize(new Dimension(width, height));
setFocusable(false);
setOpaque(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, x, y, null);
}
}
以及我如何使用它:
pCardPanel = new CardPanel();
dCardPanel = new CardPanel();
宣告CardPanels
private void createCardPanels(String imgPath) {
BufferedImage background = ImageLoader.loadImage(imgPath);
pCardPanel = new CardPanel(0, (height - Card.CARD_HEIGHT), width, Card.CARD_HEIGHT, background.getSubimage(0, (height - Card.CARD_HEIGHT), width, Card.CARD_HEIGHT));
dCardPanel = new CardPanel(0, 0, width, Card.CARD_HEIGHT, background.getSubimage(0, 0, width, Card.CARD_HEIGHT));
this.add(pCardPanel, BorderLayout.SOUTH);
this.add(dCardPanel, BorderLayout.NORTH);
}
创建和添加CardPanel的方法
createCardPanels("/textures/background.png");
使用方法
public void addCardImage(BufferedImage img, boolean playerCard) {
JLabel imgLabel = new JLabel();
ImageIcon icon;
icon = new ImageIcon(img);
imgLabel.setIcon(icon);
cardImages.add(imgLabel);
if (playerCard)
pCardPanel.add(imgLabel);
else
dCardPanel.add(imgLabel);
display.pack();
}
此后一种方法是将名片图像添加到面板中,这部分工作。现在我的问题:this is how it looks.(还有一些其他缺陷,例如卡的位置,但这将是以后的问题,我可以自己解决)如您所见,底部的面板(pCardPanel)没有背景图像。任何想法为什么会这样?在此先感谢
您可以将图像绘制为扩展javax.swing.JPanel的类的背景
背景通常表示图像填满整个面板,并且面板的大小与图像的大小相同。因此,在绘制图像时,代码应为:
g.drawImage(background, 0, 0, null);
所以图像总是画在面板的左上方。
将面板添加到框架后,布局管理器将设置面板的位置。
只是位置不同
pCardPanel = new CardPanel(0, (height - Card.CARD_HEIGHT),
我想问题是“ y”值超出了面板的尺寸,所以您看不到图像。
这是您的首选大小,并不代表您试图在(0,0)以外的其他位置绘制图像的事实,在这种情况下,首选大小应类似于:]]
setPreferredSize(new Dimension(x + width, y + height));
但是,您不想这样做,因为每个组件都应独立于其他组件。它不知道或不在乎您试图将两个面板放置在彼此之上/之下。它应该只担心绘制自己的图像,而让布局管理器担心设置每个面板的位置。
因此,您真正想做的只是在(0,0)处绘制图像,然后让布局管理器确定面板的位置。
您已经在使用BorderLayout。因此,布局管理器的工作是将组件在“ SOUTH”中的位置设置为某个非零的“ y”值。