Maanav Dalal Maanav Dalal - 3 years ago 76
Java Question

Getting one Element of a JButton in Java

I was working on a mineSweeper game when I ran into an issue while trying to flag squares. I'm using the code

if (SwingUtilities.isRightMouseButton(e)) {
int clickedTile = e.getButton();
bombNum.setText(""+userMineNum);
//flagTile(clickedTile);
}


To try and access the number of the JButton. However, this always results in the value of clickedTile being 3 (it's an array of JButtons so that's impossible more than once). Anyway, I looked into e.getSource(), which gets the whole object, and if I were to print it out for an object it'd be:

javax.swing.JButton[,221,124,44x31,alignmentX=0.0,alignmentY=0.5,border=,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=resources/0.png,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=false,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text= ,defaultCapable=true]


With the important field being "text" (which i can later change, however it's blank right now). I want to know how to access it so i can save its value to set the flag in the right location.

e.getSource().text


Doesn't work.

Any help would be greatly appreciated.
Thanks.

Answer Source

The e.getButton() indicates which button of the mouse is being clicked. In your case the right one, or number 3.

Other than that, I believe you could get the text of the button doing:

((JButton) e.getSource()).getName()

or

((JButton) e.getSource()).getText()

But I'd strongly recommend you to check wether it's a button that's being clicked and not other component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download