[英]set visible false to button using reflection, is posible?
I just trying hide button through relfection. 我只是想通过相对隐藏按钮。
Class userClass = Class.forName("vistas.RegistroPersonal");
Field f = userClass.getDeclaredField("btneliminar");
f.setAccessible(true);
f.setVisible(false);
is there a way... field does not have setVisible method... 有没有办法...字段没有setVisible方法...
The setVisible() method on a Field does not exist, what you need to do is get a reference on the setVisible(boolean) Method (by its name & parameter types) and then invoke it: 字段上的setVisible()方法不存在,您需要做的是获取setVisible(boolean)方法的引用(按其名称和参数类型),然后调用它:
public static void main(String[] args) throws Exception {
TestApplication application = new TestApplication();
Field field = TestApplication.class.getDeclaredField("button1");
// This will allow us to access the button1 field even if it's private
field.setAccessible(true);
Method method = JButton.class.getMethod("setVisible", Boolean.TYPE);
Object button = field.get(application);
method.invoke(button, Boolean.FALSE);
}
public static class TestApplication {
private JButton button1 = new JButton();
}
You need an instance of something to start with, if you start with the object owning your button then you can get its button via a Field and then invoke the Method. 首先需要一个实例,如果从拥有按钮的对象开始,则可以通过Field获取其按钮,然后调用Method。 If you start with a button instance you can call the Method.
如果从按钮实例开始,则可以调用方法。
Please note that reflection seems like a convoluted way to do things here, the equivalent would be simply: 请注意,反射似乎是一种复杂的处理方式,等效方式很简单:
TestApplication application = new TestApplication();
application.button1.setVisible(false);
To reflectivly call properties of a Java Bean such as Swing components, the recommended way is to use the Introspector class. 要反射地调用Java Bean的属性(例如Swing组件),建议的方法是使用Introspector类。
Some time ago, I've written a utility class, BeanIntrospector , to help working with beans and properties: 前一段时间,我编写了一个实用程序类BeanIntrospector ,以帮助使用bean和属性:
BeanIntrospector.setPropertyValue("visible", Boolean.FALSE, button, null);
The library is available from Maven Central: 该库可从Maven Central获得:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-beans</artifactId>
<version>2.0</version>
</dependency>
The library is Open Source and the code is available on GitHub: https://github.com/SoftSmithy/softsmithy-lib 该库是开源的,代码可在GitHub上找到: https : //github.com/SoftSmithy/softsmithy-lib
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.