将动作侦听器添加到XML中提到的按钮

时间:2018-03-20 10:21:23

标签: java xml swing compiler-errors jbutton

我尝试在下面的代码中使用ActionListenerJButton添加到XML中的DocumentBuilderfactory

我收到错误:Duplicate local variable element在我在下面发表评论的行。

但是,如果我重命名其中一个变量,那么如何将此actionListener链接到XML中存在的ID按钮?

public static void main (String args[]) throws IOException{
     try{
        XMLDecoder xmlDecoder = new XMLDecoder(new FileInputStream("ActionListener.xml"));
        Object frame = xmlDecoder.readObject();
        xmlDecoder.close();
        System.out.println("siri");
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File("ActionListener.xml"));
        Element element = doc.getElementById("Id");
        String attrValue = element.getAttribute("string");
        JButton element = new JButton("attrValue"); // <-- error happens here
        element.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                System.out.println("Its a success");
            } 
        });
    }
    catch(Exception ex){
        System.out.println(ex);
    }
}

1 个答案:

答案 0 :(得分:1)

正如异常所示,您的代码中有一个重复的变量。 这意味着您尝试声明一个与另一个名称完全相同的新变量。

在您的代码中,您有两个名为element的变量:

Element element = doc.getElementById("Id");
JButton element = new JButton("attrValue");

重命名其中一个以解决您的问题。

接下来,你的代码的这部分看起来很阴暗:

Element element = doc.getElementById("Id");
String attrValue = element.getAttribute("string");
JButton button = new JButton("attrValue"); //Note I changed the variable name

从不使用变量attrValue字符串值,因为您将常量字符串值“attrValue”设置为JButton标签。 你可能想写:

JButton button = new JButton(attrValue);

另外,您创建了一个全新的JButton并添加了一个actionListener,但它没有显示,因为您从未将其添加到视图中。

相关问题