4

So, I know there is this:

int number = Integer.parseInt("5");
String numtxt = Integer.toString(12);
double number = Double.parseDouble("4.5");
String numbertxt = Double.toString(8.2);
String letter = Character.toString('B');
char letter = "stringText".charAt(0);

so on...

but what I don't know how to make String value to call existed JButton variable name dynamically; is it even possible?

Let's say, I have 4 JButton called btn1, btn2, btn3 and btnFillNumber;

I create a String called buttonName;

package testing;

public class Testing extends javax.swing.JFrame {

String buttonName;
int num;

public Testing() {
    initComponents();
}

@SuppressWarnings("unchecked")
// Generated Code <<<-----

private void btnFillNumberActionPerformed(java.awt.event.ActionEvent evt) {                                              
    for(num = 1; num <= 3; num++){
        buttonName = "btn" + Integer.toString(num);
        JButton.parseJButton(buttonName).setText(num);
    }
}                                             

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    // Look and feel stteing code (optional) <<<-----

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Testing().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private javax.swing.JButton btnFillNumber;
// End of variables declaration                   
}

I know there's no JButton.parseJButton(), I just don't want to make complicated explaination, I simple want a convertion from String to call JButton's variable name dynamically.

See this:

    for(num = 1; num <= 3; num++){
        buttonName = "btn" + Integer.toString(num);
        JButton.parseJButton(buttonName).setText(num);
    }

I want to make a loop using a String with

  • a fixed String value (btn) and
  • increment number after it (1, 2, 3...) and
  • make use to call a JButton.

I can just simply do this, but what if I got a 25 or more? So a loop what I wanted...

btn1.setText("1");
btn2.setText("2");
btn3.setText("3");

Note that the value of these JButtons are not necessarily incremental in some purpose.

Output:

Sample output

My real development:

enter image description here

P.S. I use to make JFrame in NetBeans Design (just click and drag the objects in palette window like JPanel, JButton, etc., so I don't type the code manually except making my own logical Method; and I can't edit the code in grey background in Source View that was made automatically by Design View but in Design View itself. If you have tips and guide, I'll be happy to).

Community
  • 1
  • 1
Jan Jeremy
  • 43
  • 1
  • 6
  • if i understand this right then one way could be to store the buttons in a `Map`. Afterwards you could simply access them by `map.get("btn1")`. – SomeJavaGuy Jan 06 '16 at 12:42
  • Thank you for your quick reply, maybe I gonna look about that.. still learning Java. :D – Jan Jeremy Jan 06 '16 at 13:01
  • Possible duplicate of [Get a Swing component by name](http://stackoverflow.com/questions/4958600/get-a-swing-component-by-name) – Pete Kirkham Jan 06 '16 at 14:15
  • @Jan Jeremy my question is if each of JButtons has statics set of values or value for JButton can be changed at runtime, then this question can be anverable – mKorbel Jan 06 '16 at 14:24
  • @mKorbel what do you mean? You mean the value of btn1-btn3? (Can be change by setText). No, they are not static, they can be assign to different value. – Jan Jeremy Jan 06 '16 at 15:28
  • @Jan Jeremy if the concrete JButton has always the same properties, – mKorbel Jan 06 '16 at 16:58
  • @mKorbel yes, they have the same properties except the variable name. For now, the quantities of my JButton is fix in number, if I have 4 it's 4, if I have 3 it's 3. They are not dynamically made. – Jan Jeremy Jan 07 '16 at 12:04

2 Answers2

2

Use a Map:

private Map<String,JButton> buttonMap = new HashMap<String,JButton>();

In your constructor add your buttons:

buttonMap.add("btn1", btn1);
buttonMap.add("btn2", btn2);
buttonMap.add("btn3", btn3);
buttonMap.add("btn4", btn4);

And in your action Listener / Loop whatever make:

String buttonName = "btn1"; //should be parameter or whatever
JButton button = buttonMap.get(buttonName);

As an alternative you could just as well set up an array of JButton:

JButton[] buttons = new JButton[4];

button[0] = new JButton(); //btn1
button[1] = new JButton(); //btn2
button[2] = new JButton(); //btn3
button[3] = new JButton(); //btn4

And access it

JButton but = button[Integer.parseInt(buttonString)-1];

Or by utilizing the possibility of adding custom properties to UI elements (you'll need a JComponent for that)

getContentPane().putClientProperty("btn1", btn1);

and later retrieving whith

JButton but = (JButton)getContentPane().getClientProperty("btn1");
Jan
  • 13,738
  • 3
  • 30
  • 55
  • (Hash)Map hasn't internal index better with util.List, then all additional params could be stored (depends of index) in [get/putClientProperty](http://stackoverflow.com/a/10416286/714968) and/or by using Swing Action – mKorbel Jan 06 '16 at 13:28
  • with Map you can access items **by Name** - with List you access **by Index** only. The question was clearly worded for access **by Name** so a Map provides best result. – Jan Jan 06 '16 at 13:31
  • then reson for get/putClientProperty, is about siimplyfied all possible things without premature arrays (just my view, not flamewar) – mKorbel Jan 06 '16 at 13:33
  • You would use the get/putClientProperty on the **buttons**. And would still be able to do that if they're in a Map. Or do you suppose to **use the JPanel the buttons will be added to** as the "Map" to store the values? – Jan Jan 06 '16 at 13:34
  • yes, agree, exactly, it can be, but util.List is better array for, you have to hold index (can be required from everywhere) in (Hash)Map separatelly :-) – mKorbel Jan 06 '16 at 13:39
  • You mean instead of Array (which is poor choice) use a List? Yes, absolutely. That array example is just to show some alternatives. – Jan Jan 06 '16 at 13:40
  • :-) to your edit you have to multiply those paramaters with number, numtxt, number,numbertxt, letter, char :-) thats reason for my get/putClientProperty :-), to every JButtons, this is requirements by OP :-) phaaaa... :-) – mKorbel Jan 06 '16 at 13:41
  • This is not how I understood the question - let's wait for some feedback here. – Jan Jan 06 '16 at 13:42
  • result is then (get/putClientProperty) any type of array is useless – mKorbel Jan 06 '16 at 13:44
  • my helicopter view you can to see in my answer here – mKorbel Jan 06 '16 at 14:10
-1

I agree with Kevin's comment. The best concrete Map<K,V> class is probably Hashtable<K,V>. You don't even need to create the button name, just associate an integer with it if they are all numbered (and if btnFillNumber can be 0).

Hashtable<Integer,JButton> buttonTable = new Hashtable<>();

// Fill buttonTable with buttons

JButton button = buttonTable.get(num);

if (button != null) {
    // Do something with button
}

Because of autoboxing, you don't need to create Integer objects to query the hashtable, num can be an int primitive.

Pete A
  • 34
  • 3
  • (Hash)Map hasn't internal index better with util.List, then all additional params could be stored (depends of index) in [get/putClientProperty](http://stackoverflow.com/a/10416286/714968) and/or by using Swing Action – mKorbel Jan 06 '16 at 13:28
  • See http://stackoverflow.com/questions/8223125/replacement-for-obsolete-hashtable-class-in-java – Jan Jan 06 '16 at 13:30