A simple Java console:

Disclaimer:
The use of this code is at your own risk.

Description:
This source code will make it possible to attach a Java console to your application.
This console will show all errors and other output made by your application.
It works by redirecting System.out and System.err to the textArea of the Console.

Purpose:
I wrote this because many applications do not have a Java console.
Also it's very easy to add a Console adding the code "new Console()" is all.
Presentation:
This version uses Swing components.
Which means you will need Java 1.1.5 or higher.

Performance:
It seems to work perfectly.

Source Code description:
I'll not explain everything in all details here.
The green lines are only there for demonstration purposes you should omit them.
<DOWNLOAD>

Lines 1 to 10: Java comments.
Lines 11 to 14: import statements.
Line 16: defines the Console class.
Lines 18 to 27: class variables.
Line 29 to 106: constructor.
Line 51 to 63: redirection of System.out.
Line 65 to 77: redirection of System.err.
Line 81 to 89: the two reader threads are started:
Line 91 to 105: just for demonstration purposes.
Line 108 to 125: Event Listener methods.
Line 127: synchronized run method, here the two reader threads do their work.
Lines 157 to 162: demonstration purpose, throws a NullPointer at the console after about 1 second.
Line 166 to 178: a custom ReadLine method.
Line 180 183: application main method.
 

1: //
2: // A simple Java Console for your application (Swing version)
3: // Requires Java 1.1.5 or higher
4: //
5: // Disclaimer the use of this source is at your own risk.
6: //
7: // Permission to use and distribute into your own applications
8: //
9: // RJHM van den Bergh , rvdb@comweb.nl
10:
11: import java.io.*;
12: import java.awt.*;
13: import java.awt.event.*;
14: import javax.swing.*;
15:
16: public class Console extends WindowAdapter implements WindowListener,  ActionListener, Runnable
17: {
18:	private JFrame frame;
19:	private JTextArea textArea;
20:	private Thread reader;
21:	private Thread reader2;
22:	private boolean quit;
23:
24:	private final PipedInputStream pin=new PipedInputStream();
25:	private final PipedInputStream pin2=new PipedInputStream();
26:
27:	Thread errorThrower; // just for testing (Throws an Exception at this Console
28:
29:	public Console()
30:	{
31:		// create all components and add them
32:		frame=new JFrame("Java Console");
33:		Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
34:		Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
35:		int x=(int)(frameSize.width/2);
36:		int y=(int)(frameSize.height/2);
37:		frame.setBounds(x,y,frameSize.width,frameSize.height);
38:
39:		textArea=new JTextArea();
40:		textArea.setEditable(false);
41:		JButton button=new JButton("clear");
42:
43:		frame.getContentPane().setLayout(new BorderLayout());
44:		frame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
45:		frame.getContentPane().add(button,BorderLayout.SOUTH);
46:		frame.setVisible(true);
47:
48:		frame.addWindowListener(this);
49:		button.addActionListener(this);
50:
51:		try
52:		{
53:			PipedOutputStream pout=new PipedOutputStream(this.pin);
54:			System.setOut(new PrintStream(pout,true));
55:		}
56:		catch (java.io.IOException io)
57:		{
58:			textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
59:		}
60:		catch (SecurityException se)
61:		{
62:			textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
63:        	}
64:
65:		try
66:		{
67:			PipedOutputStream pout2=new PipedOutputStream(this.pin2);
68:			System.setErr(new PrintStream(pout2,true));
69:		}
70:		catch (java.io.IOException io)
71:		{
72:			textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
73:		}
74:		catch (SecurityException se)
75:		{
76:			textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
77:		}
78:
79:		quit=false; // signals the Threads that they should exit
80:
81:		// Starting two separate threads to read from the PipedInputStreams
82:		//
83:		reader=new Thread(this);
84:		reader.setDaemon(true);
85:		reader.start();
86:		//
87:		reader2=new Thread(this);
88:		reader2.setDaemon(true);
89:		reader2.start();
90:
91:		// testing part
92:		// you may omit this part for your application
93:		//
94:		System.out.println("Hello World 2");
95:		System.out.println("All fonts available to Graphic2D:\n");
96:		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
97:		String[] fontNames=ge.getAvailableFontFamilyNames();
98:		for(int n=0;n<fontNames.length;n++)  System.out.println(fontNames[n]);
99:		// Testing part: simple an error thrown anywhere in this JVM will be printed on the Console
100:		// We do it with a seperate Thread becasue we don't wan't to break a Thread used by the Console.
101:
102:		System.out.println("\nLets throw an error on this console");
103:		errorThrower=new Thread(this);
104:		errorThrower.setDaemon(true);
105:		errorThrower.start();
106:	}
107:
108:	public synchronized void windowClosed(WindowEvent evt)
109:	{
110:		quit=true;
111:		this.notifyAll(); // stop all threads
112:		try { reader.join(1000);pin.close();   } catch (Exception e){}
113:		try { reader2.join(1000);pin2.close(); } catch (Exception e){}
114:		System.exit(0);
115:	}
116:	public synchronized void windowClosing(WindowEvent evt)
117:	{
118:		frame.setVisible(false); // default behaviour of JFrame
119:		frame.dispose();
120:	}
121:
122:	public synchronized void actionPerformed(ActionEvent evt)
123:	{
124:		textArea.setText("");
125:	}
126:
127:	public synchronized void run()
128:	{
129:		try
129:		{
130:			while (Thread.currentThread()==reader)
131:			{
132:				try { this.wait(100);}catch(InterruptedException ie) {}
133:				if (pin.available()!=0)
134:				{
135:					String input=this.readLine(pin);
136:					textArea.append(input);
137:				}
138:				if (quit) return;
139:			}
140:
141:			while (Thread.currentThread()==reader2)
142:			{
143:				try { this.wait(100);}catch(InterruptedException ie) {}
144:				if (pin2.available()!=0)
145:				{
146:					String input=this.readLine(pin2);
147:					textArea.append(input);
148:				}
149:				if (quit) return;
150:			}
151:		} catch (Exception e)
152:		{
153:			textArea.append("\nConsole reports an Internal error.");
154:			textArea.append("The error is: "+e);
155:		}
156:
157:		// just for testing (Throw a Nullpointer after 1 second)
158:		if (Thread.currentThread()==errorThrower)
159:		{
160:			try { this.wait(1000); }catch(InterruptedException ie){}
161:			throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
162:		}
163:
164:	}
165:
166:	public synchronized String readLine(PipedInputStream in) throws IOException
167:	{
168:		String input="";
169:		do
170:		{
171:			int available=in.available();
172:			if (available==0) break;
173:			byte b[]=new byte[available];
174:			in.read(b);
175:			input=input+new String(b,0,b.length);
176:		}while( !input.endsWith("\n") &&  !input.endsWith("\r\n") && !quit);
177:		return input;
178:	}
179:
180:	public static void main(String[] arg)
181:	{
182:		new Console(); // create console with not reference
183:	}
184:}

 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

