自己的JPanels坐标

时间:2015-06-21 09:45:57

标签: java swing jpanel

代码:

for(int i=0;i<10;i++) {
            for(int j=0;j<10;j++) {
                JPanel panel = new JPanel();
                addListener(panel);
                panel.setBorder(new LineBorder(Color.black,1));
                grid.add(panel);

-

public void addListener(JPanel p) {
        p.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                System.out.println(panelX);
                System.out.println(panelY);
            }
        });

如何为每个面板设置X-coordinateY-coordinate(If i = 5 and j = 2, panelX should be 2 and panelY should be 5)。如果单击该面板,则必须返回该面板的XY

1 个答案:

答案 0 :(得分:3)

    for(int i=0;i<10;i++) {
        for(int j=0;j<10;j++) {
            JPanel panel = new JPanel();
            addListener(panel, j, i);
            panel.setBorder(new LineBorder(Color.black,1));
            grid.add(panel);

-

public void addListener(JPanel p, final int x, final int y) {
    p.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            System.out.println(x);
            System.out.println(y);
        }
    });