Java-Gaming.org Hi !
Featured games (81)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (576)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
  JavaGaming.org - Pastebin



Author: Tjstretchalot (posted 2012-10-02 15:44:15, viewed 203 times)

1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212   213   214   215   216   217   218   219   220   221   222   223   224   225   226   227   228   229   230   231   232   233   234   235   236   237   238   239   240   241   242   243   244   245   246   247   248   249   250   251   252   253   254   255   256   257   258   259   260   261   262   263   264   265   266   267   268   269   270   271   272   273   274   275   276   277   278   279   280   281   282   283   284   285   286   287   288   289   290   291   292   293   294   295   296   297   298   299   300   301   302   303   304   305   306   307   308   309   310   311   312   313   314   315   316   317   318   319   320   321   322   323   324   325   326   327   328   329   330   331   332   333   334   335   336   337   338   339   340   341   342   343   344   345   346   347   348   349   350   351   352   353   354   355   356   357   358   359   360   361   362   363   364   365   366   367   368   369   370   371   372   373   374   375   376   377   378   379   380   381   382   383   384   385   386   387   388   389   390   391   392   393   394   395   396   397   398   399   400   401   402   403   404   405   406   407   408   409   410   411   412   413   414   415   416   417   418   419   420   421   422   423   424   425   426   427   428   429   430   431   432   433   434   435   436   437   438   439   440   441   442   443   444   445   446   447   448   449   450   451   452   453   454   455   456   457   458   459   460   461   462   463   464   465   466   467   468   469   470   471   472   473   474   475   476   477   478   479   480   481   482   483   484   485   486   487   488   489   490   491   492   493   494   495   496   497   498  
package me.timothy.consolegui;

import java.util.Scanner;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.PrintStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.InputMismatchException;
import javax.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
 */
public class ConsoleGUI extends JFrame
{
  protected static volatile boolean saveRun = false;
  /**
   * The ConsoleGUI
   */
  protected static ConsoleGUI gui;
  /**
   * The Scanner being used
   */
  protected TAScanner scanner;
  /**
   * The stream being used
   */
  protected TAPrintStream stream;
  /**
   * The main text area, where calls to System.out go
   */
  private JTextArea txtArea;
  /**
   * Where the user enters information
   */
  private JTextField userField;
  /**
   * The submit button, not actually necessary
   */
  private JButton submit;
  /**
   * The JScrollPane wrapper
   */
  private JScrollPane sPane;
  /**
   * Creates the GUI
   */
  protected ConsoleGUI()
  {
    setSize(350, 350);
    setTitle("Console GUI");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());
    
    txtArea = new JTextArea();
    txtArea.setEditable(false);
    sPane = new JScrollPane(txtArea);
    add(sPane, BorderLayout.CENTER);
    userField = new JTextField();
    userField.setEditable(false);
    userField.setActionCommand("submit");
    submit = new JButton("Submit");
    submit.setActionCommand("submit");
    JPanel bot = new JPanel();
    bot.setLayout(new BorderLayout());
    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
   */
  public static void toGUI()
  {
    try
    {
      if(!SwingUtilities.isEventDispatchThread())
      {
        SwingUtilities.invokeAndWait(new Runnable() {
          @Override
          public void run()
          {
            gui = new ConsoleGUI();
            gui.stream = gui.createPrintStream();
            gui.setVisible(true);
          }
        });
      }else
      {
        gui = new ConsoleGUI();
        gui.stream = gui.createPrintStream();
        gui.setVisible(true);
      }
    }catch(Exception exc)
    {
      handleException("Failed to convert to gui", exc, saveRun);
    }
    
  }
  
  public static void clear() {
   // TODO Auto-generated method stub
   gui.txtArea.setText("");
  }
  
