import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JDialog; import javax.swing.*; /* * MessageWindow.java * * Note: This code is not suitable for any production use. It is quick code to * enable students to easily get an answer. For "real" code use JOptionPane * instead. * * Created on September 28, 2007, 1:01 PM * * @Author Dan Fleck, * George Mason University * Computer Science Department */ /** * * @author dfleck */ public class MessageWindow implements ActionListener { /** Holds the frame. */ private static JFrame jframe; /** Holds a text field. */ private static JTextField input = new JTextField(); /** Has the answer been submitted. */ private static boolean submitted = false; /** Given a question, display it to the user and ask for an answer. */ public static String getResponse(String question) { MessageWindow listener = new MessageWindow(); submitted = false; jframe = new JFrame("Question"); jframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); JComponent box = Box.createVerticalBox(); JButton jb = new JButton("Submit"); box.add(new JLabel(question)); box.add(input); box.add(jb); jb.addActionListener(listener); jframe.getContentPane().add(box); jframe.setVisible(true); jframe.pack(); /** Wait for an answer. */ while (!submitted) { try {Thread.sleep(50); } catch (Exception e) {} } return input.getText(); } public void actionPerformed(ActionEvent e) { submitted = true; } public static void close() { jframe.setVisible(false); jframe.dispose(); } public static void main(String [] args) { String ans = MessageWindow.getResponse("this is a test"); System.out.println(ans); MessageWindow.close(); } }