通过GUI等待用户输入

时间:2016-04-19 00:03:03

标签: java swing actionlistener

我是java的新手,所以这可能是一个愚蠢的问题。我想停止我的程序,直到用户按下回车。我已经实现了Actionlistener但是在按下回车键后我想打印一条消息。所有我可以想到的是实施一段时间的条件,但它似乎不起作用。

public class main {

static JTextField field;
static int x;
public static void main (String [] args)
{   
    JFrame frame = new JFrame("frame");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    frame.add(panel);
    field = new JTextField("field");
    panel.add(field);
    field.addActionListener(new action());
    while(x==0)//i want my program to stop here ,wait for user enter input and then  output below message
    JOptionPane.showMessageDialog(null, "show message after user has preseed enter");

}
static public class action implements ActionListener
{

    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == field)
        {
            JOptionPane.showMessageDialog(null, "user pressed enter");
            x=1;
        }

    }   

}

}

1 个答案:

答案 0 :(得分:1)

GUI是事件驱动程序,Swing是单线程,因此任何阻塞或长时间破坏操作都将停止UI并防止更新或响应用户输入。

有几种方法可以实现这一点,你可以使用某种观察者模式在触发ActionListener时接收事件通知,但是根据你似乎想要做的事情,我建议使用某种形式的模态对话框。

请查看How to Make Dialogs了解更多详情

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.JOptionPane;
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 frame = new JDialog((JFrame)null, "Help", true);
                frame.add(new FieldPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                JOptionPane.showMessageDialog(null, "This is after the dialog is closed");
            }
        });
    }

    public class FieldPane extends JPanel {

        public FieldPane() {
            setLayout(new GridBagLayout());
            JTextField field = new JTextField(20);
            add(field);
            field.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SwingUtilities.windowForComponent(FieldPane.this).dispose();
                }
            });
        }

    }

}