在actionPerformed中访问变量

时间:2013-02-05 00:52:52

标签: java java-ee-6 actionlistener

我必须定义一个名为'path'的变量,可以在ActionListener中的代码中看到......但是我无法在actionPerformed方法之外访问'path'变量!它在方法之外变为空...我如何访问这个变量?!

button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            System.out.println("Search " + textField.getText()
                    + " in Project");

            try {
                System.out.println(project.members().length);
                IResource[] ires = project.members();
                String path = "";
                String findResult = "notFound";
                for (int len = 0; len < ires.length; len++) {
                    if (!(path = loopInFolders(project, ires[len],
                            textField.getText())).equals("")) {
                        System.out.println("found at :" + path);
                        findResult = "found";

                        showResultBox(findResult, path);

                        break;
                    }
                }

                if (path.equals("")) {
                    showResultBox(findResult, path);
                }
            } catch (CoreException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }


        }
    });

即使我使用getter和setter将变量定义为类中的全局变量,但变量不保留其在actionPerformed中的值!只在Listener里面有我想要的正确值...我想在其他方法中使用这个值,但它在那里变为null!

这是我的课!我想在execute方法中访问path变量,这个变量将在createOutput方法中的actionListener中填充,但是在actionListener之外它总是为null!

public class FindHandler extends AbstractHandler {

private String path;

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    Shell shell = HandlerUtil.getActiveShell(event);
    ISelection sel = HandlerUtil.getActiveMenuSelection(event);

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(sel.toString()
            .substring(1, sel.toString().indexOf(" ")).trim());
    System.out.println("selected folder "
            + sel.toString().substring(1, sel.toString().indexOf(" "))
                    .trim());



    createOutput(shell, project);

    if (path != null) {
        System.out.println("Pathhhh***444"+ path);
        IPath iPath = new Path(path);
        IFile file = project.getFile(iPath);
        System.out.println("test file*****" + file.getName());

        file = ResourcesPlugin.getWorkspace().getRoot()
                .getFileForLocation(iPath);

        ISelection selection = new StructuredSelection(file);

        IViewReference[] views = PlatformUI.getWorkbench()
                .getActiveWorkbenchWindow().getActivePage()
                .getViewReferences();
        PlatformUI.getWorkbench().getActiveWorkbenchWindow()
                .getActivePage().resetPerspective();

        for (IViewReference view : views) {
            if ("org.eclipse.jdt.ui.PackageExplorer".equals(view.getId())) {
                IViewPart pExplorer = view.getView(true);
                pExplorer.getViewSite().getSelectionProvider()
                        .setSelection(selection);
                break;
            }
        }
    }

    return null;
}

private void createOutput(Shell shell, final IProject project) {

    // Creating the window with a textBox and two buttons of 'Search' and
    // 'Cancel'
    System.out.println(project.getLocation());
    final JTextField textField = new JTextField();
    final JFrame frame = new JFrame("Search File");
    frame.setLayout(null);
    frame.setSize(350, 250);
    frame.setLocation(350, 250);
    JLabel label = new JLabel("Enter File Name:");
    label.setSize(120, 20);
    label.setLocation(20, 25);
    textField.setSize(150, 20);
    textField.setLocation(150, 25);
    frame.getContentPane().add(textField);
    frame.getContentPane().add(label);
    JButton button = new JButton("Search");
    button.setSize(100, 30);
    button.setLocation(70, 100);
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            System.out.println("Search " + textField.getText()
                    + " in Project");

            try {
                System.out.println(project.members().length);
                IResource[] ires = project.members();
                path = "";
                String findResult = "notFound";
                for (int len = 0; len < ires.length; len++) {
                    if (!(path = loopInFolders(project, ires[len],
                            textField.getText())).equals("")) {
                        System.out.println("found at :" + path);
                        findResult = "found";

                        showResultBox(findResult, path);

                        break;
                    }
                }

                if (path.equals("")) {
                    showResultBox(findResult, path);
                }
            } catch (CoreException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }


        }
    });
    frame.getContentPane().add(button); // Adds Button to content pane of
                                        // frame
    JButton button_2 = new JButton("Cancel");
    button_2.setSize(100, 30);
    button_2.setLocation(180, 100);
    button_2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            frame.dispose();
        }
    });
    frame.getContentPane().add(button_2);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

    System.out.println("Pathhhh***333"+ path);

}


public String loopInFolders(IProject project, IResource ires,
        String fileName) {

    if (ires.getName().equals(fileName)) {
        return ires.getLocation().toString();
    } else {
        System.out.println(ires.getName());
        IFolder secondFolder = null;
        try {
            secondFolder = project.getFolder(ires.getName());
            System.out.println(secondFolder.members().length);
            if (secondFolder.members().length > 0) {
                IResource[] ires1 = secondFolder.members();
                for (int i = 0; i < ires1.length; i++) {
                    if (!loopInFolders(project, ires1[i], fileName).equals(
                            ""))
                        return ires1[i].getLocation().toString();
                }
            }
        } catch (Exception ex) {
        }
    }
    return "";

}

public void showResultBox(String findResult, String path) {

    if (findResult.equals("notFound")) {

        final JFrame frame = new JFrame("File Not Found");
        frame.setLayout(null);
        frame.setSize(350, 250);
        frame.setLocation(350, 250);
        JLabel label = new JLabel("There is no such file in the project!");
        label.setSize(600, 20);
        label.setLocation(20, 25);

        frame.getContentPane().add(label);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

    } else {

        System.out.println("Pathhhh***111"+ path);

        final JFrame frame = new JFrame("File Found");
        frame.setLayout(null);
        frame.setSize(350, 250);
        frame.setLocation(350, 250);
        JLabel label = new JLabel("File is found at: " + path);
        label.setSize(600, 20);
        label.setLocation(20, 25);

        frame.getContentPane().add(label);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

    }

}

}

3 个答案:

答案 0 :(得分:3)

    // make path a global variable
    String path;


    // if you are trying to access path in another class,
    // make sure you have a getter method like 
    public String getPath() {
       return this.path;
    }

    button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

        System.out.println("Search " + textField.getText()
                + " in Project");

        try {
            System.out.println(project.members().length);
            IResource[] ires = project.members();
            path = "";
            String findResult = "notFound";
            for (int len = 0; len < ires.length; len++) {
                if (!(path = loopInFolders(project, ires[len],
                        textField.getText())).equals("")) {
                    System.out.println("found at :" + path);
                    findResult = "found";

                    showResultBox(findResult, path);

                    break;
                }
            }

            if (path.equals("")) {
                showResultBox(findResult, path);
            }
        } catch (CoreException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


    }
});

答案 1 :(得分:2)

声明一个名为path的类级别字段。在ActionListener中,请勿再次重新声明,只需为其分配所需的新值。

public class MyClass {
    private String path;

    public MyClass() {
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                path = "";                
                //....//
            }
        }
    }
}

显然,这是一个简化的例子,你的实现可能会有所不同......

答案 2 :(得分:2)

您的问题也可能是您正在使用JFrame而不是模态JDialog。你的execute方法创建了一个窗口(上面提到的JFrame),显示窗口然后 立即 尝试使用路径变量,然后才能使用它与之交互的机会新窗口,所以路径为空是有意义的。

为防止这种情况发生,要停止执行execute方法,直到用户处理完窗口并按下JButton键,再次不显示JFrame,而是显示模态的JDialog。如果这样做,当对话框设置为visible时,调用代码将被“保持”,直到对话框不再可见,此时运气路径不会为空。