2015-09-15 47 views
2

所以我在這裏做了帶有按鈕的網格4x4網格:的ImageIcon數組不填充我的圖片按鈕配置

import java.awt.GridLayout; 

import javax.swing.JPanel; 

public class GameGrid extends JFrame { 

JPanel pan = new JPanel(); 
ShapeButtons[] buttons = new ShapeButtons[16]; 


public GameGrid(){ 
    super("Shape Match"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    pan.setLayout(new GridLayout(4, 4 ,2 ,2)); 
    setResizable(true); 
    setSize(500,500); 
    for (int i = 0; i<16; i++){ 

     buttons[i] = new ShapeButtons(); 
     pan.add(buttons[i]); 

    } 

    add(pan); 
    setVisible(true); 

} 

public static void main(String[] args){ 

    new GameGrid(); 
} 

}

現在我已經創建了一個單獨的類作爲存儲庫對於圖片:

import javax.swing.ImageIcon; 
import javax.swing.JButton; 

public class ShapeButtons extends JButton{ 
ImageIcon[] Shapes = new ImageIcon[8]; 

public ShapeButtons(){ 


    Shapes[0] = new ImageIcon("src/images/Circle.jpg"); 
    Shapes[1] = new ImageIcon("src/images/Diamond.jpg"); 
    Shapes[2] = new ImageIcon("src/images/Square.jpg"); 
    Shapes[3] = new ImageIcon("src/images/rectangle.jpg"); 
    Shapes[4] = new ImageIcon("src/images/Ellipse.jpg"); 
    Shapes[5] = new ImageIcon("src/images/heart.jpg"); 
    Shapes[6] = new ImageIcon("src/images/star.jpg"); 
    Shapes[7] = new ImageIcon("src/images/triangle.jpg"); 
} 

}

但他們未填入我的圖片按鈕,他們只是顯示爲空白。有什麼建議麼?

+0

有什麼異常? –

+0

是的,你沒有設置一個圖標到你創建的Jbutton .. – QuakeCore

回答

0
import javax.swing.ImageIcon; 
import javax.swing.JButton; 


public class ShapeButtons extends JButton{ 
static ImageIcon[] Shapes = new ImageIcon[8]; 
    static { 
    Shapes[0] = new ImageIcon("src/images/Circle.jpg"); 
     Shapes[1] = new ImageIcon("src/images/Diamond.jpg"); 
     Shapes[2] = new ImageIcon("src/images/Square.jpg"); 
     Shapes[3] = new ImageIcon("src/images/rectangle.jpg"); 
     Shapes[4] = new ImageIcon("src/images/Ellipse.jpg"); 
     Shapes[5] = new ImageIcon("src/images/heart.jpg"); 
     Shapes[6] = new ImageIcon("src/images/star.jpg"); 
     Shapes[7] = new ImageIcon("src/images/triangle.jpg"); 
     } 

public ShapeButtons(int picId){ 
    super();//call the jButton cunstructor 

    this.setIcon(shapes[picId]);// sets an icon the the Jbutton object. 
    } 

    public ShapeButtons(){ 
     super();//call the jButton cunstructor    
     } 

    } 

而您對第一個構造函數的調用應該如下所示。

for (int i = 0; i<16; i++){ 

    buttons[i] = new ShapeButtons(someInteger);//for example 
    pan.add(buttons[i]); 

} 

您對第二個構造函數的調用應該如下所示。

for (int i = 0; i<16; i++){ 

    buttons[i] = new ShapeButtons();//for example 
    pan.add(buttons[i]); 
    buttons[i].setIcon(buttons[i].Shapes[someInteger]) 

} 
+0

Yah問題解決了嗎? – QuakeCore

+0

我會檢查我即將得到一些其他錯誤我試圖解決 – Dwayne

+0

最有可能的是它的路徑,你有圖像。 – QuakeCore