通过setName()比较组件。

时间:2013-01-22 07:24:40

标签: java swing compare

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

每个图像片段已作为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.");
                    }
            }
        }

2 个答案:

答案 0 :(得分:3)

mouseReleased事件中m.getButton()返回单击的鼠标按钮。你会想做更像这样的事情,让你更接近:

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

m.getComponent()会返回触发事件的Component对象(您的JButton)。从那里,您可以与您正在使用的getName方法进行比较。

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

答案 1 :(得分:3)

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

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

基本上你会以类似的方式将它集成到你的鼠标听众......

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

根据您的要求,使用Action API

可能更容易

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

相关问题