Java 按名称获取Swing组件
我在Java 按名称获取Swing组件,java,swing,jframe,Java,Swing,Jframe,我在JFrame中有一些我想要的组件 参考另一个JFrame,我想要 通过名字而不是 对每种方法都执行公共获取/设置方法 从Swing有没有一种方法可以像do一样通过其名称获取组件引用 c# e、 g.form.Controls[“text”] 谢谢您可以将一个变量声明为公共变量,然后获取文本或任何您想要的操作,然后您可以在另一个框架(如果它在同一个包中)中访问它,因为它是公共的。您可以在第二个JFrame中保留对第一个JFrame的引用,只需循环JFrame.getComponents(),检
JFrame
中有一些我想要的组件
参考另一个JFrame
,我想要
通过名字而不是
对每种方法都执行公共获取/设置方法
从Swing有没有一种方法可以像do一样通过其名称获取组件引用
c#
e、 g.form.Controls[“text”]
谢谢您可以将一个变量声明为公共变量,然后获取文本或任何您想要的操作,然后您可以在另一个框架(如果它在同一个包中)中访问它,因为它是公共的。您可以在第二个JFrame中保留对第一个JFrame的引用,只需循环JFrame.getComponents(),检查每个元素的名称。每个元素都可以有一个名称,可以通过
getName()
和setName()
访问,但您必须编写自己的查找函数。我知道这是一个老问题,但我刚才发现自己在问这个问题。我想要一种简单的方法,通过名称获取组件,这样我就不必每次都编写一些复杂的代码来访问不同的组件。例如,让JButton访问文本字段中的文本或列表中的选择
最简单的解决方案是将所有组件变量都设置为类变量,以便您可以在任何地方访问它们。然而,并不是每个人都想这样做,有些人(像我一样)正在使用GUI编辑器,这些编辑器不会将组件生成为类变量
我想,我的解决方案很简单,而且据我所知,并没有违反任何编程标准(参考fortran的内容)。它允许以一种简单明了的方式按名称访问组件
private HashMap componentMap;
initialize() {
//add your components and be sure
//to name them.
...
//after adding all the components,
//call this method we're about to create.
createComponentMap();
}
private void createComponentMap() {
componentMap = new HashMap<String,Component>();
Component[] components = yourForm.getContentPane().getComponents();
for (int i=0; i < components.length; i++) {
componentMap.put(components[i].getName(), components[i]);
}
}
public Component getComponentByName(String name) {
if (componentMap.containsKey(name)) {
return (Component) componentMap.get(name);
}
else return null;
}
private void createComponentMap(){
componentMap=新的HashMap();
Component[]components=yourForm.getContentPane().getComponents();
对于(int i=0;i
如果您计划在运行时在任何时候添加、删除或重命名组件,我将考虑根据您的更改添加修改HASMAP的方法。
GETCuffeTnBame(框架,名称)< /P> 如果您使用的是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;
}
}
如果你不确定,你可以得到一个组件
,并用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
}
希望这有帮助 我需要访问单个
JFrame
中的几个JPanel
s中的元素
@Jesse Strickland给出了一个很好的答案,但是提供的代码无法访问任何嵌套元素(比如在我的例子中,JPanel
)
在谷歌搜索之后,我发现了@aioobe提供的这个递归方法
通过组合并稍微修改@Jesse Strickland和@aioobe的代码,我得到了一个可以访问所有嵌套元素的工作代码,无论它们有多深:
private void createComponentMap() {
componentMap = new HashMap<String,Component>();
List<Component> components = getAllComponents(this);
for (Component comp : components) {
componentMap.put(comp.getName(), comp);
}
}
private List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container)
compList.addAll(getAllComponents((Container) comp));
}
return compList;
}
public Component getComponentByName(String name) {
if (componentMap.containsKey(name)) {
return (Component) componentMap.get(name);
}
else return null;
}
private void createComponentMap(){
componentMap=新的HashMap();
列表组件=getAllComponents(此);
用于(组件组件:组件){
componentMap.put(comp.getName(),comp);
}
}
私有列表getAllComponents(最终容器c){
组件[]comps=c.getComponents();
List compList=new ArrayList();
用于(组件组件:组件){
compList.add(comp);
if(容器的组件实例)
addAll(getAllComponents((容器)comp));
}
返回compList;
}
公共组件getComponentByName(字符串名称){
if(componentMap.containsKey(名称)){
返回(组件)componentMap.get(名称);
}
否则返回null;
}
代码的用法与@Jesse Strickland代码中的用法完全相同。如果您的组件是在处理它们的同一个类中声明的,您只需将这些组件作为类名的属性访问即可
public class TheDigitalClock {
private static ClockLabel timeLable = new ClockLabel("timeH");
private static ClockLabel timeLable2 = new ClockLabel("timeM");
private static ClockLabel timeLable3 = new ClockLabel("timeAP");
...
...
...
public void actionPerformed(ActionEvent e)
{
...
...
...
//set all components transparent
TheDigitalClock.timeLable.setBorder(null);
TheDigitalClock.timeLable.setOpaque(false);
TheDigitalClock.timeLable.repaint();
...
...
...
}
...
...
...
}
而且,也可以从同一名称空间中的其他类访问类组件作为类名的属性。我可以访问受保护的属性(类成员变量),也许您也可以访问公共组件。试试看 Swing确实提供了其他实现方法,因为我的版本实现了在组件层次结构上下文中查找
/**
* Description : Find a component having the given name in container desccendants hierarchy
* Assumptions : First component with the given name is returned
* @return java.awt.Component
* @param component java.awt.Component
* @param componentName java.lang.String
*/
public static Component findComponentByName(Component component, String componentName) {
if (component == null ) {
return null;
}
if (component.getName() != null && component.getName().equalsIgnoreCase(componentName)) {
return component;
}
if ( (component instanceof Container ) ) {
Component[] children = ((Container) component).getComponents();
for ( int i=0; i<children.length; i++ ) {
Component child = children[i];
Component found = findComponentByName( child, componentName );
if (found != null ) {
return found;
}
}
}
return null;
}
/**
*描述:在容器描述层次结构中查找具有给定名称的组件
*假设:返回具有给定名称的第一个组件
*@return java.awt.Component
*@param component java.awt.component
*@param componentName java.lang.String
*/
公共静态组件findComponentByName(组件组件、字符串组件名称){
如果(组件==null){
返回null;
}
如果(component.getName()!=null&&component.getName().equals
/**
* Description : Find a component having the given name in container desccendants hierarchy
* Assumptions : First component with the given name is returned
* @return java.awt.Component
* @param component java.awt.Component
* @param componentName java.lang.String
*/
public static Component findComponentByName(Component component, String componentName) {
if (component == null ) {
return null;
}
if (component.getName() != null && component.getName().equalsIgnoreCase(componentName)) {
return component;
}
if ( (component instanceof Container ) ) {
Component[] children = ((Container) component).getComponents();
for ( int i=0; i<children.length; i++ ) {
Component child = children[i];
Component found = findComponentByName( child, componentName );
if (found != null ) {
return found;
}
}
}
return null;
}