packageme.timothy.consolegui;
importjava.util.Scanner;
importjavax.swing.*;
importjava.awt.BorderLayout;
importjava.awt.event.ActionListener;
importjava.awt.event.ActionEvent;
importjava.io.PrintStream;
importjava.io.BufferedWriter;
importjava.io.FileWriter;
importjava.io.File;
importjava.io.IOException;
importjava.util.InputMismatchException;
importjavax.swing.text.DefaultCaret;
/**
* Turns a console program into a basic GUI program, useful
* for Window 7 programs that are unable to open command
* prompt with a .jar All a class has to do in order to use
* this program is call the static method toGUI(), a special Scanner is
* acquirable instead of System.in
* (Attrievable by a call to getScanner(), which is static)
* By a call to saveSaveText(true), it will save the calls to out and scanner,
* however it does not throw any exceptions and may cause lag if
* there are a lot of System.out calls.
*
* @author Timothy Moore
*/publicclassConsoleGUIextendsJFrame
{
protectedstaticvolatilebooleansaveRun = false;
/**
* The ConsoleGUI
*/protectedstaticConsoleGUIgui;
/**
* The Scanner being used
*/protectedTAScannerscanner;
/**
* The stream being used
*/protectedTAPrintStreamstream;
/**
* The main text area, where calls to System.out go
*/privateJTextAreatxtArea;
/**
* Where the user enters information
*/privateJTextFielduserField;
/**
* The submit button, not actually necessary
*/privateJButtonsubmit;
/**
* The JScrollPane wrapper
*/privateJScrollPanesPane;
/**
* Creates the GUI
*/protectedConsoleGUI()
{
setSize(350, 350);
setTitle("Console GUI");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(newBorderLayout());
txtArea = newJTextArea();
txtArea.setEditable(false);
sPane = newJScrollPane(txtArea);
add(sPane, BorderLayout.CENTER);
userField = newJTextField();
userField.setEditable(false);
userField.setActionCommand("submit");
submit = newJButton("Submit");
submit.setActionCommand("submit");
JPanelbot = newJPanel();
bot.setLayout(newBorderLayout());
bot.add(userField, BorderLayout.CENTER);
bot.add(submit, BorderLayout.EAST);
add(bot, BorderLayout.SOUTH);
System.out.println("here");
}
/**
* Sets the program to use the ConsoleGUI instead of the regular
* Console
*/publicstaticvoidtoGUI()
{
try
{
if(!SwingUtilities.isEventDispatchThread())
{
SwingUtilities.invokeAndWait(newRunnable() {
@Overridepublicvoidrun()
{
gui = newConsoleGUI();
gui.stream = gui.createPrintStream();
gui.setVisible(true);
}
});
}else
{
gui = newConsoleGUI();
gui.stream = gui.createPrintStream();
gui.setVisible(true);
}
}catch(Exceptionexc)
{
handleException("Failed to convert to gui", exc, saveRun);
}
}
publicstaticvoidclear() {
// TODO Auto-generated method stub
gui.txtArea.setText("");
}
publicstaticvoidsetConsoleTitle(Stringtit)
{
gui.setTitle(tit);
}
/**
* Creates a TAPrintStream based on the text area
*/protectedTAPrintStreamcreatePrintStream()
{
returnnewTAPrintStream(txtArea);
}
/**
* @return a new TAScanner
*/privateTAScannercreateScanner()
{
returnnewTAScanner(userField, submit);
}
/**
* @return the print stream
*/publicstaticTAPrintStreamgetStream()
{
returngui.stream;
}
/**
* Sets if it is saving the text, by default false
* @param b if it should save text
*/publicstaticvoidsetSaveText(booleanb)
{
saveRun = b;
}
/**
* @return the scanner to use. Has most methods of Scanner
* @throws NullPointerException if called before toGUI
*/publicstaticTAScannergetScanner()
{
if(gui.scanner == null)
gui.scanner = gui.createScanner();
returngui.scanner;
}
publicstaticConsoleGUIgetGUI()
{
returngui;
}
/**
* Handles an exception with the specified message and
* underlying throwable. This method will handle all
* exceptions appropriately.
*
* This method will return normally.
*
* @param msg the message, can be null.
* @param exc the exception, cannot be null
* @param saveToFile if file io should be attempted.
*/publicstaticvoidhandleException(Stringmsg, Throwableexc, booleansaveToFile)
{
try
{
TAPrintStreamout = getStream();
out.print(msg);
out.println(" - " + exc.getClass().getSimpleName());
StackTraceElement[] elements = exc.getStackTrace();
for(StackTraceElementt : elements)
{
out.println(t);
}
}catch(SecurityExceptionexce)
{
setSaveText(false);
}catch(Exceptionexce)
{
// Not cool.
exce.printStackTrace();
System.err.println(msg);
}
}
/**
* For testing purposes, shows an example usage of this program
*/publicstaticvoidmain(String[] args)
{
ConsoleGUI.toGUI();
ConsoleGUI.setSaveText(true);
TAScannerscanner = ConsoleGUI.getScanner();
TAPrintStreamout = ConsoleGUI.getStream();
out.println("Type a string");
Stringstr = scanner.nextLine();
out.println("Type an int");
inti = scanner.nextInt();
out.println("You typed "+str+" and "+i);
out.println("Say something starting with y");
booleanb = scanner.nextBoolean();
out.println(b);
out.println("Say something starting with n");
b = scanner.nextBoolean("n", true);
out.println(b);
out.println("Say banana");
b = scanner.nextBoolean("banana", false);
out.println(b);
out.println();
RuntimeExceptionexc = newRuntimeException();
handleException("Test", exc, saveRun);
//for(int i = 0; i < 50; i++) { out.println("Purposeful Spam"); }
}
@OverridepublicStringtoString()
{
return"initialized";
}
/**
* Short for TextAreaPrintStream, this stream sends all messages
* to the GUI instead of the regular System.out
*
* @author Timothy Moore
*/publicclassTAPrintStream
{
privateJTextAreatxtArea;
privateBufferedWriterfileWriter;
privatefinalFilefile = newFile("lastRun.txt");
/**
* Create a print stream to the specified text area
*/privateTAPrintStream(JTextAreatxtArea)
{
this.txtArea = txtArea;
DefaultCaretcaret = (DefaultCaret)txtArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
}
publicvoidprint(Objectmsg)
{
txtArea.append(msg.toString());
if(saveRun)
{
if(fileWriter == null)
{
//System.out.println("Creating file writer");
try
{
file.createNewFile();
fileWriter = newBufferedWriter(newFileWriter(file));
}catch(Exceptionexc)
{
saveRun = false;
handleException("Failed to create file", exc, false);
}
Runtime.getRuntime().addShutdownHook(newThread()
{
@Overridepublicvoidrun()
{
try
{
fileWriter.close();
}catch(IOExceptione)
{
handleException("Failed to close writer", e, false);
}
}
});
}
//System.out.println("Saving to filewriter");
try
{
String[] msgs = msg.toString().split("/n");
for(Strings : msgs)
{
fileWriter.write(s);
fileWriter.newLine();
}
}catch(Exceptione)
{
handleException("Failed to write to file", e, false);
saveRun = false;
}
}
}
publicvoidprint(booleanmsg)
{
print(newStringBuilder().append(msg));
}
publicvoidprint(intmsg)
{
print(newStringBuilder().append(msg));
}
publicvoidprint(longmsg)
{
print(newStringBuilder().append(msg));
}
publicvoidprint(doublemsg)
{
print(newStringBuilder().append(msg));
}
publicvoidprintln()
{
print("\n");
}
publicvoidprintln(Objectmsg)
{
print(newStringBuilder().append(msg).append("\n"));
}
publicvoidprintln(intmsg)
{
println(newStringBuilder().append(msg));
}
publicvoidprintln(longmsg)
{
println(newStringBuilder().append(msg));
}
publicvoidprintln(booleanmsg)
{
println(newStringBuilder().append(msg));
}
publicvoidprintln(doublemsg)
{
println(newStringBuilder().append(msg));
}
}
/**
* Short for TextAreaScanner, this Scanner retrieves messages
* from the GUI instead of the regular new Scanner(System.in)
*
* @author Timothy Moore
*/publicclassTAScannerimplementsActionListener
{
privateStringstr;
privateJTextFieldfield;
privateJButtonbut;
/**
* Creates a scanner based on the specified text field
* and button
*/privateTAScanner(JTextFieldfield, JButtonbut)
{
this.field = field;
this.but = but;
field.addActionListener(this);
but.addActionListener(this);
}
/**
* Reads one string
*/publicStringreadLine()
{
field.setEditable(true);
str = null;
while(str == null)
{
delay(100);
}
ConsoleGUI.getStream().println(newStringBuilder("> ").append(str));
returnstr;
}
/**
* Same as readLine()
*/publicStringnextLine()
{
returnreadLine();
}
/**
* Same as readInt()
*/publicintnextInt()
{
returnreadInt();
}
/**
* Same as readBoolean()
*/publicbooleannextBoolean()
{
returnreadBoolean();
}
/**
* Same as readLong()
*/publiclongnextLong()
{
returnreadLong();
}
/**
* @return an integer from user
*/publicintreadInt()
{
try
{
returnInteger.valueOf(readLine());
}catch(NumberFormatExceptionexc)
{
thrownewInputMismatchException(exc.getMessage());
}
}
/**
* @return a long from user
*/publiclongreadLong()
{
try
{
returnLong.valueOf(readLine());
}catch(NumberFormatExceptionexc)
{
thrownewInputMismatchException(exc.getMessage());
}
}
/**
* @return a boolean from user, assuming anything starting with a y is yes
*/publicbooleanreadBoolean()
{
returnreadBoolean("Y", true);
}
/**
* This is not case sensitive.
* @return a boolean from user
* @param str the string that the response needs to be true
* @param start if the string has to start with the string or be completely that string
*/publicbooleanreadBoolean(Stringstr, booleanstart)
{
if(start)
{
returnreadLine().toLowerCase().startsWith(str.toLowerCase());
}else
{
returnreadLine().equalsIgnoreCase(str);
}
}
/**
* Same as <code>readBoolean(String str, boolean str)</code>
*/publicbooleannextBoolean(Stringstr, booleanstart)
{
returnreadBoolean(str, start);
}
@OverridepublicvoidactionPerformed(ActionEventevent)
{
str = field.getText();
field.setText("");
}
}
/**
* Like thread.sleep but does not throw exceptions. Use with caution
* @param ms the time in ms
*/publicstaticvoiddelay(longms)
{
try
{
Thread.sleep(ms);
}catch(InterruptedExceptionexc)
{
}
}
}
Special syntax:
To highlight a line (yellow background), prefix it with '@@'
To indicate that a line should be removed (red background), prefix it with '-'
To indicate that a line should be added (green background), prefix it with '+'
To post multiple snippets, seperate them by '~~~~'