0

这是我上一个问题的后续问题。我正在尝试解决上一个问题中的问题。 关联

我正在编写一个图像益智游戏,其中一部分代码是将用户选择的部分与正确图像的部分进行比较。

每个图像片段都已作为 ImageIcon 添加到 JButton。

需要一个标识符来区分每个图像片段并进行比较。

我正在为作为标识符创建的每个 JButton 设置一个 setName()。

当用户从原始 3x3 网格中拖动块时,当用户将鼠标光标移动到另一个 3x3 网格上的特定按钮坐标时,比较开始。

已编辑:标记已编辑的代码。Flex似乎有一种方法可以检测光标下的对象,java有吗? Link ^ getSource() 解决了上述问题。

但是,当我试图system.out.println查看按钮何时getName()运行时,当我将碎片拖到按钮时,它似乎没有运行;要激活getName(),我必须在将图像块拖到按钮后将鼠标悬停在按钮上 =/。

private int mouseX,mouseY;
private JButton[] button = new JButton[9];
private JButton[] userarea = new JButton[9];

// setName for each of the 9 buttons in the original 3x3 grid being created 
// which stores the shuffled puzzle pieces
for(int a=0; a<9; a++){
    button[a] = new JButton(new ImageIcon());
    id += Integer.toString(++cc);
    button[a].setName(id); 
}

// create 9 buttons for the user to place the puzzle pieces to
for(int b=0; b<9; b++){
         userarea[b] = new JButton();
         id2 += Integer.toString(++cc2);
         // setName for each button (as unique id)
         userarea[b].setName(id2); 
         TransferHandler transfer1 = new TransferHandler("icon");
         userarea[b].setTransferHandler(transfer1);
    //<--- EDITED CODE ------>
            ChangeListener clistener = new ChangeListener(){                 
               public void stateChanged(ChangeEvent ce) {

                     JButton source = (JButton)ce.getSource();
                     ButtonModel mod = source.getModel(); 
                     if (mod.isRollover()){
                     System.out.println(source.getName());
                     }
                     else{

                 }
             }
         };
   //<--- EDITED CODE ------>
}


public void nameOfDestButton() {

            // not sure how to do this
            if(mouseCoordinate == getBounds of one of the buttons){
                userarea[appropriate button number].getName();
            }
}

public void mouseMoved(MouseEvent m){
        mouseX=m.getX();
        mouseY=m.getY();

        nameOfDestButton();

        // not sure how to do this. Obtaining a return value of getName
        // in the nameOfDestButton() method ?
        if (m.getComponent().getName().equals(nameOfDestButton) {  

        }
        else{
             JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
        }
    }         
4

0 回答 0