如何在ActionListener中退出方法

时间:2014-12-19 06:19:26

标签: java swing methods actionlistener jtextfield

我有ActionListenerJTextField相关联,并希望输入内容以便退出ActionListener所在的方法。

代码:

main() {
    Security(x,x,x);
}
public void Security(JTextArea out, JTextField in) {
        in.setText("");
        in.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (in.getText().contains("exitsys")) {
                    out.append("Security:Security System Deactivated\n");
                    return;
                }
                in.setText("");
            }
        });
        out.append("Security:Security System Activated\n");
        fileWrite(":SYSTEM_INITIATED@" + time(), out);
    }

我想输入"exitsys"并返回主类方法"main()"

fileWrite方法使用PrintWriter输出数据。

问题摘要:我尝试调用return;但它没有返回方法main(),我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

基本上你需要的是某种模态对话框,这将允许你有效地停止程序的执行,直到对话框被解除(关闭),执行将继续时对话框可见...

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JDialog dialog = new JDialog();
                dialog.setTitle("Testing");
                dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                dialog.add(new TestPane());
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);

                System.out.println("Now back in the main...");
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField field;

        public TestPane() {

            setLayout(new GridBagLayout());

            field = new JTextField(10);
            field.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if ("exitsys".equals(field.getText())) {
                        SwingUtilities.getWindowAncestor(field).dispose();
                    }
                }
            });

            add(field);

        }

    }

}

有关详细信息,请参阅How to Make Dialogs