[英]Java Is it possible to get the Variable name of a jButton?
我想不出任何其他方法来做到这一点。 我正在尝试获取我已经声明的 java 按钮的变量名称,以便我可以循环访问数据库(它具有访问正确产品的屏幕字段)并将所需的文本设置为该 jButton。 我可以通过手动设置每个 jButtons 文本或通过 Netbeans GUI 设置硬编码文本来做到这一点。 但我想看看是否有更有效的方法来做到这一点。
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++;
}
}
}
});
这是一个 Epos 系统,当程序执行时,我想从数据库中获取文本并将其设置为所需的按钮。 只有 9 个按钮。 我试过 getName() 但它返回 null。 还有其他我可以实现的吗。 谢谢
创建按钮时,您还可以将每个按钮添加到ArrayList
:
List<JButton> buttons = new ArrayList<JButton>();
buttons.add(btnProduct1);
buttons.add(btnProduct2);
然后,当您想更新按钮上的文本时,只需使用:
JButton button = buttons.get( i.getScreen() );
button.setText( i.getProductName() );
您使用了 setText(),因此应该使用 getText()。
如果您使用 setName(),您将使用 getName()。
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/AbstractButton.html#getText()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.