How to exit a method in ActionListener

后端 未结 1 1212
不知归路
不知归路 2021-01-28 08:19

I have an ActionListener connected to a JTextField and want to type something so that it will exit the method the ActionListener is in.

相关标签:
1条回答
  • 2021-01-28 09:04

    Basically what you need is some kind of modal dialog, which will allow you to, effectively, halt the execution of your program at the point the dialog is made visible until the dialog is dismissed (closed), when the execution will continue...

    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);
    
            }
    
        }
    
    }
    

    See How to Make Dialogs for more details

    0 讨论(0)
提交回复
热议问题