Search code examples
javaarraysjframejbutton

A JButtonGrid created with an Arry, and with actionlistener in an Arry, get the info of the Button?


for (int b = 0; b < Hsize; b++) {
    for (int c = 0; c < Lsize; c++) {
        System.out.println(Hsize + Lsize);
        Button[b][c] = new JButton("b:" + b + "c:" + c);
        Button[b][c].setBounds(l, h, 40, 40);
        Button[b][c].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getSource());
            }
        });
    }
}

The output if one of the buttons is pressed:

javax.swing.JButton[0 2,95,105,40x40,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@53c0c322,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=D:/Users/Max/workspace/Battleship/images/Unbenannt.png,disabledIcon=D:/Users/Max/workspace/Battleship/images/Unbenannt.png,disabledSelectedIcon=D:/Users/Max/workspace/Battleship/images/Unbenannt.png,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=,defaultCapable=true]

How can I filter out only the {0 2, or anything different for example the b/c coordinate ?


Solution

  • Since you've attached the listener to the button, you know that the triggering object is a Button. You can cast it into a button and then use the get methods to access the information you need. Right now you're just printing everything about the object.

      public void actionPerformed(ActionEvent e) {
          Button b = (Button)e.getSource();      
          System.out.println(b.getAlignmnetX()); //get whatever you need 
      }
    

    Button inherits from a bunch of classes, so you'll have to look up the documentation to figure out which get methods are available for you to use.

    http://docs.oracle.com/javase/7/docs/api/java/awt/Button.html