【问题标题】:JAVA: how to create button with name parameter of the method?JAVA:如何使用方法的名称参数创建按钮?
【发布时间】:2015-03-23 22:47:47
【问题描述】:

我想编写一个方法来创建不同名称的 JButton。

我希望我可以发送参数名称和按钮标题。

AddButtonMethod("name", "title");

方法:

private void AddButtonMethod(String name, String title){


            JButton name = new JButton(title);

            name.addActionListener(ecouteurBouton);

            add(name);

    }

我希望新按钮作为收到 patranetre "name" 的名称

谢谢你

【问题讨论】:

    标签: java swing methods jbutton


    【解决方案1】:

    请理解变量名远没有你想象的那么重要,而且在代码编译后几乎不存在。更重要和关键的是变量引用——能够在程序中的特定点访问特定对象,并且您可以使用 Map(如 HashMap)轻松地让字符串引用对象。比如

    // in the variable declaration section of the class
    private Map<String, JButton> buttonMap = new HashMap<>();
    
    // your method should be named addButton, not AddButton
    private void addButton(String name, String title){
       JButton button = new JButton(title);
       button.addActionListener(ecouteurBouton);
       buttonMap.put(name, button);
       add(button);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多