将JLabel列表添加到JPanel Grid

时间:2014-10-11 16:50:05

标签: java swing jpanel jlabel

我想将JLabel List添加到JPanel,这是代码但不起作用。我认为第一个循环正常工作,并在第二个循环不要把JLabel列表放在网格中。我无法在Eclipse中运行此代码

    private static final long serialVersionUID = 1L;
    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];


    public DragLabelOnLayeredPane() {
        final List<JLabel> list = new ArrayList<JLabel>();
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        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))); 
            }
        }
        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());
                panelGrid[row][col].add(list.get(row));
                gbc.gridx = row; gbc.gridy = col;
                backingPanel.add(panelGrid[row][col], gbc);


            }
        }

0 个答案:

没有答案