getComponentByName (marco, nombre)
si usted está utilizando NetBeans IDE u otra que por defecto crea variables privadas (campos) para contener todos sus componentes AWT/Swing, entonces el siguiente código puede trabajar para ti. Utilice la siguiente manera:
// get a button (or other component) by name
JButton button = Awt1.getComponentByName(someOtherFrame, "jButton1");
// do something useful with it (like toggle it's enabled state)
button.setEnabled(!button.isEnabled());
Aquí está el código para que lo anterior sea posible ...
import java.awt.Component;
import java.awt.Window;
import java.lang.reflect.Field;
/**
* additional utilities for working with AWT/Swing.
* this is a single method for demo purposes.
* recommended to be combined into a single class
* module with other similar methods,
* e.g. MySwingUtilities
*
* @author http://javajon.blogspot.com/2013/07/java-awtswing-getcomponentbynamewindow.html
*/
public class Awt1 {
/**
* attempts to retrieve a component from a JFrame or JDialog using the name
* of the private variable that NetBeans (or other IDE) created to refer to
* it in code.
* @param <T> Generics allow easier casting from the calling side.
* @param window JFrame or JDialog containing component
* @param name name of the private field variable, case sensitive
* @return null if no match, otherwise a component.
*/
@SuppressWarnings("unchecked")
static public <T extends Component> T getComponentByName(Window window, String name) {
// loop through all of the class fields on that form
for (Field field : window.getClass().getDeclaredFields()) {
try {
// let us look at private fields, please
field.setAccessible(true);
// compare the variable name to the name passed in
if (name.equals(field.getName())) {
// get a potential match (assuming correct <T>ype)
final Object potentialMatch = field.get(window);
// cast and return the component
return (T) potentialMatch;
}
} catch (SecurityException | IllegalArgumentException
| IllegalAccessException ex) {
// ignore exceptions
}
}
// no match found
return null;
}
}
Se utiliza la reflexión para mirar a través de los campos de la clase para ver si se puede encontrar un componente que se refiere por una variable del mismo nombre.
NOTA: El código anterior utiliza genéricos para convertir los resultados al tipo que espere, por lo que en algunos casos es posible que tenga que ser explícito sobre el tipo de conversión. Por ejemplo, si myOverloadedMethod
acepta tanto JButton
y JTextField
, puede ser necesario definir explícitamente la sobrecarga que desea llamar ...
myOverloadedMethod((JButton) Awt1.getComponentByName(someOtherFrame, "jButton1"));
Y si no está seguro, se puede obtener una Component
y comprobar que funciona con instanceof
...
// get a component and make sure it's a JButton before using it
Component component = Awt1.getComponentByName(someOtherFrame, "jButton1");
if (component instanceof JButton) {
JButton button = (JButton) component;
// do more stuff here with button
}
Hope this helps!
Window.getWindows() y luego escanea lo que necesitas – bestsss
¿Por qué en el mundo te gustaría hacer eso?Al hacerlo, pierde dos comprobaciones importantes del compilador estático: - Primero, el campo existe. - En segundo lugar, es del tipo correcto. Además, la búsqueda dinámica es más lenta que tener una referencia al campo. – fortran
Por ejemplo, debido a las temidas API, donde no tiene acceso directo a algunos componentes que desea modificar. –