2010-11-04 35 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); 
}