[출처] http://www.comweb.nl/java/Console/Console.html

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
22 Command Prompt Shell Interface in Java 졸리운_곰 2015.07.12 310
21 java console 졸리운_곰 2015.07.05 223
20 Java Console and File Input/Output Cheat Sheet 졸리운_곰 2015.07.05 249
19 Demonstrates standard I/O redirection 졸리운_곰 2015.07.05 232
18 Java로 외부 프로그램 실행 ( ProcessBuilder 사용) 졸리운_곰 2015.03.17 1175
17 Java Clipboard 자바 클립보드 복사/붙여넣기 졸리운_곰 2015.03.17 2214
16 Java Inner class 자바 중첩(내부)클래스 졸리운_곰 2015.03.03 887
15 IzPack으로 GUI 설치 프로그램 만들기 file 졸리운_곰 2015.02.15 638
14 [Java],[AWT],[Layout],[AWT Layout], file 졸리운_곰 2015.02.13 370
13 [Java],[AWT],[SWING], Java GUI file 졸리운_곰 2015.02.13 922
12 [Java][AWT 개요] file 졸리운_곰 2015.02.13 464
11 javac 로 컴파일 시 유니코드(utf-8) 한글 소스 코드 컴파일 문제 졸리운_곰 2015.02.02 1134
10 파일 존재 여부 판단, 디렉토리 있는지 확인 함수; File Directory Exist 졸리운_곰 2014.03.03 1215
9 Java Static 변수 졸리운_곰 2014.01.28 1102
8 Properties 클래스 사용하기. 졸리운_곰 2014.01.28 1026
7 Java => Thread 졸리운_곰 2014.01.28 835
6 Java 세마포어(Semaphore) 가을의 곰을... 2013.12.11 2517
5 Java Thread 제어 (Thread Pool) 가을의 곰을... 2013.12.11 975
4 Java Delay (지연실행) 루틴 가을의 곰을... 2013.11.20 1364
3 Java Runtime시 Memory monitoring 가을의 곰을... 2013.11.19 875
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED