繁体   English   中英

java swing将JPanel与鼠标侦听器的行col值相关联

[英]java swing associating JPanel with row col values for mouse listener

我正在编写一个带有GUI的棋盘游戏,基本上我有一个10x10 GridLayout JPanel。

每个网格单元格都是正方形JPanel(我为这些JPanel使用了BorderLayout,因此边框可见)。

无论如何,我想要它,以便当单击其中一个方块时,它会对boardGameGrid进行更改,这是一个导入到游戏后端的GUI的类。 说我想使用该方法

boardGameGrid.setCellCross(x,y)

当按下位置(x,y)的单元格时。

我无法弄清楚如何做到这一点,因为每个JPanel都不包含任何有关其位置的信息。

谢谢

您必须将此JPanels准备为Object并将其放入Map或List,这是一个基于简单但简单的想法的简单示例

在此输入图像描述在此输入图像描述在此输入图像描述

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.LineBorder;
//based on @trashgod code from http://stackoverflow.com/a/7706684/714968
public class FocusingPanel extends JFrame {

    private static final long serialVersionUID = 1L;
    private int elements = 10;
    private List<GridPanel> list = new ArrayList<GridPanel>();
    private final JFrame mainFrame = new JFrame();
    private final JPanel fatherPanel = new JPanel();

    public FocusingPanel() {
        fatherPanel.setLayout(new GridLayout(elements, elements));
        for (int i = 0; i < elements * elements; i++) {
            int row = i / elements;
            int col = i % elements;
            GridPanel gb = new GridPanel(row, col);
            list.add(gb);
            fatherPanel.add(gb);
        }
        mainFrame.setLayout(new BorderLayout(5, 5));
        mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        mainFrame.add(fatherPanel, BorderLayout.CENTER);
        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    private GridPanel getGridPanel(int r, int c) {
        int index = r * elements + c;
        return list.get(index);
    }

    private class GridPanel extends JPanel {

        private int row;
        private int col;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(20, 20);
        }

        public GridPanel(int row, int col) {
            this.row = row;
            this.col = col;
            this.setBackground(Color.red);
            this.setBorder(new LineBorder(Color.black,1));
            this.addMouseListener(new MouseListener() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    int r = GridPanel.this.row;
                    int c = GridPanel.this.col;
                    GridPanel gb = FocusingPanel.this.getGridPanel(r, c);
                    System.out.println("r" + r + ",c" + c
                            + " " + (GridPanel.this == gb)
                            + " " + (GridPanel.this.equals(gb)));
                }

                @Override
                public void mousePressed(MouseEvent e) {
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                    int r = GridPanel.this.row;
                    int c = GridPanel.this.col;
                    GridPanel gb = FocusingPanel.this.getGridPanel(r, c);
                    System.out.println("r" + r + ",c" + c
                            + " " + (GridPanel.this == gb)
                            + " " + (GridPanel.this.equals(gb)));
                    setBackground(Color.blue);

                }

                @Override
                public void mouseExited(MouseEvent e) {
                    setBackground(Color.red);
                }
            });
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                FocusingPanel focusingPanel = new FocusingPanel();
            }
        });
    }
}

你为什么不简单地让每个小组了解他的立场:

public MyPanel(int x, int y) {
    this.x = x;
    this.y = y;
}

并且,在鼠标监听器中:

MyPanel p = (MyPanel) event.getSource();
boardGameGrid.setCellCross(p.getX(), p.getY());

或者Map<MyPanel, Point>如果您不想更改MyPanel,也可以使用Map<MyPanel, Point> ,并将每个面板的位置存储在此地图中:

MyPanel p = (MyPanel) event.getSource();
Point point = panelPositionMap.get(p);
boardGameGrid.setCellCross(p.x, p.y);

为什么不将它作为JTable而不是JPanel,并且每个单元格可以添加一个监听器。 这样您就可以知道单击了哪一行和哪一列

