0
我正嘗試在Java中創建一個國際象棋界面,並且我正在使用JLayeredPane
將棋子放在我的棋盤圖像上。問題是這些部分不會添加到分層窗格中。自定義JComponent未顯示在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();
爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –
創建框架,設置大小,添加面板,打包,設置可見。 – arynaq
*「圖像地址正確,但沒有顯示在面板上。」*真的嗎?試試這個實驗。 'String path =「pieces \\」+ tabla [i] [j] +「.png」;文件f =新文件(路徑); System.out.println(「File exists:」+ file.exists());'。我會**打賭**打印'File exists:false'(修復任何小錯別字後,可能會阻止它編譯).. –