简体   繁体   中英

Grid of JButtons Label

grid=new JButton[width][length];
for(y=0;y<length;y++){
    for(x=0;x<width;x++){
        final Border border=new LineBorder(Color.red, 5);
            grid[x][y]=new JButton(" ");
            grid[x][y].addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                ((JButton)e.getSource()).setBorder(border);;
                System.out.println("Where do you want to move this piece");
            }
        });
        frame.add(grid[x][y]);

    }
}
grid[1][1]='R';

I am trying to get the first spot of the grid to say the letter R as in Rook; I am not sure how I can label specific JButton in a grid. Please help me... I am trying to make a GUI chess game.

使用方法而不是=Swing设置组件属性

grid[0][0].setText("R");

This won't compile:

grid[1][1]='R';

Because you're trying to assign a char to a JButton. Instead understand that the grid holds JButtons, and call the JButton methods:

grid[0][0].setText("R");

Also, you don't want to do this:

System.out.println("Where do you want to move this piece");

It's a bad idea to combine println statements and GUI's (unless you're debugging). Rather, show that String in a JLabel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM