自定义JComponent未显示在JLayeredPane上

时间:2013-05-18 13:20:59

标签: java swing jcomponent jlayeredpane

我正在尝试用Java创建一个国际象棋界面,我正在使用JLayeredPane将棋子放在我的棋盘图像上。问题是这些部分没有添加到分层窗格中。

这是我的DragImage类的代码(每个部分都将成为此类的一个实例,您可以将其拖放到棋盘上)。

class DragImage extends JComponent implements MouseMotionListener {
        private static final long serialVersionUID = 1L;
        int imageWidth = 52, imageHeight = 52;
        int imageX, imageY;
        Image img;

        public DragImage(Image i) {
            img = i;
            repaint();
            addMouseMotionListener(this);
        }

        public void mouseDragged(MouseEvent e) {
            imageX = e.getX();
            imageY = e.getY();
            repaint();
        }

        public void mouseMoved(MouseEvent e) {
        }

        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;

            g2.drawImage(img, imageX, imageY, this);
        }

    }

这是JPanel的代码。

图像地址正确但它们没有显示在面板上。

class MyPanel extends JPanel {
        private JLayeredPane layeredPane;
        private JLabel imageContainer = new JLabel();
        private ImageIcon img;

        MyPanel() {
            super();
            img = new ImageIcon("chessboard.png");
            this.imageContainer.setIcon(img);
            this.layeredPane = new JLayeredPane();
            layeredPane.setPreferredSize(new Dimension(416, 416));
            layeredPane.add(imageContainer, 50);
            imageContainer.setBounds(0, 0, img.getIconWidth(),
                    img.getIconHeight());
            int pozx = 52, pozy = 52;
            for (int i = 0; i < 8; i++) {
                for (int j = 0; j < 8; j++) {
                    if(tabla[i][j]!="--"){
                    DragImage img = new DragImage(Toolkit.getDefaultToolkit().getImage("pieces\\" + tabla[i][j] + ".png"));
                    //System.out.println("pieces\\" + tabla[i][j] + ".png");
                    img.setBounds(pozx,pozy,img.imageWidth,img.imageHeight);
                    layeredPane.add(img,100);   //this doesn't work
                    }
                    pozx+=52;
                }
                pozy+=52;
                pozx=52;
            }

            this.add(layeredPane);
        }
}

...

frame = new JFrame();
frame.setVisible(true);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new MyPanel();
frame.add(panel);
frame.pack();

1 个答案:

答案 0 :(得分:0)

首先使用Layeredpane,然后将两个面板连接到一个用于图像,另一个面板用于组件,第二个面板必须是苍白层,然后组件将出现..