package Lect39GUIs; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingOptionPaneReplacement1 { static synchronized public String showInputDialog(String labelText) { JFrame frame = buildFrame(); JTextField textField = buildGUI(frame, labelText); displayFrame(frame); // This is a fancy way of saying stop execution until frame.notify() is called elsewhere // That happens when the user clicks on the OK button synchronized (frame) { try { frame.wait(); } catch (InterruptedException e) {} } // User has clicked on OK button, so get rid of window and return string frame.hide(); frame.dispose(); return textField.getText(); } static private JFrame buildFrame() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) {} // Create a top-level window to put the picture in JFrame frame; frame = new JFrame("Swing Example"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); return frame; } static private JTextField buildGUI(JFrame frame, String labelText) { JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); panel.setLayout(new BorderLayout()); JLabel label = new JLabel(labelText); panel.add(label, BorderLayout.NORTH); JTextField textField = new JTextField(); panel.add(textField, BorderLayout.CENTER); JButton okButton = new JButton("OK"); panel.add(okButton, BorderLayout.SOUTH); OptionPaneOKListener okListener = new OptionPaneOKListener(frame); okButton.addActionListener(okListener); textField.addKeyListener(okListener); frame.setContentPane(panel); return textField; } static private void displayFrame(JFrame frame) { frame.setLocation(100, 100); frame.pack(); frame.show(); } static public void main(String[] args) { String result = SwingOptionPaneReplacement1.showInputDialog("Enter some text:"); System.out.println("You entered: " + result); } } class OptionPaneOKListener implements ActionListener, KeyListener { private JFrame frame; public OptionPaneOKListener(JFrame frame) { this.frame = frame; } public void actionPerformed(ActionEvent e) { okAction(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { okAction(); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } private void okAction() { synchronized (frame) { frame.notifyAll(); } } }