1

I am new to swing core functionalities. I have experience in web designing. There is id for uniqueness and class for commonality.

<div class="x" id="div1"></div>
<div class="x" id="div2"></div>

If i want to set property for all the divs, i ll use class x.

.x
{
} or via javascript or jquery

If i want to access single div, i ll make use of id. Because it is unique.

In the same way is there anything in java swing buttons?Assume i have 2D array of jbuttons.

Tried so far

I found putClientProperty and getClientproperty. It sets and returns id.

btnName.putClientproperty('id',value);

My first question:
Is it correct way to set Unique id's? Is there any other ways?

JButton[][] btns = new JButton[5][5];
for(int i=0; i<5; i++)
{
 for(int j=0;j<5;j++)
 {
   btns[i][j] = new JButton("Button"+i+j);
 }
}

The above code will create 25 buttons with names.

My Second Question: I am unaware of it.How to set classes so that i can enable or disable them with single line code? I meant All the 25 buttons has a common class let it be tiles

JButton.find('tiles').setEnabled(false);

Is there anything similarly in java? I know the way to iterate and do it. But i want to reduce the number of lines, function calls. That's why i posted this question. Please let me know

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • You could use [`JButton#setName`](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#setName(java.lang.String)) (and `getName`) and or [`JButton#setActionCommand`](http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html#setActionCommand(java.lang.String)) (and `getActionName`) which is probably the typical mechanism used to identify the button uniquely...obviously, that comes down to your create names that are unique ;) – MadProgrammer Aug 11 '14 at 06:15
  • *"So there is id for uniqueness and class for commonality. In the same way is there anything in java swing buttons?"* Not in the sense you are asking. *"Is it correct way to set Unique id's? Is there any other ways?"* Not ideal, no. But then, if you *"have 2D array"* it is easy to iterate that. Perhaps you are after an `Action` or a collection of them. *"**My Second Question:**"* Each thread here should focus on one question with hopefully at least one good & accepted answer. But I don't even understand the concept of 'disabling classes'. – Andrew Thompson Aug 11 '14 at 06:19
  • Isn't `btnName` the identifier already? ;-) – Paul Samsotha Aug 11 '14 at 06:19
  • @MadProgrammer so names and commands are other unique ways. Could you please tell about common names??[i.e class] btnclas.setEnabled(false) which llset all btns disabled. Is it possible?? – Gibbs Aug 11 '14 at 06:21
  • @All i ll edit it for further clarifications. – Gibbs Aug 11 '14 at 06:22
  • No. In java, all variables names need to be unique (and will only point a single reference of an object) and there's no way to simply bind all references to a single object and have them updated automatically in that way, you would need to use an array or `List` with which you could iterate over to interact with each individual referenced object – MadProgrammer Aug 11 '14 at 06:24
  • @MadProgrammer *"you would need to use an array or `List`"* The OP says *"Assume i **have 2D array** of jubttons."* & I have mentioned collections of objects. Based on the mention of 'enable/disable' made me think to suggest `Action` - though the OP seems to be ignoring me.. :-/ – Andrew Thompson Aug 11 '14 at 06:26
  • 1
    @AndrewThompson Yeah, I'd go for `Action` to...(I'm still trying to get my head around the question) – MadProgrammer Aug 11 '14 at 06:28
  • *"All the 25 buttons has a common class let it be tiles"* For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal, Complete, Verifiable Example). – Andrew Thompson Aug 11 '14 at 06:31
  • @MadProgrammer, Andrew I am not ignoring anyone's comments. please see my edits and let me now whether my doubt or the question is invalid.. – Gibbs Aug 11 '14 at 06:31
  • @user3801433 put/getClientproperty is best of ways – mKorbel Aug 11 '14 at 06:35
  • The `class` concept from HTML is most directly mappable to the 'Pluggable Look and Feel (PLAF)' applied to all buttons. But you seem to be referring to enabling or disabling them all in a single stroke, and the PLAF does not enter much into the *functionality* of the buttons (except in which keyboard keys will activate the buttons). I mentioned the 2D array because it is only a few LOC to iterate the entire array and do a single operation (e.g. enable/disable) every component in the array. .. – Andrew Thompson Aug 11 '14 at 06:37
  • .. OTOH Java has the concept of an `Action` that a button or menu item can share. If you disable the `Action`, any button(s) or menu item(s) using it are also enabled/disabled (in a single line of code). – Andrew Thompson Aug 11 '14 at 06:37
  • @mKorbel So Client Property the best way for id's. AM i clear?? – Gibbs Aug 11 '14 at 06:40
  • @Andrew Action interfaces are the best ways for classes. It ll do what i need in single stroke?? Am i corect? – Gibbs Aug 11 '14 at 06:40
  • @MadProgrammer You are correct in the first comment itself. I ll check it out as korbel and andrew said. So u can add it as an answer.. thanks – Gibbs Aug 11 '14 at 06:42
  • *"It ll do what i need in single stroke??"* Well, yes they could, but no they normally would not be used in quite the way you intend. E.G. although I suggested one `Action` might be applied to every button in the 2D array, it is generally better to create one action for each ..distinct action (e.g. `Save`, `Open`, `Exit` would be 3 `Action` objects). Technically it is possible to compound them all into one `Action`, but considered bad design. – Andrew Thompson Aug 11 '14 at 06:44
  • @user3801433 I think that yes, value can be accesible, settable, etc., incl. id for Swing Action as is shadowing in JButton#setName/setActionCommand by MadProgrammer, every [Listeners returns this valuse (you can to multiply ...)](http://stackoverflow.com/questions/13531346/java-input-a-matrix-using-gridlayout/13531549#13531549) and methods implemented in API too – mKorbel Aug 11 '14 at 06:45

