2013-01-22 47 views
0

我正在编码图像益智游戏,代码的一部分是比较用户选择的部分片段的正确图像。通过setName()比较组件。

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

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

我为每个JButton创建一个setName()作为标识符。

比较在用户从原始3x3网格中拖拽拼图后释放鼠标时开始,在这个网格中将混洗的部分放到其他3x网格进行匹配。

我有问题,从比较if声明中删除错误。

我从这个SO线程比较主意 - link

private JButton[] button = new JButton[9]; 
    private JButton[] waa = new JButton[9]; 

    private String id; 
    private int cc; 
    private String id2; 
    private int cc2; 

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

    // setName for each of the 9 buttons in the other 3x3 grid 
    // where the images will be dragged to by the user 
     for(int b=0; b<9; b++){ 
     waa[b] = new JButton(); 
     id2 += Integer.toString(++cc2); 
     waa[b].setName(id2); 
    } 

    // check if puzzle pieces are matched in the correct place 
    // compare name of original 'button' array button with the name of 'waa' array buttons 
     button[a].addMouseListener(new MouseAdapter(){ 

      public void mouseReleased(MouseEvent m){ 
       if(m.getbutton().getName().equals (waa.getName())){ 

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

回答

3

在你mouseReleased事件m.getButton()将返回被点击鼠标按钮。你会想要做更多像这样的东西,将让你更接近:

if (m.getComponent().getName().equals(waa.getName())) { 

m.getComponent()返回Component对象(你JButton),该事件从被解雇。从那里您可以与您使用的getName方法进行比较。

还有一个问题,因为你的waa变量是一个数组。我不确定您想如何比较它们,无论是通过数组运行并确保索引和名称匹配,但这是您需要研究的另一个问题。

+1

如果您不关心是否鼠标事件发生在按钮上,MouseEvent包含一个getComponent方法,该方法应允许放弃演员(至少您确定您想要)。就我个人而言,我也正在检查以确保getName没有返回空值 – MadProgrammer

+2

其实,当我想到它时,为什么我们在按钮上使用鼠标监听器? – MadProgrammer

+0

关于'getComponent'的好处是,我更新了代码。鼠标监听器也是不必要的,它可以通过'addActionListener'完成。在上面的代码中显然有一些问题,但希望这会让OP开始朝着正确的方向发展。 –

3

JButton使用ActionListener触发通知回到您的程序以指示它何时被触发。这允许按钮响应不同类型的事件,包括鼠标,键盘和程序触发器。

作为操作API的一部分,您可以为每个按钮提供操作命令。见JButton#setActionCommand

基本上你会在simular方式到您的鼠标监听它集成...

public void actio Performed(ActionEvent evt) { 
    if (command.equals(evt.getActionCommand()) {...} 
} 

根据您的要求,它甚至可能会更易于使用的Action API

您的问题实际上是waa是一个数组,因此它没有getName方法。我也不清楚为什么你有两个按钮阵列?

+0

哦,第9个按钮阵列用于显示存储为ImageIcons的9个混洗件。第9个按钮的第二个数组供用户将其拖动到。 – iridescent

+2

@iridescent:听起来好像你使用JButtons作为真正的按钮,而是作为存储库来保存JLabel。为什么要使用JButtons呢?为什么不简单地创建并使用一组JLabel来保存ImageIcons? –

+0

如果您愿意,也可以使用拖放来移动图标。 1+疯狂的方式。 –