How to make String value to call specific existed JButton variable name in java?

情到浓时终转凉″ 提交于 2019-12-05 15:06:48

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");

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!