getComponentByName (telaio, nome)
se si sta utilizzando NetBeans IDE o un altro che di default crea variabili private (campi) per contenere tutti i componenti AWT/Swing, quindi il seguente codice può funzionare per te. Utilizzare come segue:
// 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());
Ecco il codice per fare quanto sopra è possibile ...
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;
}
}
Si utilizza la riflessione per guardare attraverso i campi della classe per vedere se si riesce a trovare un componente che si riferisce a da una variabile con lo stesso nome
NOTA: il codice sopra riportato utilizza i generici per trasmettere i risultati a qualsiasi tipo che ci si aspetta, quindi in alcuni casi potrebbe essere necessario esplicitare il tipo di trasmissione. Per esempio, se myOverloadedMethod
accetta sia JButton
e JTextField
, potrebbe essere necessario definire esplicitamente il sovraccarico che si desidera chiamare ...
myOverloadedMethod((JButton) Awt1.getComponentByName(someOtherFrame, "jButton1"));
E se non siete sicuri, è possibile ottenere un Component
e controllare 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
}
Spero che questo aiuti!
Window.getWindows() e quindi scansiona quello che ti serve – bestsss
Perché nel mondo ti piacerebbe farlo?In questo modo, si perdono due importanti controlli del compilatore statico: - Innanzitutto, il campo esiste. - In secondo luogo, è del tipo corretto. Inoltre, la ricerca dinamica è più lenta dell'avere un riferimento al campo. – fortran
Ad esempio, a causa delle API temute, in cui non si ha accesso diretto ad alcuni componenti che si desidera modificare. –