  public static void setConsoleTitle(String tit)
  {
    gui.setTitle(tit);
  }
  /**
   * Creates a TAPrintStream based on the text area
   */
  protected TAPrintStream createPrintStream()
  {
    return new TAPrintStream(txtArea);
  }
  /**
   * @return a new TAScanner
   */
  private TAScanner createScanner()
  {
    return new TAScanner(userField, submit);
  }
  /**
   * @return the print stream
   */
  public static TAPrintStream getStream()
  {
    return gui.stream;
  }
  /**
   * Sets if it is saving the text, by default false
   * @param b if it should save text
   */
  public static void setSaveText(boolean b)
  {
    saveRun = b;
  }
  /**
   * @return the scanner to use.  Has most methods of Scanner 
   * @throws NullPointerException if called before toGUI
   */
  public static TAScanner getScanner()
  {
    if(gui.scanner == null)
      gui.scanner = gui.createScanner();
    return gui.scanner;
  }
  
  public static ConsoleGUI getGUI()
  {
    return gui;
  }
  
  /**
   * 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.
   */
  public static void handleException(String msg, Throwable exc, boolean saveToFile)
  {
    try
    {
      TAPrintStream out = getStream();
      
      out.print(msg);
      out.println(" - " + exc.getClass().getSimpleName());
      StackTraceElement[] elements = exc.getStackTrace();
      
      for(StackTraceElement t : elements)
      {
        out.println(t);
      }
    }catch(SecurityException exce)
    {
      setSaveText(false);
    }catch(Exception exce)
    {
      // Not cool.
      exce.printStackTrace();
      
      System.err.println(msg);
    }
  }
  /**
   * For testing purposes, shows an example usage of this program
   */
  public static void main(String[] args)
  {
    ConsoleGUI.toGUI();
    ConsoleGUI.setSaveText(true);
    TAScanner scanner = ConsoleGUI.getScanner();
    TAPrintStream out = ConsoleGUI.getStream();
    out.println("Type a string");
    String str = scanner.nextLine();
    out.println("Type an int");
    int i = scanner.nextInt();
    out.println("You typed "+str+" and "+i);
    out.println("Say something starting with y");
    boolean b = 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();
    RuntimeException exc = new RuntimeException();
    handleException("Test", exc, saveRun);
    //for(int i = 0; i < 50; i++) { out.println("Purposeful Spam"); }
  }
  @Override
  public String toString()
  {
    return "initialized";
  }
  /**
   * Short for TextAreaPrintStream, this stream sends all messages
   * to the GUI instead of the regular System.out
   * 
   * @author Timothy Moore
   */
  public class TAPrintStream
  {
    private JTextArea txtArea;
    private BufferedWriter fileWriter;
    private final File file = new File("lastRun.txt");
    /**
     * Create a print stream to the specified text area
     */
    private TAPrintStream(JTextArea txtArea)
    {
      this.txtArea = txtArea;
      DefaultCaret caret = (DefaultCaret)txtArea.getCaret();
      caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    }
    
    public void print(Object msg)
    {
      txtArea.append(msg.toString());
      if(saveRun)
      {
        if(fileWriter == null)
        {
          //System.out.println("Creating file writer");
          try
          {
            
            file.createNewFile();
            fileWriter = new BufferedWriter(new FileWriter(file));
          }catch(Exception exc)
          {
            saveRun = false;
            handleException("Failed to create file", exc, false);
          }
          Runtime.getRuntime().addShutdownHook(new Thread()
                                                   {
            @Override
            public void run()
            {
              try
              {
                fileWriter.close();
              }catch(IOException e)
              {
                handleException("Failed to close writer", e, false);
              }
            }
          });
        }
        //System.out.println("Saving to filewriter");
        try
        {
          String[] msgs = msg.toString().split("/n");
          for(String s : msgs)
          {
            fileWriter.write(s);
            fileWriter.newLine();
          }
        }catch(Exception e)
        {
          handleException("Failed to write to file", e, false);
          saveRun = false;
        }
      }
      
    }
    public void print(boolean msg)
    {
      print(new StringBuilder().append(msg));
    }
    public void print(int msg)
    {
      print(new StringBuilder().append(msg));
    }
    public void print(long msg)
    {
      print(new StringBuilder().append(msg));
    }
    public void print(double msg)
    {
      print(new StringBuilder().append(msg));
    }
    
