如何使按钮列表器为您提供按下按钮的坐标

时间:2017-09-24 15:42:32

标签: java swing

所以基本上我正在尝试用GUI创建一个国际象棋/跳棋程序,该板是由8x8按钮矩阵组成的,我需要当我按下i按钮时按钮监听器会告诉我按下了哪个按钮。 我没有添加按钮列表器,但因为我希望你可能会更好的方式来做到这一点

PS:跳棋板被称为“棋盘” 代码:

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;
    }

}

1 个答案:

答案 0 :(得分:2)

您只需通过侦听器ActionEvent参数的.getSource()方法获取按下的按钮即可。

如,

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

上面的e是actionPerformed方法的ActionEvent方法参数。 然后调用你需要调用的对象上的任何方法。

支持问题:您将已发布的代码与==进行比较。不要这样做,因为这会比较 references ,而您想要比较String包含的实际文本。请改用.equals(...)方法。

例如,如果我们有一个持有JPanel网格的JPanel(看起来更清洁JButtons),我们可以为每个JPanel单元格添加一个MouseListener,就像动作监听器一样,我们可以得到被按下的组件。

在下面的代码中,我使用了Swing putClientProperty方法和getClientProperty让我的JPanel单元格“知道”它们所在的行和列。尝试一下:

编辑:现在使用可以容纳图标的JLabel:

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);
        }
    }
}