getComponentByName (frame, name)
ЕСЛИ вы используете NetBeans или другую IDE, которая по умолчанию создает закрытые переменные (поля) для хранения всех ваших компонентов AWT / Swing, тогдаследующий код может работать для вас.Используйте его следующим образом:
// 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());
Вот код, позволяющий сделать все возможное выше ...
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;
}
}
Он использует отражение, чтобы просмотреть поля класса, чтобы увидеть, может ли он найти компонентна который ссылается переменная с тем же именем.
ПРИМЕЧАНИЕ. Приведенный выше код использует обобщенные значения для приведения результатов к тому типу, который вы ожидаете, поэтому в некоторых случаях вам может потребоваться явно указать тип приведения.Например, если myOverloadedMethod
принимает и JButton
, и JTextField
, вам может понадобиться явно определить перегрузку, которую вы хотите вызвать ...
myOverloadedMethod((JButton) Awt1.getComponentByName(someOtherFrame, "jButton1"));
И если вы не уверены, вы можетеполучите Component
и проверьте его с помощью 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
}
Надеюсь, это поможет!