336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Java SocketServer control Image, DBConnect, String




package com.tistory.tansanc;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.imageio.ImageIO;

class DBConnect {
	ResultSet rs = null;
	Connection conn = null;
	Statement stmt = null;
	public DBConnect() {
		try {
			String url = "jdbc:sqlserver://192.168.10.17:1433;DatabaseName=MSSQLSERVER";
			
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(url, "sa", "1234");
			stmt = conn.createStatement();
			

		} catch (Exception e) {

		}
	}

	public void finalize() {
		try {
			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {

		}
	}
}

class PerClientThread extends Thread {
	Socket s;
	static ArrayList socketArray = new ArrayList();
	static DBConnect dbc;
	
	public PerClientThread()
	{
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub

		socketArray.add(s);
		BufferedReader br;

		
		try {
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			String temp;
			while ((temp = br.readLine()) != null) {
				// DB Query
				if (temp.startsWith("select")) {
					
					try {
						dbc.rs = dbc.stmt.executeQuery("SELECT * FROM [dbo].[TESTDB]");

						while (dbc.rs.next()) {
							String field1 = dbc.rs.getString("Date");
							String field2 = dbc.rs.getString("FileName");
							System.out.println(field1);
							System.out.println(field2);

							java.sql.Blob blb = dbc.rs.getBlob("Image");
							byte[] imagebytes = blb.getBytes(0, (int) blb.length());
							BufferedImage theImage = ImageIO.read(new ByteArrayInputStream(imagebytes));

						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					temp = "SQL:" + temp;
					System.out.println(temp);
				}
				// Arduino
				else if (temp.startsWith("insert"))
				{
					
				}
				// Arduino
				else if (temp.startsWith("image"))
				{

			        int size = Integer.parseInt(br.readLine());
			        
			        DataInputStream inputStream = new DataInputStream(s.getInputStream());
			        
			        byte[] imageAr = new byte[size];
			        inputStream.read(imageAr, 0, size);

			        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));

			        System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis());
			        ImageIO.write(image, "png", new File("C:\\test2.png"));


				}
				// Arduino
				else if (temp.startsWith("to"))
				{
					
				}
				System.out.print(s.getInetAddress() + " : ");
				System.out.println(temp);
				for (int i = 0; i < socketArray.size(); i++) {
					PrintWriter os = new PrintWriter(socketArray.get(i).getOutputStream(), true);
					os.print(s.getInetAddress() + " : ");
					os.println(temp);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.run();
	}
}

public class Server {
	public static void main(String[] args) throws Exception {
 
		System.out.println("Server Side");
		ServerSocket ss = new ServerSocket(33333);
		Socket s;
		while (true) {
			s = ss.accept();
			PerClientThread pct = new PerClientThread();
			pct.s = s;
			pct.dbc = new DBConnect();
			pct.start();
		}

	}
}










Client.java
package com.tistory.tansanc;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class MyFrame extends JFrame {
	public static JTextArea textArea;
	JTextField textField;
	PrintWriter out;
	Socket s;

	public MyFrame() {
		textArea = new JTextArea();
		textField = new JTextField();
		add(BorderLayout.CENTER, textArea);
		add(BorderLayout.SOUTH, textField);
		textField.addActionListener(new FieldListener());
		setSize(300, 200);
		setTitle("채팅프로그램 Client");
		setVisible(true);
		// GUI를 설계한다.
	}

	class FieldListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if (textField.getText().compareTo("image") == 0) {

				BufferedImage image;
				ByteArrayOutputStream byteArrayOutputStream = null;
				DataOutputStream os = null;
				try {
					image = ImageIO.read(new File("C:\\test.png"));
					byteArrayOutputStream = new ByteArrayOutputStream();
					ImageIO.write(image, "png", byteArrayOutputStream);
					os = new DataOutputStream(s.getOutputStream());
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				try {
					int size = byteArrayOutputStream.size();
					out.println("image");
					out.println(size);
					os.write(byteArrayOutputStream.toByteArray());
					os.flush();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			} else {
				out.println(textField.getText());
				textField.setText("");
			}
			// 메세지 보내기
		}
	}
}

class SendThread extends Thread {
	PrintWriter out;

	public SendThread(PrintWriter out) {
		this.out = out;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
	}
}

class RecvThread extends Thread {
	BufferedReader in;

	public RecvThread(BufferedReader in) {
		this.in = in;
	}

	@Override
	public void run() {
		String temp;
		try {
			while ((temp = in.readLine()) != null) {

				MyFrame.textArea.setText(MyFrame.textArea.getText() + "\n" + temp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ClientModule {
	MyFrame mFrame;
	SendThread mSendThread;
	RecvThread mRecvThread;
	Socket s;

	// 서버에 패킷을 보내는 Thread
	// 서버로부터 패킷을 받는 Thread
	public ClientModule() // 준비
	{

		try {
			s = new Socket("192.168.10.17", 33333);
			PrintWriter out = new PrintWriter(s.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			mFrame = new MyFrame(); // GUI 객체
			mFrame.s = s;
			mFrame.out = out;
			mSendThread = new SendThread(out);
			mRecvThread = new RecvThread(in);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	void start() // 시작
	{
		mSendThread.start();
		mRecvThread.start();
	}
}

public class Client {
	public static void main(String[] args) {
		ClientModule cm = new ClientModule();
		// 초기화 작업
		cm.start();
		// Thread.start();
	}
}





Java JNetPcap Library Packet Capture

Programming/JNetPcap 2016. 9. 20. 13:46 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Java JNetPcap Library Packet Capture 


pcap File




테스트 환경 : Win7 64bit, Eclipse, Java 1.8



이클립스와


자바는 설치되어있다고 가정합니다.





JNetPcap 라이브러리 다운로드


http://jnetpcap.com/download



저는 x84_64



압축을 풀면





jnetpcap.jar, jnetpcap.dll



두 개의 파일이 보입니다.



1. jnetpcap.jar 은 Eclipse 프로젝트에서 참조 할 수 있도록






Package Explorer > Properties > Java Build Path > Libraries > Add JARs 나 Add External JARs 로 추가하여 줍니다.



다운받은 경로보다는


해당 프로젝트 Eclipse Workspace 내에 두는것을 추천합니다.




한글 경로 때문에 안되는 경우도 있습니다,



2. jnetpcap.dll





C:\Windows\System32 경로에 jnetpcap.dll 파일을 복사하여 줍니다.









이제 설정은 끝났습니다.




테스트 코드는 다음과 같습니다.










import java.io.File;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.jnetpcap.ByteBufferHandler;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapDumper;
import org.jnetpcap.PcapHeader;
import org.jnetpcap.PcapIf;

public class Test1 {
	public static void main(String[] args) {
		// pcap.loop(x, dumpHandler, dumper); x 개 패킷을
		// String ofile = "tmp-capture-file.cap"; tmp-capture-file.cap 파일로 저장


		List alldevs = new ArrayList(); // Will be filled with
														// NICs
		StringBuilder errbuf = new StringBuilder(); // For any error msgs

		/***************************************************************************
		 * First get a list of devices on this system
		 **************************************************************************/
		int r = Pcap.findAllDevs(alldevs, errbuf);
		if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
			System.err.printf("Can't read list of devices, error is %s\n", errbuf.toString());
			return;
		}
		PcapIf device = alldevs.get(0); // We know we have atleast 1 device

		/***************************************************************************
		 * Second we open up the selected device
		 **************************************************************************/
		int snaplen = 64 * 1024; // Capture all packets, no trucation
		int flags = Pcap.MODE_PROMISCUOUS; // capture all packets
		int timeout = 10 * 1000; // 10 seconds in millis
		Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);
		if (pcap == null) {
			System.err.printf("Error while opening device for capture: %s\n", errbuf.toString());
			return;
		}

		/***************************************************************************
		 * Third we create a PcapDumper and associate it with the pcap capture
		 ***************************************************************************/
		String ofile = "tmp-capture-file.cap";
		PcapDumper dumper = pcap.dumpOpen(ofile); // output file

		/***************************************************************************
		 * Fouth we create a packet handler which receives packets and tells the
		 * dumper to write those packets to its output file
		 **************************************************************************/
		ByteBufferHandler dumpHandler = new ByteBufferHandler() {

			public void nextPacket(PcapHeader arg0, ByteBuffer arg1, PcapDumper arg2) {
				// TODO Auto-generated method stub
				dumper.dump(arg0, arg1);
			}
		};

		/***************************************************************************
		 * Fifth we enter the loop and tell it to capture 10 packets. We pass in
		 * the dumper created in step 3
		 **************************************************************************/
		pcap.loop(10, dumpHandler, dumper);

		File file = new File(ofile);
		System.out.printf("%s file has %d bytes in it!\n", ofile, file.length());

		/***************************************************************************
		 * Last thing to do is close the dumper and pcap handles
		 **************************************************************************/
		dumper.close(); // Won't be able to delete without explicit close
		pcap.close();

		if (file.exists()) {
			// file.delete(); // Cleanup
		}	
	}
}


'Programming > JNetPcap' 카테고리의 다른 글

Java JNetPcap Library Packet Analytics  (0) 2016.09.20

Java Chatting Server, Client

Programming/JAVA,JSP 2014. 7. 12. 16:18 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

 

 

 

JavaChattingClient.zip

 

JavaChattingServer.zip

 

'Programming > JAVA,JSP' 카테고리의 다른 글

mysql table datetime tip  (0) 2014.10.20
JSP, MYSQL, ECLIPSE 연동하기  (0) 2014.10.12
JScrollPane , ScrollPane 차이점  (0) 2014.07.12
Java ScrollPane 활용  (0) 2014.07.12
java  (0) 2014.07.12

JAVA 채팅 소스 -1 Client 쪽

Programming/JAVA,JSP 2014. 7. 12. 14:50 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Scanner;

 

class RecvThread extends Thread {

     Socket s;

 

     public RecvThread(Socket s) {

          this.s = s;

     }

 

     @Override

     public void run() {

          // 받는 부분

          BufferedReader is;

          try {

              is = new BufferedReader(new InputStreamReader(s.getInputStream()));

              String recvMsg;

              while ((recvMsg = is.readLine()) != null) {

                   System.out.println(recvMsg);

              }

          } catch (IOException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

          }

     }

}

 

class SendThread extends Thread {

     Socket s;

 

     public SendThread(Socket s) {

          this.s = s;

     }

 

     @Override

     public void run() {

          PrintWriter os;

          try {

              os = new PrintWriter(s.getOutputStream(), true);

              // 보내는 부분

              Scanner sc = new Scanner(System.in);

              while (true) {

                   String msg = sc.next();

                   os.println(msg);

              }

          } catch (IOException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

          }

     }

 

}

 

public class ClientTest {

     public static void main(String[] args) {

          try {

              Socket s = new Socket("115.20.247.142", 4000);

              SendThread st = new SendThread(s);

              RecvThread rt = new RecvThread(s);

          } catch (UnknownHostException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

          } catch (IOException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

          }

     }

}

 

 

'Programming > JAVA,JSP' 카테고리의 다른 글

Java ScrollPane 활용  (0) 2014.07.12
java  (0) 2014.07.12
Java 선택 정렬 알고리즘 구현  (0) 2014.06.14
String to int, int to String  (0) 2014.06.07
이클립스 라인넘버 표시  (1) 2014.03.07

JAVA 계산기 프로그램 부분완성

Programming/JAVA,JSP 2013. 8. 16. 14:25 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
package com.tansanc.tistory;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

class Cal extends JFrame
{

	private JTextField t1;

	private JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;

	JButton pl, mi, mu, di, cal, c;

	String x, y;

	public Cal()
	{

		setSize(285, 350);

		setDefaultCloseOperation(EXIT_ON_CLOSE);

		setTitle("Calculator");

		JPanel p = new JPanel();

		p.setLayout(null);

		t1 = new JTextField(10);

		p.add(t1);

		b1 = new JButton("1");

		p.add(b1);

		b1.addActionListener(new Number());

		b2 = new JButton("2");

		p.add(b2);

		b2.addActionListener(new Number());

		b3 = new JButton("3");

		p.add(b3);

		b3.addActionListener(new Number());

		b4 = new JButton("4");

		p.add(b4);

		b4.addActionListener(new Number());

		b5 = new JButton("5");

		p.add(b5);

		b5.addActionListener(new Number());

		b6 = new JButton("6");

		p.add(b6);

		b6.addActionListener(new Number());

		b7 = new JButton("7");

		p.add(b7);

		b7.addActionListener(new Number());

		b8 = new JButton("8");

		p.add(b8);

		b8.addActionListener(new Number());

		b9 = new JButton("9");

		p.add(b9);

		b9.addActionListener(new Number());

		b0 = new JButton("0");

		p.add(b0);

		b0.addActionListener(new Number());

		pl = new JButton("+");

		p.add(pl);

		pl.addActionListener(new Number());

		mi = new JButton("-");

		p.add(mi);

		mi.addActionListener(new Number());

		mu = new JButton("*");

		p.add(mu);

		mu.addActionListener(new Number());

		di = new JButton("/");

		p.add(di);

		di.addActionListener(new Number());

		cal = new JButton("=");

		p.add(cal);

		cal.addActionListener(new Number());

		c = new JButton("C");

		p.add(c);

		c.addActionListener(new Number());

		t1.setBounds(10, 10, 245, 80);

		b1.setBounds(10, 105, 45, 45);

		b2.setBounds(60, 105, 45, 45);

		b3.setBounds(110, 105, 45, 45);

		b4.setBounds(10, 155, 45, 45);

		b5.setBounds(60, 155, 45, 45);

		b6.setBounds(110, 155, 45, 45);

		b7.setBounds(10, 205, 45, 45);

		b8.setBounds(60, 205, 45, 45);

		b9.setBounds(110, 205, 45, 45);

		b0.setBounds(60, 255, 45, 45);

		pl.setBounds(160, 105, 45, 45);

		mi.setBounds(160, 155, 45, 45);

		mu.setBounds(160, 205, 45, 45);

		di.setBounds(160, 255, 45, 45);

		c.setBounds(110, 255, 45, 45);

		cal.setBounds(210, 105, 45, 195);

		add(p);

		setVisible(true);

	}

	String operand1;
	String operator;
	private class Number implements ActionListener
	{

		public void actionPerformed(ActionEvent e)
		{
			if( e.getSource() == b1)
			{
				t1.setText(t1.getText() + "1");
			}
			else if( e.getSource() == b2)
			{
				t1.setText(t1.getText() + "2");
			}
			else if( e.getSource() == pl)
			{
				operand1 = t1.getText();
				operator = "+";
				t1.setText("");
			}
			else if( e.getSource() == cal)
			{
				if(operator == "+")
				{
					t1.setText("" + ( Integer.parseInt(operand1) + Integer.parseInt(t1.getText())) );
				}
			}
		}
	}

}

public class CardTest
{

	public static void main(String[] args)
	{

		Cal Cals = new Cal();

	}

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 채팅 프로그램 소스  (0) 2013.08.23
JAVA 채팅 클라이언트  (0) 2013.08.23
JAVA 계산기 레이아웃  (0) 2013.08.16
JAVA 타자연습 프로그램  (0) 2013.08.13
JAVA Console Token 구현  (0) 2013.08.07

JAVA 계산기 레이아웃

Programming/JAVA,JSP 2013. 8. 16. 13:30 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
package com.tansanc.tistory;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

class Cal extends JFrame
{

	private JTextField t1;

	private JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;

	JButton pl, mi, mu, di, cal, c;

	String x, y;

	public Cal()
	{

		setSize(285, 350);

		setDefaultCloseOperation(EXIT_ON_CLOSE);

		setTitle("Calculator");

		JPanel p = new JPanel();

		p.setLayout(null);

		t1 = new JTextField(10);

		p.add(t1);

		b1 = new JButton("1");

		p.add(b1);

		b1.addActionListener(new Number());

		b2 = new JButton("2");

		p.add(b2);

		b2.addActionListener(new Number());

		b3 = new JButton("3");

		p.add(b3);

		b3.addActionListener(new Number());

		b4 = new JButton("4");

		p.add(b4);

		b4.addActionListener(new Number());

		b5 = new JButton("5");

		p.add(b5);

		b5.addActionListener(new Number());

		b6 = new JButton("6");

		p.add(b6);

		b6.addActionListener(new Number());

		b7 = new JButton("7");

		p.add(b7);

		b7.addActionListener(new Number());

		b8 = new JButton("8");

		p.add(b8);

		b8.addActionListener(new Number());

		b9 = new JButton("9");

		p.add(b9);

		b9.addActionListener(new Number());

		b0 = new JButton("0");

		p.add(b0);

		b0.addActionListener(new Number());

		pl = new JButton("+");

		p.add(pl);

		pl.addActionListener(new Number());

		mi = new JButton("-");

		p.add(mi);

		mi.addActionListener(new Number());

		mu = new JButton("*");

		p.add(mu);

		mu.addActionListener(new Number());

		di = new JButton("/");

		p.add(di);

		di.addActionListener(new Number());

		cal = new JButton("=");

		p.add(cal);

		cal.addActionListener(new Number());

		c = new JButton("C");

		p.add(c);

		c.addActionListener(new Number());

		t1.setBounds(10, 10, 245, 80);

		b1.setBounds(10, 105, 45, 45);

		b2.setBounds(60, 105, 45, 45);

		b3.setBounds(110, 105, 45, 45);

		b4.setBounds(10, 155, 45, 45);

		b5.setBounds(60, 155, 45, 45);

		b6.setBounds(110, 155, 45, 45);

		b7.setBounds(10, 205, 45, 45);

		b8.setBounds(60, 205, 45, 45);

		b9.setBounds(110, 205, 45, 45);

		b0.setBounds(60, 255, 45, 45);

		pl.setBounds(160, 105, 45, 45);

		mi.setBounds(160, 155, 45, 45);

		mu.setBounds(160, 205, 45, 45);

		di.setBounds(160, 255, 45, 45);

		c.setBounds(110, 255, 45, 45);

		cal.setBounds(210, 105, 45, 195);

		add(p);

		setVisible(true);

	}

	private class Number implements ActionListener
	{

		public void actionPerformed(ActionEvent e)
		{

		}

	}

}

public class CardTest
{

	public static void main(String[] args)
	{

		Cal Cals = new Cal();

	}

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 채팅 클라이언트  (0) 2013.08.23
JAVA 계산기 프로그램 부분완성  (0) 2013.08.16
JAVA 타자연습 프로그램  (0) 2013.08.13
JAVA Console Token 구현  (0) 2013.08.07
JAVA 제네릭을 사용한 Store Class  (0) 2013.08.07

JAVA 타자연습 프로그램

Programming/JAVA,JSP 2013. 8. 13. 12:18 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
package com.tansanc.tistory;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

class MyFrame extends JFrame implements KeyListener
{
	JLabel staticText;
	JTextField inputText;
	JLabel resultText;
	long start;
	long end;
	String problemArray[] =
	{ "JAVA", "안녕하세요" };
	ArrayList problemList = new ArrayList();

	public MyFrame()
	{
		problemList.add("JAVA");
		problemList.add("안녕하세요");
		this.setSize(300, 200);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("이벤트 예제");
		staticText = new JLabel("Hello World");
		add(staticText, BorderLayout.NORTH);
		inputText = new JTextField("");
		add(inputText, BorderLayout.CENTER);
		resultText = new JLabel("Hello World");
		add(resultText, BorderLayout.SOUTH);

		inputText.addKeyListener(this);

		setVisible(true);
		start = System.currentTimeMillis();
	}

	@Override
	public void keyPressed(KeyEvent e)
	{
	}

	@Override
	public void keyReleased(KeyEvent e)
	{

	}

	@Override
	public void keyTyped(KeyEvent e)
	{
		if (staticText.getText().equals(inputText.getText()))
		{
			Random r = new Random();
			end = System.currentTimeMillis();
			resultText.setText("정답입니다. " + inputText.getText().length()
					/ ((end - start) / 1000.0 / 60.0));
			staticText.setText(problemList.get(r.nextInt(2)));
			inputText.setText("");
		}
	}
}

public class Test
{
	public static void main(String[] args)
	{
		MyFrame t = new MyFrame();
	}
}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 계산기 프로그램 부분완성  (0) 2013.08.16
JAVA 계산기 레이아웃  (0) 2013.08.16
JAVA Console Token 구현  (0) 2013.08.07
JAVA 제네릭을 사용한 Store Class  (0) 2013.08.07
JAVA DRAG 가능한 Component 만들기  (0) 2013.08.03

JAVA Console Token 구현

Programming/JAVA,JSP 2013. 8. 7. 13:37 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
public class Test
{
	public static void main(String[] args)
	{
		String text = "AAA BBB CCC DDD EEE FFF";
		int count = 0;

		for (int i = 0; i < text.length(); i++)
		{
			if (text.charAt(i) == ' ')
			{
				count++;
			} else
			{
			}
		}
		String[] textResult = new String[count + 1];

		int i, j, k;
		for (i = 0; i < text.length(); i++)
		{
			if (text.charAt(i) == ' ')
			{
				textResult[0] = text.substring(0, i);
				break;
			}
		}
		System.out.print(textResult[0]);
		int lastValue =	0;
		for (k = 1; i < text.length(); k++)
		{
			i = i + 1;
			j = i;
			for (; i < text.length(); i++)
			{
				if (text.charAt(i) == ' ')
				{
					System.out.print("\n");
					textResult[k] = text.substring(j, i);
					lastValue = i;
					break;
				}
			}
		}
		textResult[k-1] = text.substring(lastValue+1 , text.length() );		
		for( String s : textResult )
		{
			System.out.println(s);
		}
	}
}
시스템 라이브러리를 활용
public class Test
{
	public static void main(String[] args)
	{
		String text = "AAA BBB CCC DDD EEE FFF";
		
		StringTokenizer st = new StringTokenizer(text, " ");
		
		while(st.hasMoreTokens() )
		{
			System.out.println(st.nextToken());
		}
	}
}
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

class DraggableComponent extends JComponent

{

 

    /** If sets <b>TRUE</b> this component is draggable */

    private boolean draggable = true;

    /**

     * 2D Point representing the coordinate where mouse is, relative parent

     * container

     */

    protected Point anchorPoint;

    /** Default mouse cursor for dragging action */

    protected Cursor draggingCursor = Cursor

           .getPredefinedCursor(Cursor.HAND_CURSOR);

    /**

     * If sets <b>TRUE</b> when dragging component, it will be painted over each

     * other (z-Buffer change)

     */

    protected boolean overbearing = false;

 

    public DraggableComponent()

    {

        addDragListeners();

        setOpaque(true);

        setBackground(new Color(240, 240, 240));

    }

 

    /**

     * Add Mouse Motion Listener with drag function

     */

    private void addDragListeners()

    {

        /**

         * This handle is a reference to THIS because in next Mouse Adapter

         * "this" is not allowed

         */

        final DraggableComponent handle = this;

        addMouseMotionListener(new MouseAdapter()

        {

 

           @Override

           public void mouseMoved(MouseEvent e)

           {

               anchorPoint = e.getPoint();

           setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

           }

 

           @Override

           public void mouseDragged(MouseEvent e)

           {

               int anchorX = anchorPoint.x;

               int anchorY = anchorPoint.y;

 

               Point parentOnScreen = getParent().getLocationOnScreen();

               Point mouseOnScreen = e.getLocationOnScreen();

               Point position = new Point(mouseOnScreen.x - parentOnScreen.x

                       - anchorX, mouseOnScreen.y - parentOnScreen.y - anchorY);

               setLocation(position);

 

               // Change Z-Buffer if it is "overbearing"

               if (overbearing)

               {

                   getParent().setComponentZOrder(handle, 0);

                   repaint();

               }

           }

        });

    }

 

    @Override

    protected void paintComponent(Graphics g)

    {

        super.paintComponent(g);

        if (isOpaque())

        {

           g.setColor(getBackground());

           g.fillRect(0, 0, getWidth(), getHeight());

        }

    }

 

    private void removeDragListeners()

    {

        for (MouseMotionListener listener : this.getMouseMotionListeners())

        {

           removeMouseMotionListener(listener);

        }

        setCursor(Cursor.getDefaultCursor());

    }

}


http://www.codeproject.com/Articles/116088/Draggable-Components-in-Java-Swing

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA Console Token 구현  (0) 2013.08.07
JAVA 제네릭을 사용한 Store Class  (0) 2013.08.07
JAVA Swing 두개의 판넬을 겹치기  (0) 2013.08.03
JAVA JNI  (0) 2013.05.01
Eclipse Tips  (0) 2013.04.30