我正在为国际象棋编程gui,我正在使用JLayeredpane,以便在JFrame上显示黑白图块,然后在JLayeredpane的下一层上,我将显示棋子,我是新手。 Jlayeredpane,我不太了解如何使用它,我无法将碎片图层叠加在tile图层上,我尝试将不透明度设置为false,并尝试将背景色设置为0,0,0, 0个想法?
我创建了一个jpanel,该jpanel包含一个具有黑白背景的jpanel数组,然后创建了另一个jpanel,它包含一个jlabels数组,这些jlabel的文本显示了棋子。
总代码:
class frame extends JFrame implements MouseListener, MouseMotionListener{
private JLabel[][]label;
private int xIndex;
private int yIndex;
private JPanel[][]panels;
private JPanel mainPanel;
private JPanel labelPanel;
public frame() {
super("Chessboard");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
label = new JLabel[8][8];
mainPanel = new JPanel();
panels = new JPanel[8][8];
labelPanel = new JPanel();
mainPanel.setLayout(new GridLayout(8,8));
addTiles();
labelPanel.setLayout(new GridLayout(8,8));
addButtons();
JLayeredPane mainPane = new JLayeredPane();
add(mainPane);
mainPane.add(mainPanel,1);
mainPane.add(labelPanel, 2);
setBoard();
setSize(new Dimension(500,500));
setVisible(true);
}
public void setBoard(){
label[0][0].setText("\u2656");
label[0][7].setText("\u2656");
label[0][1].setText("\u2658");
label[0][2].setText("\u2657");
label[0][3].setText("\u2655");
label[0][4].setText("\u2654");
label[0][5].setText("\u2657");
label[0][6].setText("\u2658");
label[7][0].setText("\u265C");
label[7][1].setText("\u265E");
label[7][2].setText("\u265D");
label[7][3].setText("\u265B");
label[7][4].setText("\u265A");
label[7][5].setText("\u265D");
label[7][6].setText("\u265E");
label[7][7].setText("\u265C");
for(int i =0; i <8 ;i++){
label[1][i].setText("\u2659");
}
for(int i =0; i <8 ;i++){
label[6][i].setText("\u265F");
}
}
public void addTiles(){
for(int i =0; i<8;i++){
for(int k =0; k<8;k++){
panels[i][k] = new JPanel();
if(i%2 == 1){
if(k%2 == 0){
panels[i][k].setBackground(Color.gray);
}else{
panels[i][k].setBackground(Color.WHITE);
}
}else{
if(k%2 == 1){
panels[i][k].setBackground(Color.gray);
}else{
panels[i][k].setBackground(Color.WHITE);
}
}
mainPanel.add(panels[i][k]);
}
}
}
public void addButtons(){
for(int i =0; i<8;i++){
for(int k =0; k<8;k++){
label[i][k] = new JLabel();
label[i][k].setLayout(null);
label[i][k].setFont(label[i][k].getFont().deriveFont(29f));
label[i][k].addMouseListener(this);
label[i][k].addMouseMotionListener(this);
labelPanel.add(label[i][k]);
}
}
}
public void findIndex(MouseEvent arg0){
for(int x =0; x<8;x++){
for(int y =0; y <8; y++){
if(arg0.getSource().equals(label[x][y])){
xIndex = x;
yIndex = y;
}
}
}
}
public void mouseDragged(MouseEvent arg0) {
findIndex(arg0);
int mouseX = arg0.getX();
int mouseY = arg0.getY();
label[xIndex][yIndex].setLocation(mouseX, mouseY);
}
我想要这样,使碎片层显示在黑白jpanels的图块层的顶部,并且颜色可见。