2010-11-04 77 views
2

我希望图像显示在网格顶部,但它们似乎被打包到不同的面板中。如何使用Java GUI面板?

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.*; 
import javax.imageio.ImageIO; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class test4 extends JPanel { 

BufferedImage image; 
Dimension size = new Dimension(); 

public test4(BufferedImage image) { 
    this.image = image; 

JPanel content = new JPanel(new GridLayout(8,8)); 

for (int i = 0; i < 8*8; ++i) { 
    JPanel panel = new JPanel(); 

    if (i % 2 == i/8 % 2) { 
     panel.setBackground(Color.WHITE); 
    } else { 
     panel.setBackground(Color.DARK_GRAY); 
    } 
     content.add(panel); 
    } 
     this.add(content); 
    } 

protected void paintComponent(Graphics g) { 
    int x = 100; 
    int y = 300; 
    g.drawImage(image, x, y, this); 
} 

public static void main(String[] args) throws IOException { 
String path = "images/Untitled.png"; 
BufferedImage image = ImageIO.read(new File(path)); 

test4 test = new test4(image); 
    JFrame f = new JFrame(); 
    f.setDefaultCloseOperation(JFrame.EXIT_O… 
    f.add(test); 
    f.setSize(400,400); 
    f.setLocationRelativeTo(null); 
    f.setVisible(true); 
    } 
} 

回答

2

但他们似乎是打包成不同的面板。

这是因为默认情况下JPanel使用FlowLayout。 FlowLayout尊重添加到其中的任何组件的大小。一个空的JPanel默认大小为10 X 10,这是FlowLayout的默认水平/垂直间隙。因此,您的棋盘将以其首选大小居中在面板顶部。

您可以通过添加容易解决这个问题:

setLayout(new BorderLayout()); 

我想有图像出现在网格

这没有任何意义,我的顶部?你为什么要在国际象棋棋盘上画一幅图像?

如果您想要棋子,请创建一个JLabel并将标签添加到各个棋子。

如果您想要在游戏开始时显示图像,请使用模态JDialog在JLabel中显示图像。

如果你想更好地理解绘画,那么通常你会重写paintComponent来绘制图像。然而,在这种情况下,图像将被绘制,然后棋盘将被绘制在图像的顶部,所以你永远不会看到图像。

正如前面所说,这样做的正确方法是使用分层窗格,但仍然可以通过重写面板的paint()方法来完成:

public void paint(Graphics g) 
{ 
    super.paint(g); 
    int x = 50; 
    int y = 50; 
    g.drawImage(image, x, y, this); 
} 

要理解这一点是如何工作的请阅读Understanding the Paint Mechanism上的Swing教程部分。现在,您应该看到在子组件被绘制后,图像被绘制。

+0

嗯,我终于得到了标签来改变颜色,所以没有必要再画矩形。对不起,我不明白你在说什么,但我最后修复了它。 – 2010-11-06 10:24:23

0

而不是创造这么多的面板,这将是更有效地只画在循环中使用graphics.fillRect电网。事情是这样的:

public void paint(Graphics g){ 
    int x = 0 ; 
    int y = 0 ; 
    g.setColor(Color.WHITE); 
    while (y <= getHeight()) { 
     //flip the color 
     g.setColor(g.getColor() == Color.WHITE ? Color.DARK_GRAY : Color.WHITE); 

     g.fillRect(x, y, 8, 8); 

     x += 8; 
     if (x >= getWidth()) { 
      x = 0; 
      y += 8; 
     } 
    } 

    //now the image 
    int xi = 100; 
    int yi = 300; 
    g.drawImage(image, xi, yi, this); 
}