0

so basically I am trying to make a a chess/checkers program with GUI, the board is made out of a matrix of 8x8 buttons and i need that when i press i button the button listener will tell me which button was pressed. I didnt add the button listner yet becuase i was hoping you would maybe sujjest a better way to do it

PS: the checkers board is called "chessboard" CODE:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;


public class BetterGui {
    private final JPanel gui = new JPanel(new BorderLayout(3, 3));
    public JButton[][] chessBoardSquares = new JButton[8][8];
    private JPanel chessBoard;
    private final JLabel message = new JLabel(
            "Amos is the King");
    private static final String COLS = "ABCDEFGH";

    BetterGui(Board board) {
        updateGui(board);
    }

    public final void updateGui(Board board) {
        // set up the main GUI
        gui.setBorder(new EmptyBorder(5, 5, 5, 5));
        JToolBar tools = new JToolBar();
        tools.setFloatable(false);
        gui.add(tools, BorderLayout.PAGE_START);
        tools.add(new JButton("New")); // TODO - add functionality!
        tools.add(new JButton("Save")); // TODO - add functionality!
        tools.add(new JButton("Restore")); // TODO - add functionality!
        tools.addSeparator();
        tools.add(new JButton("Resign")); // TODO - add functionality!
        tools.addSeparator();
        tools.add(message);

        gui.add(new JLabel("?"), BorderLayout.LINE_START);

        chessBoard = new JPanel(new GridLayout(0, 9));
        chessBoard.setBorder(new LineBorder(Color.BLACK));
        gui.add(chessBoard);

        // create the chess board squares
        Insets buttonMargin = new Insets(0, 0, 0, 0);
        for (int ii = 0; ii < chessBoardSquares.length; ii++) {
            for (int jj = 0; jj < chessBoardSquares[ii].length; jj++) {
                JButton b = new JButton();
                b.setMargin(buttonMargin);
                // our chess pieces are 64x64 px in size, so we'll
                // 'fill this in' using a transparent icon..
                BufferedImage img = null;
                try {
                    if (ii % 2 == jj % 2) {
                        if (board.GameBoard[ii][jj].ContainingChecker.CheckerType == "red") {
                            img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\large_blue_circle.png")); // eventually C:\\ImageTest\\pic2.jpg
                        } else if (board.GameBoard[ii][jj].ContainingChecker.CheckerType == "black") {
                            img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\chcekrplayer.png")); // eventually C:\\ImageTest\\pic2.jpg
                        } else {
                            img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\clearImage.png")); // eventually C:\\ImageTest\\pic2.jpg
                        }
                    } else {
                        img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\clearImage.png")); // eventually C:\\ImageTest\\pic2.jpg
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ImageIcon icon = new ImageIcon(img);
                b.setIcon(icon);
                if ((jj % 2 == 1 && ii % 2 == 1)
                        //) {
                        || (jj % 2 == 0 && ii % 2 == 0)) {
                    b.setBackground(Color.WHITE);
                } else {
                    b.setBackground(Color.BLACK);
                }
                chessBoardSquares[jj][ii] = b;
            }
        }

        //fill the chess board
        chessBoard.add(new JLabel(""));
        // fill the top row
        for (int ii = 0; ii < 8; ii++) {
            chessBoard.add(
                    new JLabel(COLS.substring(ii, ii + 1), SwingConstants.CENTER));
        }
        // fill the black non-pawn piece row
        for (int ii = 0; ii < 8; ii++) {
            for (int jj = 0; jj < 8; jj++) {
                switch (jj) {
                    case 0:
                        chessBoard.add(new JLabel("" + (ii + 1), SwingConstants.CENTER));
                    default:
                        chessBoard.add(chessBoardSquares[jj][ii]);
                }
            }
        }
    }

    public final void initializeGui2() {
        // set up the main GUI
        gui.setBorder(new EmptyBorder(5, 5, 5, 5));
        JToolBar tools = new JToolBar();
        tools.setFloatable(false);
        gui.add(tools, BorderLayout.PAGE_START);
        tools.add(new JButton("New")); // TODO - add functionality!
        tools.add(new JButton("Save")); // TODO - add functionality!
        tools.add(new JButton("Restore")); // TODO - add functionality!
        tools.addSeparator();
        tools.add(new JButton("Resign")); // TODO - add functionality!
        tools.addSeparator();
        tools.add(message);

        gui.add(new JLabel("?"), BorderLayout.LINE_START);

        chessBoard = new JPanel(new GridLayout(0, 9));
        chessBoard.setBorder(new LineBorder(Color.BLACK));
        gui.add(chessBoard);

        // create the chess board squares
        Insets buttonMargin = new Insets(0, 0, 0, 0);
        for (int ii = 0; ii < chessBoardSquares.length; ii++) {
            for (int jj = 0; jj < chessBoardSquares[ii].length; jj++) {
                JButton b = new JButton();
                b.setMargin(buttonMargin);
                // our chess pieces are 64x64 px in size, so we'll
                // 'fill this in' using a transparent icon..
                BufferedImage img = null;
                try {
                    if (ii % 2 == jj % 2) {
                        if (ii < 2) {
                            img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\large_blue_circle.png")); // eventually C:\\ImageTest\\pic2.jpg
                        } else if (ii > 4) {
                            img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\chcekrplayer.png")); // eventually C:\\ImageTest\\pic2.jpg
                        } else {
                            img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\clearImage.png")); // eventually C:\\ImageTest\\pic2.jpg
                        }
                    } else {
                        img = ImageIO.read(new File("C:\\Users\\Awesome\\Desktop\\clearImage.png")); // eventually C:\\ImageTest\\pic2.jpg
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ImageIcon icon = new ImageIcon(img);
                b.setIcon(icon);
                if ((jj % 2 == 1 && ii % 2 == 1)
                        //) {
                        || (jj % 2 == 0 && ii % 2 == 0)) {
                    b.setBackground(Color.WHITE);
                } else {
                    b.setBackground(Color.BLACK);
                }
                chessBoardSquares[jj][ii] = b;
            }
        }

        //fill the chess board
        chessBoard.add(new JLabel(""));
        // fill the top row
        for (int ii = 0; ii < 8; ii++) {
            chessBoard.add(
                    new JLabel(COLS.substring(ii, ii + 1), SwingConstants.CENTER));
        }

    }

    public final JComponent getChessBoard() {
        return chessBoard;
    }

    public final JComponent getGui() {
        return gui;
    }

}
borat
  • 3
  • 3
  • 1
    In the future, we're all better off if you can condense your posted code into a valid [mcve], one that is a small self-contained complete program (no need for outside dependencies such as `Board`), one that compiles, and runs and shows us your problem, but does nothing else. Your above code contains too much unrelated code as well as dependencies that we don't have access to including classes and images, meaning we have to wade through a lot of irrelevant stuff, and we can't run your program. Thanks in advance. – DontKnowMuchBut Getting Better Sep 24 '17 at 15:51
  • See also [Making a robust, resizable Swing Chess GUI](http://stackoverflow.com/q/21142686/418556). – Andrew Thompson Sep 24 '17 at 17:48

1 Answers1

2

You can simply get the pressed button via the listeners ActionEvent parameter's .getSource() method.

e.g.,

public class MyListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        AbstractButton myBtn = (AbstractButton) e.getSource();
        // call whatever methods needed on myBtn
    }
}

With e above being the ActionEvent method parameter for the actionPerformed method. Then call whatever methods on the object obtained that you need to call.

Side problem: your posted code you compare Strings with ==. Don't do that since this compares references and you want to instead compare the actual text that the String contains. Use the .equals(...) method instead.

For example, if we had a JPanel that held a grid of JPanels (cleaner looking that JButtons), we could add a MouseListener to each JPanel cell, and just like action listener, we can get the pressed component.

In the code below, I've used the Swing putClientProperty method and getClientProperty to have my JPanel cells "know" what row and column they're in. Try it:

Edit: now using JLabels that can hold icons:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.*;

@SuppressWarnings("serial")
public class MyGrid extends JPanel {
    public static final String ROW = "row";
    public static final String COL = "col";
    private static final int SIDES = 8;
    private static final int CELL_SZ = 60;
    private static final Dimension CELL_DIMENSION = new Dimension(CELL_SZ, CELL_SZ);
    private static final Color DARK = Color.GRAY;
    private static final int LT = 250;
    private static final Color LIGHT = new Color(LT, LT, LT);
    private JLabel[][] cells = new JLabel[SIDES][SIDES];
    private Icon whiteIcon;
    private Icon redIcon;

    public MyGrid() {
        whiteIcon = createIcon(LIGHT);
        redIcon = createIcon(Color.RED);
        MyMouse myMouse = new MyMouse();
        setLayout(new GridLayout(SIDES, SIDES));
        for (int row = 0; row < cells.length; row++) {
            for (int col = 0; col < cells[row].length; col++) {
                JLabel cell = new JLabel();
                cell.setOpaque(true);
                cell.setPreferredSize(CELL_DIMENSION);
                cell.putClientProperty(ROW, row);
                cell.putClientProperty(COL, col);
                cell.addMouseListener(myMouse);
                Color bg = row % 2 == col % 2 ? LIGHT : DARK;
                if (bg.equals(DARK) && row < 3) {
                    cell.setIcon(redIcon);
                } else if (bg.equals(DARK) && row > 4) {
                    cell.setIcon(whiteIcon);
                }
                cell.setBackground(bg);
                cells[row][col] = cell;
                add(cell);
            }
        }
    }

    private Icon createIcon(Color color) {
        BufferedImage img = new BufferedImage(CELL_SZ, CELL_SZ, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = img.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int gap = 4;
        g2.setColor(color);
        g2.fillOval(gap, gap, CELL_SZ - 2 * gap, CELL_SZ - 2 * gap);
        g2.dispose();
        return new ImageIcon(img);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        MyGrid mainPanel = new MyGrid();
        JFrame frame = new JFrame("MyGrid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;

public class MyMouse extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
        JComponent cell = (JComponent) e.getSource();
        if (cell != null) {
            Integer row = (Integer) cell.getClientProperty(MyGrid.ROW);
            Integer col = (Integer) cell.getClientProperty(MyGrid.COL);

            System.out.printf("[%d, %d]%n", row, col);
        }
    }
}