简体   繁体   English

将JLabel数组添加到JPanel

[英]Add JLabel Array to JPanel

I created a JPanel Grid and now I want add Array of image Slices to Grid with loop in last line I have error. 我创建了一个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));
    }
}

Since list is an instance of List , and Java is not C++, you cant specify methods like operator[] . 由于listList一个实例,而Java不是C ++,因此您不能指定诸如operator[]类的方法。 You need to use list.get() , like this: 您需要像这样使用list.get()

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

Also, you should use a GridBagLayout with GridBagConstraints . 另外,您应该将GridBagLayoutGridBagConstraints Therefore, call 因此,请致电

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

And change the lines where you add the panel to this: 并更改将面板添加到其中的行:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM