/*
 * Created on Nov 3, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package de.tuberlin.polymake.common;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * @author thilosch
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SocketFrame extends JFrame implements ActionListener {

	protected JTextArea receivedText = new JTextArea(30,30);
	protected JTextArea sendText = new JTextArea(30,30);
	protected SelectionKey readKey;
	protected SelectionKey writeKey;
	protected SocketThread socketThread;
	
	public SocketFrame(String title, int port) {
		super(title);
		
		Container contentPanel = getContentPane();
		contentPanel.setLayout(new GridLayout(1,2));
		
		JPanel receivedPanel = new JPanel();
		receivedPanel.setLayout(new BorderLayout());
		receivedPanel.add(new JScrollPane(receivedText),BorderLayout.CENTER);
		
		socketThread = new SocketThread(port,receivedText);
		socketThread.start();
		
		JPanel sendPanel = new JPanel(new BorderLayout());
		JButton sendButton = new JButton("Send");
		sendButton.addActionListener(this);
		sendPanel.add(new JScrollPane(sendText),BorderLayout.CENTER);
		sendPanel.add(sendButton,BorderLayout.SOUTH);
		
		contentPanel.add(receivedPanel);
		contentPanel.add(sendPanel);
		setBounds(10,10,400,200);
		pack();
		setVisible(true);
		
	}
	
	public void actionPerformed(ActionEvent e) {
		try {
			SocketChannel sChannel = socketThread.getSocketChannel();
			BufferedWriter channelWriter = new BufferedWriter(Channels.newWriter(sChannel,"ISO-8859-1"));
			channelWriter.write(sendText.getText());
			channelWriter.flush();
		} catch (IOException ex) {
			System.err.println(ex.getMessage());
			ex.printStackTrace(System.err);
		}
	}

}


syntax highlighted by Code2HTML, v. 0.9.1