2 Answers2

3

In your code example...

JButton[][] btns = new JButton[5][5];
for(int i=0; i<5; i++)
{
    for(int j=0;j<5;j++)
    {
        btns[i][j] = new JButton("Button"+i+j);
    }
}

You say...

The above code will create 25 buttons with names.

This isn't entirely true, it creates 25 buttons with the text of Button"+i+j, this might sound like a nit-pick, but it's important, as the buttons don't have names and so far, the only thing differentiating them is the text which is displayed on the screen.

Multiple buttons might have the same text, so this isn't really setting up uniqueness, other than their individual (memory) reference.

"Unique id's" is also ambiguous. Each button you have created is unique, but it might share similar properties, such as name, text and actionCommand, so the only thing making it unique is it's location in memory.

If that's what you mean, then yes, this would be start...

My Second Question: I am unaware of it.How to set classes so that i can enable or disable them with single line code? I meant All the 25 buttons has a common class let it be tiles

From an API point of view, no. You would need to iterate the buttons and manage each one individually. However, having said that, you could take advantage of the Action API.

An Action is typically a self-contained unit of work, which makes it easy to apply to multiple buttons, menu items and key bindings...but in your case, we're only interested in manipulating it's enabled state, for example, starting with...

public class GroupAction extends AbstractAction {
    @Override
    public void actionPerformed(ActionEvent evt) {
    }
}

You could then do something like...

GroupAction groupAction = new GroupAction();
JButton[][] btns = new JButton[5][5];
for(int i=0; i<5; i++)
{
    for(int j=0;j<5;j++)
    {
        btns[i][j] = new JButton(groupAction);
        // This is important as the button will want
        // to use the Action properties to configure itself
        btns[i][j].setText("Button"+i+j);
    }
}

Then you could use something like...

groupAction.setEnabled(false);

to disable all the buttons with the SAME instance of the GroupAction

Take a look at How to Use Actions for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks:) You are really a MAdProgrammer :) ll check it out. – Gibbs Aug 11 '14 at 06:46
  • disagree JButton#setName/setActionCommand, not talking about coordinates inside array, still is there x.y. problem --> where is this element really placed, you can'm multiplay this id's, sure not attack to your person :-) as you know very well – mKorbel Aug 11 '14 at 06:48
  • @mKorbel Focusing on the details not the implementation ;) - You are correct in saying the the placement should be assumed and I agree with. Would prefer to use `actionCommand` personally, but this leads us to the `Action` API which could be considered an extension to the idea (multiple buttons could have the same `actionCommand` or the same `Action`) – MadProgrammer Aug 11 '14 at 06:52
0

You can always make a map of Object -> Integer or String with your id. Ex.:

Map<JButton, Integer> buttonToIdMap = new TreeMap<JButton, Integer>();

And put into the map your IDs:

buttonToIdMap.put(button, 123);

When you need ID to a button:

int id = buttonToIdMap.get(button);
marioc64
  • 381
  • 3
  • 12
  • This should really be a comment, at this stage (of confusion in the question itself). You seem to now have enough rep. to make comments, please use that. – Andrew Thompson Aug 11 '14 at 06:28
  • @AndrewThompson what are you talking about? This solves the problem. – Silviu Burcea Aug 11 '14 at 06:34
  • It's making me to learn about map with key and values. Can i use array names instead of JButton in the first line of your code. What about class?? Any ideas? – Gibbs Aug 11 '14 at 06:37
  • @SilviuBurcea *"This solves the problem."* I'm still not sure what the problem is (exactly), but it seems that a map would be no more use in dealing with collections of objects than an array. – Andrew Thompson Aug 11 '14 at 06:41
  • 1
    @user3801433 you can identify a Button by the key you used to store the Button in the map. Another alternative is to extend a JButton(MyButton) that will hold a unique key and the actual JButton. You can also change the way the button is rendered or leave it the way it is. – Silviu Burcea Aug 11 '14 at 06:49