Reputation: 33
I can't come up with any other way of doing this. I'm trying to get the variable name of a java button which I've already declared so I can loop through a Database (Which has a screen field to access the correct product) and set the desired text to that jButton. I can do this by manually setting each jButtons text or setting a hard codded text through the Netbeans GUI. But I was looking to see if there's a more efficient way of doing this.
ArrayList<Products> myList = myProductsDataHandler.getAllProducts();
myList.forEach((var i) ->
{
if (i.getScreen() == 0)
{
btnProduct1.setText(i.getProductName());
}
else if (i.getScreen() == 1)
{
btnProduct2.setText(i.getProductName());
}
else if (i.getScreen() == 2)
{
btnProduct3.setText(i.getProductName());
}
else if (i.getScreen() == 3)
{
btnProduct4.setText(i.getProductName());
}
else if (i.getScreen() == 4)
{
btnProduct5.setText(i.getProductName());
}
else if (i.getScreen() == 5)
{
btnProduct6.setText(i.getProductName());
}
else if (i.getScreen() == 6)
{
btnProduct7.setText(i.getProductName());
}
else if (i.getScreen() == 7)
{
btnProduct8.setText(i.getProductName());
}
else if (i.getScreen() == 8)
{
btnProduct9.setText(i.getProductName());
}
int btnInt = 1;
String btnStr = "btnProduct";
btnCatagory1.setText(i.getCategory());
Component[] components = pnlOrder.getComponents();
for(Component component : components)
{
if(component instanceof JButton)
{
System.out.println(btnStr+btnInt);
JButton button = (JButton) component;
System.out.println(button.getName());
if (button.getName().contains(btnStr+btnInt))
{
btnProduct1.setText(i.getProductName());
btnInt++;
}
}
}
});
It's an Epos system and when the program is executed I want to get texts from the Database and set it to desired buttons. There are only 9 buttons. I have tried getName() but it returns null. Is there any other I can achieve this. Thanks
Upvotes: 0
Views: 156
Reputation: 324128
When you create your buttons you can also add each button to an ArrayList
:
List<JButton> buttons = new ArrayList<JButton>();
buttons.add(btnProduct1);
buttons.add(btnProduct2);
Then when you want to update the text on the button you simply use:
JButton button = buttons.get( i.getScreen() );
button.setText( i.getProductName() );
Upvotes: 2
Reputation: 187
You used setText() therefore should be using getText().
Had you used setName() you would use getName().
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/AbstractButton.html#getText()
Upvotes: 1