    public void println()
    {
      print("\n");
    }
    
    public void println(Object msg)
    {
      print(new StringBuilder().append(msg).append("\n"));
    }
    public void println(int msg)
    {
      println(new StringBuilder().append(msg));
    }
    public void println(long msg)
    {
      println(new StringBuilder().append(msg));
    }
    public void println(boolean msg)
    {
      println(new StringBuilder().append(msg));
    }
    public void println(double msg)
    {
      println(new StringBuilder().append(msg));
    }
  }
  /**
   * Short for TextAreaScanner, this Scanner retrieves messages
   * from the GUI instead of the regular new Scanner(System.in)
   * 
   * @author Timothy Moore
   */
  public class TAScanner implements ActionListener
  {
    private String str;
    private JTextField field;
    private JButton but;
    /**
     * Creates a scanner based on the specified text field
     * and button
     */
    private TAScanner(JTextField field, JButton but)
    {
      this.field = field;
      this.but = but;
      field.addActionListener(this);
      but.addActionListener(this);
    }
    /**
     * Reads one string
     */
    public String readLine()
    {
      field.setEditable(true);
      str = null;
      while(str == null)
      {
        delay(100);
      }
      ConsoleGUI.getStream().println(new StringBuilder("> ").append(str));
      return str;
    }
    /**
     * Same as readLine()
     */
    public String nextLine()
    {
      return readLine();
    }
    /**
     * Same as readInt()
     */
    public int nextInt()
    {
      return readInt();
    }
    /**
     * Same as readBoolean()
     */
    public boolean nextBoolean()
    {
      return readBoolean();
    }
    /**
     * Same as readLong()
     */
    public long nextLong()
    {
      return readLong();
    }
    /**
     * @return an integer from user
     */
    public int readInt()
    {
      try
      {
        return Integer.valueOf(readLine());
      }catch(NumberFormatException exc)
      {
        throw new InputMismatchException(exc.getMessage());
      }
    }
    /**
     * @return a long from user
     */
    public long readLong()
    {
      try
      {
        return Long.valueOf(readLine());
      }catch(NumberFormatException exc)
      {
        throw new InputMismatchException(exc.getMessage());
      }
    }
    /**
     * @return a boolean from user, assuming anything starting with a y is yes
     */
    public boolean readBoolean()
    {
      return readBoolean("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
     */
    public boolean readBoolean(String str, boolean start)
    {
      if(start)
      {
        return readLine().toLowerCase().startsWith(str.toLowerCase());
      }else
      {
        return readLine().equalsIgnoreCase(str);
      }
    }
    /**
     * Same as <code>readBoolean(String str, boolean str)</code>
     */
    public boolean nextBoolean(String str, boolean start)
    {
      return readBoolean(str, start);
    }
    @Override
    public void actionPerformed(ActionEvent event)
    {
      str = field.getText();
      field.setText("");
    }
  }
  /**
   * Like thread.sleep but does not throw exceptions. Use with caution
   * @param ms the time in ms
   */
  public static void delay(long ms)
  {
    try
    {
      Thread.sleep(ms);
    }catch(InterruptedException exc)
    {
      
    }
  }
}





Dump your java code here :



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 '~~~~'
  EOF
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Longarmx (38 views)
2014-10-17 03:59:02

Norakomi (29 views)
2014-10-16 15:22:06

Norakomi (24 views)
2014-10-16 15:20:20

lcass (28 views)
2014-10-15 16:18:58

TehJavaDev (56 views)
2014-10-14 00:39:48

TehJavaDev (55 views)
2014-10-14 00:35:47

TehJavaDev (46 views)
2014-10-14 00:32:37

BurntPizza (64 views)
2014-10-11 23:24:42

BurntPizza (36 views)
2014-10-11 23:10:45

BurntPizza (78 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!