我试图在JButton上使用.getName,但它返回null,但是当我执行toString时它返回所有正确的属性?

时间:2010-08-18 00:44:04

标签: java button null

来源: javax.swing.JButton中[,571,647,80x80,alignmentX = 0.0,alignmentY = 0.5,边界= com.apple.laf.AquaButtonBorder $切换@ 1380cf2a,旗帜= 288,MAXIMUMSIZE = java.awt.Dimension中[宽度= 80,高度= 80],=的minimumSize java.awt.Dimension中[宽度= 80,高度= 80],使用preferredSize = java.awt.Dimension中[宽度= 80,高度= 80],的DefaultIcon =文件:/用户/ andreaks /桌面/ PreEntregaiDomino /build/classes/imagenes/A23.png,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=2,bottom=0,right=2],paintBorder=true,paintFocus=真,pressedIcon =,rolloverEnabled =假,rolloverIcon =,rolloverSelectedIcon =,selectedIcon =,文本=,defaultCapable =真]

NAME:null

使用的代码是

private void JBsetseleccionadActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Object boton = evt.getSource();
    JButton este= (JButton) boton;

    seleccionado = este;
    System.out.println("SOURCE " + boton.toString());
    System.out.println("NAME " + este.getName());
}

任何想法?

3 个答案:

答案 0 :(得分:1)

尝试类似:

String text = ((JButton) e.getSource()).getText();
BTW,这样的代码的更好模式是:

private JButton button;
button = new JButton("Button");
button.addActionListener(new BListener());
private class BListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == button){
            //code for when the JButton button is pushed
        }
    }
}

答案 1 :(得分:0)

getComponentVariableName(组分)

如果您正在使用NetBeans或类似的IDE,默认情况下会创建私有变量(字段)以保存对所有组件的引用,那么您可以执行以下操作...

private void JBsetseleccionadActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Object boton = evt.getSource();
    JButton este= (JButton) boton;

    seleccionado = null;
    System.out.println("SOURCE " + boton.toString());
    System.out.println("NAME " + Awt2.getComponentVariableName(boton));
    seleccionado = este;
}

使上述代码成为可能的代码如下......

import java.awt.Component;
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-getcomponentvariablenamec.html
 */
public class Awt2 {

    /**
     * substitute for component.getName() when used in NetBeans or other IDE
     * that creates class fields to hold the components. uses reflection to
     * search through class fields for a match.
     * @param component the component to look for
     * @return hopefully the variable name used to hold this component
     */
    static public String getComponentVariableName(Object object) {

        if (object instanceof Component) {
            final Component component = (Component) object;
            final StringBuilder sb = new StringBuilder();

            // find the form where the variable name would be likely to exist
            final Component parentForm = getParentForm(component);

            // loop through all of the class fields on that form
            for (Field field : parentForm.getClass().getDeclaredFields()) {

                try {
                    // let us look at private fields, please
                    field.setAccessible(true);

                    // get a potential match
                    final Object potentialMatch = field.get(parentForm);

                    // compare it
                    if (potentialMatch == component) {

                        // return the name of the variable used
                        // to hold this component
                        if (sb.length() > 0) sb.append(",");
                        sb.append(field.getName());
                    }

                } catch (SecurityException | IllegalArgumentException 
                        | IllegalAccessException ex) {

                    // ignore exceptions
                }
            }

            if (sb.length() > 0) {
                return sb.toString();
            }
        }

        // if we get here, we're probably trying to find the form
        // itself, in which case it may be more useful to print
        // the class name (MyJFrame) than the AWT-assigned name
        // of the form (frame0)
        final String className = object.getClass().getName();
        final String[] split = className.split("\\.");
        final int lastIndex = split.length - 1;
        return (lastIndex >= 0) ? split[lastIndex] : className;

    }

    /**
     * traverses up the component tree to find the top, which i assume is the
     * dialog or frame upon which this component lives.
     * @param sourceComponent
     * @return top level parent component
     */
    static public Component getParentForm(Component sourceComponent) {
        while (sourceComponent.getParent() != null) {
            sourceComponent = sourceComponent.getParent();
        }
        return sourceComponent;
    }
}

它使用反射来查看表单上的所有私有变量,并尝试将它们与您要识别的组件相匹配。如果找到匹配项,则返回用于引用该组件的java变量的名称。如果它找到两个或多个匹配项,则返回逗号分隔列表,这就是我将seleccionado = null;添加到第一个示例中的原因。如果我们把代码放回原来......

private void JBsetseleccionadActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Object boton = evt.getSource();
    JButton este= (JButton) boton;

    seleccionado = este;
    System.out.println("SOURCE " + boton.toString());
    System.out.println("NAME " + Awt2.getComponentVariableName(boton));
}

结果可能如下所示......

SOURCE javax.swing.JButton[,6,6,126x28,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@7c0d41,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=What's my name?,defaultCapable=true]
NAME seleccionado,jButton1

希望这有帮助!

答案 2 :(得分:0)

虽然这是一个老问题,但如果有帮助,我仍然想回答。

添加按钮时,请确保调用setName()函数,如下所示:

private void JBsetseleccionadActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Object boton = evt.getSource();
    JButton este = (JButton) boton;
    este.setName("button_name"); // set the name first

    seleccionado = este;
    System.out.println("SOURCE " + boton.toString());
    System.out.println("NAME " + este.getName());
}

这应解决您的问题,getName()应该能够提供名称。这有点奇怪,但仍然是完成它的最简单方法。