如何在运行时创建JPanel并在用户单击时显示其名称

时间:2014-11-27 14:12:11

标签: java swing

我正在创建国际象棋游戏,为此我使用Loop创建64个JPanel。和更改背景颜色,这是我用来创建面板和更改其背景颜色的示例代码。

for(int i=0;i<8;i++)
    {
        for( int j=0;j<8;j++)
        {
            jp[i][j]=new JPanel();
            p.add(jp[i][j]);
            this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel
            if(j%2==0&&i%2==0)// code to change background color of panels for chess board
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
            if(j%2!=0&&i%2!=0)
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
        }
    }

当用户在棋盘上点击时,我需要代码来获取JPanel的名称

1 个答案:

答案 0 :(得分:-1)

扩展JPanel并添加要保存并读取的名称属性

   class MyPanel extends JPanel {
        public final int i;
        public final int j;
        public MyPanel(int i,int j){
            super();
            this.i = i;
            this.j = j;
        }
    }

for(int i=0;i<8;i++)
    {
        for( int j=0;j<8;j++)
        {
            jp[i][j]=new MyJPanel(i,j);
            p.add(jp[i][j]);
            jp[i][j].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    MyPanel p = (MyPanel)e.getSource();
                    // p.i p.j
                }
            });
            this.allSquares.add(jp[i][j]); // adding panel in arraylist of type Jpanel
            if(j%2==0&&i%2==0)// code to change background color of panels for chess board
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
            if(j%2!=0&&i%2!=0)
            {
            jp[i][j].setBackground(Color.DARK_GRAY);
            }
        }
    }

并点击监听器,将面板转换为MyPanel

MyPanel p = (MyPanel)object;
String name = p.name;