每个JPanel都知道它的位置,你可以使用panel.getX()/ getY()来获取它。 看起来像你要求的是这样的:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PanelLocation extends JFrame implements MouseListener
{
    private JPanel mainPanel, footerPanel;
    private JPanel[] panel = new JPanel[9];
    private JTextField tfield;

    public PanelLocation()
    {
        mainPanel = new JPanel();
        mainPanel.setLayout(new GridLayout(3, 3));

        for (int i = 0; i < 9; i++)
        {
            panel[i] = new JPanel();
            panel[i].addMouseListener(this);
            panel[i].setBorder(BorderFactory.createLineBorder(Color.BLUE));
            mainPanel.add(panel[i]);
        }   

        footerPanel = new JPanel();

        tfield = new JTextField(10);
        footerPanel.add(tfield);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        add(mainPanel, BorderLayout.CENTER);
        add(footerPanel, BorderLayout.PAGE_END);

        pack();     
        setVisible(true);
    }



     private void getWhichButtonGotPressed(int x, int y)
     {
         if ((x == panel[0].getX()) && (y == panel[0].getY()))
         {
            panel[0].setBackground(Color.MAGENTA);
            tfield.setText("You Clicked Panel : " + panel[0].getToolTipText());
         }
         else if ((x == panel[1].getX()) && (y == panel[1].getY()))
         {
            panel[1].setBackground(Color.YELLOW);
            tfield.setText("You Clicked Panel : " + panel[1].getToolTipText());
         }
         else if ((x == panel[2].getX()) && (y == panel[2].getY()))
         {
            panel[2].setBackground(Color.RED);
            tfield.setText("You Clicked Panel : " + panel[2].getToolTipText());
         }
         else if ((x == panel[3].getX()) && (y == panel[3].getY()))
         {
            panel[3].setBackground(Color.DARK_GRAY);
            tfield.setText("You Clicked Panel : " + panel[3].getToolTipText());
         }
         else if ((x == panel[4].getX()) && (y == panel[4].getY()))
         {
            panel[4].setBackground(Color.ORANGE);
            tfield.setText("You Clicked Panel : " + panel[4].getToolTipText());
         }
         else if ((x == panel[5].getX()) && (y == panel[5].getY()))
         {
            panel[5].setBackground(Color.PINK);
            tfield.setText("You Clicked Panel : " + panel[5].getToolTipText());
         }
         else if ((x == panel[6].getX()) && (y == panel[6].getY()))
         {
            panel[6].setBackground(Color.BLUE);
            tfield.setText("You Clicked Panel : " + panel[6].getToolTipText());
         }
         else if ((x == panel[7].getX()) && (y == panel[7].getY()))
         {
            panel[7].setBackground(Color.CYAN);
            tfield.setText("You Clicked Panel : " + panel[7].getToolTipText());
         }
         else if ((x == panel[8].getX()) && (y == panel[8].getY()))
         {
            panel[8].setBackground(Color.GRAY);
            tfield.setText("You Clicked Panel : " + panel[8].getToolTipText());
         }
    }

    public void mouseClicked(MouseEvent ae)
    {
        JPanel panel = (JPanel) ae.getSource();

        getWhichButtonGotPressed(panel.getX(), panel.getY());
    }

    public void mousePressed(MouseEvent ae)
    {
    }

    public void mouseReleased(MouseEvent ae)
    {
    }

    public void mouseEntered(MouseEvent ae)
    {
    }

    public void mouseExited(MouseEvent ae)
    {
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new PanelLocation();
                }
            });
    }
}

一个示例程序,显示所单击面板的坐标。 您只需单击面板,坐标将传递给函数,该函数将检查单击哪个面板,并返回所述面板的toopTipText。

这是程序的输出:

通过X,Y坐标选择面板

希望这可能在某种程度上有所帮助。

问候

您可以使用二维数组来存储对面板的引用。

例:

JPanel[][] panels = new JPanel[10][10];

//to store a panel:
JPanel p = new JPanel();
panels[x][y] = p;

//then change your method so that it gets the panel at position (x,y) from the array
public void setCellCross(int x, int y){
     JPanel clickedPanel = panels[x][y];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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