Java 将JPanel与底层背景图像分层
我正在尝试编写一个棋盘游戏。我想加载游戏板的图像,然后在上面加载一个透明的网格。我编写了一个自定义面板来绘制图像,并将其作为0级添加到分层面板中。然后我用一个Java 将JPanel与底层背景图像分层,java,swing,jpanel,paintcomponent,jlayeredpane,Java,Swing,Jpanel,Paintcomponent,Jlayeredpane,我正在尝试编写一个棋盘游戏。我想加载游戏板的图像,然后在上面加载一个透明的网格。我编写了一个自定义面板来绘制图像,并将其作为0级添加到分层面板中。然后我用一个GridLayout创建一个JPanel,并将其添加到级别1。然后将分层窗格放入滚动窗格,以说明背景图像有点大。我们希望在任何给定的时间,大部分网格都是透明的,但是如果一个玩家的棋子进入一个正方形,那么我会将该正方形设置为代表棋子的颜色。但是,当我将顶部面板设置为透明时(通过调用setOpaque(false)),我只得到一个白色背景,没有
GridLayout
创建一个JPanel
,并将其添加到级别1。然后将分层窗格放入滚动窗格,以说明背景图像有点大。我们希望在任何给定的时间,大部分网格都是透明的,但是如果一个玩家的棋子进入一个正方形,那么我会将该正方形设置为代表棋子的颜色。但是,当我将顶部面板设置为透明时(通过调用setOpaque(false)
),我只得到一个白色背景,没有图像。为什么会这样
public class ImagePanel extends JPanel
{
private Image image;
public ImagePanel(Image image)
{
this.image = image;
this.setPreferredSize(new Dimension(936,889));
}
protected void paintComponent(Graphics g)
{
g.drawImage(image, 0, 0, null);
}
}
下面是主程序中创建面板并嵌套它们的代码。篮板是外框。稍后将设置为可见,因此这不是问题
BufferedImage boardImage = null;
try
{
boardImage = ImageIO.read(new File("Clue Board.jpg"));
}
catch(IOException e)
{
}
ImagePanel background = new ImagePanel(boardImage); //load clue board image
JPanel gameBoard = new JPanel (new GridLayout(24,24)); //yet to add actual squares
gameBoard.setSize(936,889);
gameBoard.setOpaque(false);
JLayeredPane lPane = new JLayeredPane();
lPane.setPreferredSize(new Dimension(936,889));
lPane.add(background, new Integer(0));
lPane.add(gameBoard, new Integer(1));
JScrollPane layerScroller = new JScrollPane(lPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
backBoard.add(layerScroller, BorderLayout.CENTER);
- 尝试调用
如下:super.paintComponent(..)
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, null); }
- 不要调用
使用并覆盖JFrame#setSize(..)
的JPanel
,它将返回正确的大小,然后在getPreferedSize(..)
实例上调用JFrame
,然后将其设置为可见pack()
ImagePanel
类的外观示例:
public class ImagePanel extends JPanel
{
private int width,height;
private Image image;
public ImagePanel(Image image)
{
this.image = image;
//so we can set the JPanel preferred size to the image width and height
ImageIcon ii = new ImageIcon(this.image);
width = ii.getIconWidth();
height = ii.getIconHeight();
}
//so our panel is the same size as image
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
感谢您提供有关设置首选尺寸的建议。然而,它仍然只是画了一个白色的屏幕,而不是图像。我的一个朋友说,他已经让它工作了。我现在没有密码。谢谢大家!为什么不将线路板的布局管理器设置为BorderLayout并将网格面板添加到其中?