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

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
18 [java 인공지능] Spring AI 로 ChatGPT API 만들기 졸리운_곰 2024.12.30 214
17 [java 인공지능] 오라클, 자바 머신러닝 라이브러리 ‘트리뷰오’ 오픈소스로 공개 졸리운_곰 2023.08.27 296
16 [java 인공지능] 자바를 위한 머신 러닝 라이브러리 졸리운_곰 2023.08.27 360
15 [Java 인공지능] 오라클, 자바 머신러닝 라이브러리 ‘트리뷰오’ 오픈소스로 공개 file 졸리운_곰 2023.08.13 358
14 [java 인공지능] [java] 라이프 게임 (life game) file 졸리운_곰 2021.10.19 337
13 How to use Weka in your Java code 졸리운_곰 2020.02.01 307
12 weka and java eclipse example : A Simple Machine Learning Example in Java file 졸리운_곰 2020.01.31 362
11 머신러닝? weka file 졸리운_곰 2020.01.31 357
10 [Weka] Weka를 이용한 Iris 데이터 머신러닝 file 졸리운_곰 2020.01.30 363
9 [강좌] WEKA 사용법 (간단한 분류, 의사결정트리 분석 설명) file 졸리운_곰 2020.01.30 343
8 [JESS] Jess , 이클립스 연동 file 졸리운_곰 2019.12.22 215
7 Jess 간단한 문법 요약 졸리운_곰 2019.12.22 277
6 Jess 6.1 다운로드 friedman-hill_src_1_jess_se file 졸리운_곰 2019.12.22 184
5 java artificial intelligence Rule Engine Jess Working Memory 졸리운_곰 2019.12.22 300
4 Defining Functions in Jess 졸리운_곰 2019.12.22 389
3 Jess Language Basics 졸리운_곰 2019.12.22 272
2 Embedding Jess in a Java Application 졸리운_곰 2019.12.22 298
1 다섯개의 탑 자바로 머신러닝 라이브러리 Top 5 machine learning libraries for Java file 졸리운_곰 2017.08.22 388
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED