1
2
3
4
5
6
7
8
9
10
11
12 package org.hyphenType.input;
13
14 import java.awt.GraphicsEnvironment;
15 import java.awt.HeadlessException;
16 import java.io.Console;
17
18 import javax.swing.JOptionPane;
19
20 import org.hyphenType.util.soc.StringObjectConversion;
21 import org.hyphenType.util.soc.StringParsingError;
22
23
24
25
26 public class StandardUserInput extends UserInput {
27
28 @Override
29 protected boolean isGraphicalUIAvailable() {
30 return !GraphicsEnvironment.isHeadless();
31 }
32
33 @Override
34 protected <T> T readFromGraphicalUI(Class<T> type, String message, String regex) throws UserInputException {
35 if (!isGraphicalUIAvailable())
36 throw new UserInputException("Graphical environment not available.");
37 try {
38 String input = JOptionPane.showInputDialog(message);
39 if (input == null)
40 return null;
41 if (!input.matches(regex))
42 throw new UserInputException("Input does not match regex.");
43 return StringObjectConversion.fromString(type, input);
44 } catch (HeadlessException e) {
45 throw new UserInputException(e);
46 } catch (StringParsingError e) {
47 throw new UserInputException(e);
48 }
49 }
50
51 @Override
52 protected boolean isTextUIAvailable() {
53 return System.console() != null;
54 }
55
56 @Override
57 protected <T> T readFromTextUI(Class<T> type, String message, String regex) throws UserInputException {
58 if (!isTextUIAvailable())
59 throw new UserInputException("System console not available while trying to use text input.");
60 try {
61 Console console = System.console();
62 String input = console.readLine(message + " ");
63 if (input.equals(""))
64 return null;
65 if (!input.matches(regex))
66 throw new UserInputException("Input does not match regex.");
67 return StringObjectConversion.fromString(type, input);
68 } catch (StringParsingError e) {
69 throw new UserInputException(e);
70 }
71 }
72 }