2014-10-11 149 views
0

我創建了一個JPanel網格,現在我想添加圖像片陣列到網格,最後一行中的循環爲 我有錯誤。添加JLabel數組到JPanel

public static final int WIDTH = 1024; 
public static final int HEIGHT = 640; 
private static final int GRID_ROWS = 20; 
private static final int GRID_COLS = 20; 
private static final int GAP = 1; 
private static final Dimension LAYERED_PANE_SIZE = new Dimension(WIDTH, HEIGHT); 
private static final Dimension LABEL_SIZE = new Dimension(60, 40); 
private GridLayout gridlayout = new GridLayout(GRID_ROWS, GRID_COLS, GAP, GAP); 
private JPanel backingPanel = new JPanel(gridlayout); 
private JPanel[][] panelGrid = new JPanel[GRID_ROWS][GRID_COLS]; 
private JLabel redLabel = new JLabel("Red", SwingConstants.CENTER); 
private JLabel blueLabel = new JLabel("Blue", SwingConstants.CENTER); 

// code in constructor 

backingPanel.setSize(LAYERED_PANE_SIZE); 
backingPanel.setLocation(2 * GAP, 2 * GAP); 
backingPanel.setBackground(Color.black); 
for (int row = 0; row < GRID_ROWS; row++) { 
    for (int col = 0; col < GRID_COLS; col++) { 
     panelGrid[row][col] = new JPanel(new GridBagLayout()); 
     backingPanel.add(panelGrid[row][col]); 
    } 
} 
setLayout(new GridLayout(GRID_ROWS, GRID_COLS)); 
BufferedImage bi = null; 
try { 
    bi = ImageIO.read(new File("assets/image.jpg")); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
for (int r = 0; r < GRID_ROWS; r++) { 
    for (int c = 0; c < GRID_COLS; c++) { 
     int w = bi.getWidth()/GRID_ROWS; 
     int h = bi.getHeight()/GRID_COLS; 
     BufferedImage b = bi.getSubimage(c * w, r * h, w, h); 
     list.add(new JLabel(new ImageIcon(b))); 
     panelGrid[r][c] = new JPanel(new GridBagLayout()); 
     backingPanel.add(panelGrid[r][c]); 
     panelGrid[r][c].add(list.get(r)); 
    } 
} 
+0

類型的表達式必須是一個數組類型,但它決心列出,這是一個arrray私人最終列表 list = new ArrayList (); – 2014-10-11 12:34:26

回答

0

由於listList一個實例,Java是不是C++,你不能指定喜歡operator[]方法。您需要使用list.get(),像這樣:

panelGrid[r][c].add(list.get(r)); 

此外,你應該使用GridBagLayoutGridBagConstraints。因此,呼籲

setLayout(new GridBagLayout()); 
GridBagConstraints gbc = new GridBagConstraints(); 

而改變,你的面板添加到該行:

panelGrid[r][c] = new JPanel(new GridBagLayout()); 
panelGrid[r][c].add(list.get(r)); 
gbc.gridx = r; gbc.gridy = c; 
backingPanel.add(panelGrid[r][c], gbc); 
+0

Dosent的工作,無錯誤,但在運行我沒有任何網格 – 2014-10-11 12:55:10

+0

@ArtinRadpour'for''循環之後'panelGrid'包含什麼? – msrd0 2014-10-11 14:21:17

+0

我在代碼中改變了一些東西,只是在網格中有第一個切片。 'panelGrid [r] [c] = new JPanel(new GridBagLayout()); panelGrid [r] [c] .add(list.get(r)); backingPanel.add(panelGrid [r] [c]);' – 2014-10-11 15:20:46