【问题标题】:Add JLabel Array to JPanel将 JLabel 数组添加到 JPanel
【发布时间】:2014-10-11 12:30:37
【问题描述】:

我创建了一个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));
    }
}

【问题讨论】:

  • 表达式的类型必须是数组类型,但它解析为 List,这是一个数组 private final List list = new ArrayList();

标签: java arrays loops jpanel jlabel


【解决方案1】:

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

【讨论】:

  • @ArtinRadpour panelGridfor 循环之后包含什么?
  • 我在代码中更改了一些内容,现在只在 grid 中有第一个切片。 panelGrid[r][c] = new JPanel(new GridBagLayout()); panelGrid[r][c].add(list.get(r)); backingPanel.add(panelGrid[r][c]);
  • @ArtinRadpour 您能否发布您如何创建面板和添加组件的整个代码?
  • @ArtinRadpour 请看我的编辑,它现在应该可以工作了
  • 我这里有错误 new GridBagConstraints(r, c));错误:构造函数 GridBagConstraints(int, int) 未定义
猜你喜欢
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多