Java Programming Tutorial for Intermediate – 1 / 59 – Common String Methods
.
public class ForIf {
public static void main (String[ ] args) {
String[ ] word = {“funk”, “fury“, “junk“, “sunk“};
for (String a: word) {
if (a.startsWith(“fu“))
System.out.println (a +“ starts with fu“);
}
for (String a: word){
if (a.endsWith(“nk“))
System.out.println (a +“ ends with nk“);
}
}
}
.
Java Programming Tutorial for Intermediate – 2 / 59 – Some More String Methods
.
public class StringIndex {
public static void main (String[ ] args){
String a = “Kind ”;
String b = “Cool ”;
String c = “Clear ”;
String d = “Coder ”;
String s = “KindCoolClearCoderKindCoolClearCoder”;
.
System.out.println (a.trim( ) + d); // KindCoder
System.out.println (a + b + c + d); // Kind Cool Clear Coder
System.out.println (a.concat(b.concat(c.concat(d)))); // Kind Cool Clear Coder
.
System.out.println (a.toLowerCase()); // kind
System.out.println (a.toUpperCase()); // KIND
System.out.println (a.replace(‘K’, ‘F’)); // Find
.
System.out.println (s.indexOf(‘X’)); // -1
System.out.println (s.indexOf(‘K’)); // 0
System.out.println (s.indexOf(‘K’, 5)); // passing the first 6 digits, 18
System.out.println (s.indexOf(“Coo”)); // 4
System.out.println (s.indexOf(“Coo”, 10)); // 22
}
}
.
Java Programming Tutorial for Intermediate – 3 / 59 – Recursion
.
public class Factorial {
public static void main (String[ ] args) {
System.out.println (factorial (5));
}
public static long factorial (long n) {
if (n<=1)
return 1;
else
return n * factorial (n-1);
}
}
.
Java Programming Tutorial for Intermediate – 4 & 5 / 59 – ArrayList 1 & 2
.
import java.util.*;
public class ArrayListHandling {
public static void main (String[ ] args){
String[ ] A1 = {“apple”, “banana”, “cranberry”, “durian”};
List<String> L1 = new ArrayList<String> ( );
for (String s1:A1)
L1.add(s1);
for (int i=0; i<L1.size( ); i++){
System.out.printf (“%s “, L1.get(i));
}
System.out.println ( );
.
String[ ] A2 = {“apple”, “durian”};
List <String> L2 = new ArrayList<String> ( );
for (String s2:A2)
L2.add(s2);
for (int i=0; i<L2.size( ); i++){
System.out.printf (“%s “, L2.get(i));
}
System.out.println ( );
.
editList (L1, L2);
for (int i=0; i<L1.size( ); i++){
System.out.printf (“%s “, L1.get(i));
}
}
.
public static void editList (Collection<String> C1, Collection<String> C2) {
Iterator<String> I1 = C1.iterator( );
while (I1.hasNext( )) {
if (C2.contains(I1.next( )))
I1.remove( );
}
}
}
.
Java Programming Tutorial for Intermediate – 6 & 7/ 59 – LinkedList 1 & 2
.
import java.util.*;
public class LinkedListHandling {
public static void main (String[ ] args) {
String[ ] A1 = {“apple”, “banana”, “cranberry”, “durian”, “eggplant”};
List<String> L1 = new LinkedList<String> ( );
for (String s1:A1)
L1.add (s1);
.
String[ ] A2 = {“durian”, “eggplant”, “fig”, “guava”, “honeydew”};
List<String> L2 = new LinkedList<String> ( );
for (String s2:A1)
L2.add (s2);
.
L1.addAll (L2);
L2 = null;
.
printOut (L1);
removeThose (L1, 2, 5);
printOut (L1);
reverseThose (L1);
}
.
private static void printOut (List<String> L) {
for (String s:L)
System.out.printf (“%s “, s);
System.out.println ( );
}
.
private static void removeThose (List<String> L, int from, int before) {
L.subList (from, before).clear( );
}
.
private static void reverseThose (List<String> L) {
ListIterator<String> LI = L.listIterator (L.size( ));
while (LI.hasPrevious( ))
System.out.printf (“%s “, LI.previous ( ));
}
}
.
Java Programming Tutorial for Intermediate – 8 / 59 – Converting Lists to Arrays
.
import java.util.*;
public class ListToArrayHandling {
public static void main (String[ ] args) {
String[ ] A1 = {“banana”, “cranberry”, “durian”, “eggplant”};
LinkedList<String> L1 = new LinkedList<String> (Arrays.asList(A1));
.
L1.addFirst(“apple”);
L1.add(“fig”);
.
A1 = L1.toArray (new String [L1.size( )]);
for (String s1:A1)
System.out.printf (“%s “, s1);
}
}
.
Java Programming Tutorial for Intermediate – 9 / 59 – Collections Method Sort
.
import java.util.*;
public class CollectionsSortHandling {
public static void main (String[ ] args) {
String [ ] A1 = {“cranberry”, “durian”,“apple”, “banana”, “eggplant”};
List<String> L1 = Arrays.asList (A1);
.
Collections.sort (L1);
System.out.printf (“%s \n”, L1); // [apple, banana, cranberry, durian, eggplant]
.
Collections.sort (L1, Collections.reverseOrder());
System.out.printf (“%s”, L1); // [eggplant, durian, cranberry, banana, apple]
}
}
.
Java Programming Tutorial for Intermediate – 10 & 11 / 59 – Collections Reverse, Copy & Fill
.
import java.util.*;
public class ReverseCopyHandling {
public static void main (String[ ] args){
Character [ ] C1 = {‘a’, ‘b’, ‘c’};
List <Character> L1 = Arrays.asList (C1);
.
System.out.println (“The original list: “);
output (L1);
.
Collections.reverse (L1);
System.out.println (“The reversed list: “);
output (L1);
.
Character [ ] C2 = new Character [3];
List <Character> L2 = Arrays.asList (C2);
.
Collections.copy (L2, L1);
System.out.println (“The copied list: “);
output (L2);
.
Collections.fill (L1, ‘d’);
System.out.println (“The newly filled list: “);
output (L1);
}
private static void output (List <Character> L) {
for (Character c:L)
System.out.printf(“%s “, c);
System.out.println( );
}
}
.
Java Programming Tutorial for Intermediate – 12 &13 / 59 – AddAll, Frequency & Disjoint.
.
import java.util.*;
public class AddAllFrequencyDisjointHandling {
public static void main (String[] args) {
String[ ] A1 = {“apple”, “banana”, “cranberry”, “durian”};
List<String> L1 = Arrays.asList(A1);
ArrayList<String> AL1 = new ArrayList<String> ( );
AL1.add (“eggplant”);
AL1.add (“fig”);
AL1.add (“guava”);
AL1.add (“guava”);
AL1.add (“guava”);
printOut (AL1);
.
Collections.addAll (AL1, A1);
printOut (AL1);
.
Collections.sort (AL1);
printOut (AL1);
.
System.out.println (Collections.frequency (AL1, “guava”));
.
Boolean B1 = Collections.disjoint (L1, AL1);
System.out.println (B1);
if (B1)
System.out.println (“There’s nothing in common.”);
else
System.out.println (“There’s something in common.”);
}
.
private static void printOut(ArrayList<String> AL){
for (String al:AL)
System.out.printf (“%s “, al);
System.out.println ( );
}
}
.
Java Programming Tutorial for Intermediate – 14 / 59 – Stack, Push & Pop.
.
import java.util.*;
public class StackPushPopHandling {
public static void main (String [ ] args) {
Stack <String> S1 = new Stack <String> ( );
S1.push (“bottom”);
printOut (S1);
S1.push (“second”);
printOut (S1);
S1.push (“third”);
printOut (S1);
S1.pop ( );
printOut (S1);
S1.pop ( );
printOut (S1);
S1.pop ( );
printOut (S1);
}
.
private static void printOut (Stack <String> S1) {
if (S1.isEmpty( ))
System.out.println (“Nothing is in Stack.”);
else
System.out.printf (“%s top\n”, S1);
}
}
.
Java Programming Tutorial for Intermediate – 15 / 59 – PriorityQueue, Offer, Peek & Poll.
.
import java.util.*;
public class PriorityQueuePeekPollHandling {
public static void main (String[ ] args) {
PriorityQueue <String> PQ = new PriorityQueue <String> ( );
PQ.offer (“first”);
PQ.offer (“second”);
PQ.offer (“third”);
.
System.out.printf (“%s “, PQ);
System.out.println ( );
.
System.out.printf (“%s “, PQ.peek ( ));
System.out.println ( );
.
PQ.poll ( );
System.out.printf (“%s”, PQ);
}
}
.
Java Programming Tutorial for Intermediate – 16 / 59 – HashSet
.
import java.util.*;
public class HashSetHandling {
public static void main (String[ ] args) {
String [ ] A1 = {“apple”, “banana”, “cranberry”, “durian”, “durian”, “durian”};
List <String> L1 = Arrays.asList (A1);
.
System.out.printf (“%s “, L1); // [apple, banana, cranberry, durian, durian, durian]
System.out.println ( );
.
Set <String> S1 = new HashSet <String> (L1);
.
System.out.printf (“%s “, S1); // [cranberry, banana, apple, durian]
System.out.println ( );
}
}
.
Java Programming Tutorial for Intermediate – 17 / 59 – Non-Generic Methods
.
import java.util.*;
public class NonGenericHandling {
public static void main (String [ ] args) {
Integer [ ] I1 = {1, 2, 3, 4};
Character [ ] C1 = {‘a’, ‘b’, ‘c’, ‘d’};
printThose (I1); // 1 2 3 4
printThose (C1); // a b c d
}
.
private static void printThose (Integer[ ] I) {
for (Integer i: I)
System.out.printf (“%s “, i);
System.out.println ( );
}
.
private static void printThose (Character[ ] C) {
for (Character c: C)
System.out.printf (“%s “, c);
System.out.println ( );
}
}
.
Java Programming Tutorial for Intermediate – 18 / 59 – Implementing a Generic Method
.
import java.util.*;
public class GenericHandling {
public static void main (String [ ] args) {
Integer [ ] I1 = {1, 2, 3, 4};
Character [ ] C1 = {‘a’, ‘b’, ‘c’, ‘d’};
printThose (I1); // 1 2 3 4
printThose (C1); // a b c d
}
.
private static <T> void printThose (T [ ] t) {
for (T x: t)
System.out.printf(“%s “, x);
System.out.println();
}
}
.
Java Programming Tutorial for Intermediate – 19 / 59 – Generic Return Type.
.
import java.util.*;
public class GenericReturnHandling {
public static void main (String [ ] args) {
System.out.println (max (1, 23, 456)); //456
System.out.println (max (“abc”, “efg”, “hij”)); //hij
}
private static <T extends Comparable <T>> T max( T a, T b, T c){
T m = a;
if (b.compareTo(a) > 0)
m = b;
if (c.compareTo(m) > 0)
m = c;
return m;
}
}
.
Java Programming Tutorial for Intermediate – 20 ~21 / 59 – Applets on a Website
.
import java.awt.*;
import javax.swing.*;
public class AppletHandling extends JApplet {
public void paint (Graphics g) {
super.paint (g);
g.drawString (“This is a new applet”, 25, 25);
}
}
.
Open Windows Explorer and search for “AppletHandling.class” and copy it to desktop.
C:\Users\Adrian\workspace\Adrian\bin\Adrian\AppletHandling.class
C:\Users\Adrian\Desktop\AppletHandling.class
.
Open Notepad ++ and edit as below, then save it as “index.html” on desktop.
<html>
<body>
<applet code = “AppletHandling.class” width = “400” height = “100”>
</applet>
</body>
</html>
C:\Users\Adrian\Desktop\index.html
.
Log into Cpanel, open File manager and upload “index.html” & “AppletHandling.class” to “public_html”.
Go to the webpage “www.howtochange.com” to see how the applet comes out.
.
Java Programming Tutorial for Intermediate – 22 / 59 – Init for Applets
.
import java.awt.*;
import javax.swing.*;
public class InitHandling extends JApplet {
private double sum;
public void init ( ) {
String st1 = JOptionPane.showInputDialog (“Enter your first number”);
String st2 = JOptionPane.showInputDialog (“Enter your second number”);
double do1 = Double.parseDouble (st1);
double do2 = Double.parseDouble (st2);
sum = do1 + do2;
}
public void paint (Graphics g) {
super.paint (g);
g.drawString (“The sum is ” + sum, 25, 25);
}
}
.
Java Programming Tutorial for Intermediate – 23 ~ 25 / 59 – Oval Panel with Slider
.
import java.awt.*;
import javax.swing.*;
public class OvalPanel extends JPanel {
private int DiameterA = 0;
public void paintComponent (Graphics g) {
super.paintComponent (g);
g.fillOval (10, 10, DiameterA, DiameterA);
}
public void setDiameter (int d) {
DiameterA = (d >= 0? d : 10);
repaint ( );
}
public Dimension getPreferredSize ( ) {
return new Dimension (200, 200);
}
public Dimension getMinimumSize ( ) {
return getPreferredSize ( );
}
}
.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class WindowFrame extends JFrame {
private OvalPanel OvalPanelA;
private JSlider SliderA;
public WindowFrame ( ) {
super (“Oval Panel with Slider”);
OvalPanelA = new OvalPanel ( );
OvalPanelA.setBackground (Color.ORANGE);
.
SliderA = new JSlider (SwingConstants.HORIZONTAL, 0, 200, 10);
SliderA.setMajorTickSpacing (10);
SliderA.setPaintTicks (true);
.
SliderA.addChangeListener (
new ChangeListener ( ) {
public void stateChanged (ChangeEvent CE) {
OvalPanelA.setDiameter (SliderA.getValue ( ));
}
}
);
add (OvalPanelA, BorderLayout.CENTER);
add (SliderA, BorderLayout.SOUTH);
}
}
.
import javax.swing.*;
public class WindowFrameHandling {
public static void main (String [ ] args) {
WindowFrame wf = new WindowFrame ( );
wf.setSize (230, 280);
wf.setVisible (true);
wf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
.
Java Programming Tutorial for Intermediate – 26 ~ 27 / 59 – Runnable & Thread
.
import java.util.*;
public class RunnableA implements Runnable {
String nameA;
int timeA;
Random randomA = new Random();
public RunnableA (String nameX){
nameA = nameX;
timeA = randomA.nextInt(999);
}
public void run (){
try{
System.out.printf(“%s is sleeping for %d\n”, nameA, timeA);
Thread.sleep(timeA);
System.out.printf(“%s is awake\n”, nameA};
}catch(Exception E){
}
}
}
.
public class ThreadMain{
public static void main(String[] args){
Thread threadA = new Thread(new RunnableA(“The first one”));
Thread threadB = new Thread(new RunnableA(“The second one”));
Thread threadC = new Thread(new RunnableA(“The third one”);
Thread threadD = new Thread(new RunnableA(“The fourth one”));
threadA.start();
threadB.start();
threadC.start();
threadD.start();
}
}
.
Java Programming Tutorial for Intermediate – 28 ~ 33 / 59 – Applet & Networking
.
Open Notepad++ and edit as below to save it as Adrian.html to the Desktop.
<html>
<body>
<applet code = “Webpages.class” width= “500” height = “230”>
<param name = “websiteName0” value = “Google”>
<param name = “websiteAddress0″ value = “www.google.com”>
<param name = “websiteName1″ value = “Youtube”>
<param name = “websiteAddress1″ value = “www.youtube.com”>
</applet>
</body>
</html>
C:\Users\Adrian\Desktop\Adrian.html
.
Open Eclipse, edit as below and save it as Webpages.java.
import java.applet.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class Webpages extends JApplet {
private JList theWebsiteList;
private ArrayList<String> theWebsiteNames;
private HashMap<String, URL> theWebsiteInfo;
public void init(){
theWebsiteNames = new ArrayList<String>() ;
theWebsiteInfo = new HashMap<String, URL>();
grabHTMLInfo();
add(new JLable(“What website would like to visit?”), BorderLayout.North);
theWebsiteList = new JList(theWebsiteNames.toArray());
theWebsiteList.addListSelectionListener{
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent LSE){
Object theObject = theWebsiteList.getSelectedValue();
URL theURL = theWebsiteInfo.get(theObject);
AppletContext theAppletContext = getAppletContext();
theAppletContext.showDocument(theURL);
}
}
};
add(new JScrollPane(theWebsiteList), BorderLayout.CENTER);
}
public void grabHTMLInfo(){
String theWebsiteName;
String theWebsiteAddress;
URL theURL;
int counter = 0;
theWebsiteName = getParameter(“websiteName” + counter);
while (theWebsiteName ! = null){
theWebsiteAddress = getParameter(“websiteAddress” + counter);
try{
theURL = new URL(theWebsiteAddress);
theWebsiteNames.add(theWebsiteName);
theWebsiteInfo.put(theWebsiteName, theURL);
}catch(){MalformedURLException MUE){
MUE.printStackTrace();
}
counter++;
theWebsiteName = getParameter(“websiteName” + counter);
}
}
}
.
Open Windows Explorer and search Webpages.class & Webpages$1.class
C:\Users\Adrian\workspace\Adrian\bin\Adrian\Webpages$1.class
C:\Users\Adrian\workspace\Adrian\bin\Adrian\Webpages.class
.
Copy Webpages.class & Webpages$1.class to the Desktop.
C:\Users\Adrian\Desktop\Webpages$1.class
C:\Users\Adrian\Desktop\Webpages.class
.
Move Adrian.html, Webpages.class & Webpages$1.class to a new folder TestApplet on the Desktop.
C:\Users\Adrian\Desktop\TestApplet\Adrian.html
C:\Users\Adrian\Desktop\TestApplet\Webpages$1.class
C:\Users\Adrian\Desktop\TestApplet\Webpages.class
.
Open Chrome and go to the file to see how it works
file:////C:/Users/Adrian/Desktop/TestApplet/Adrian.html
.
Log into the website host, go to cpanel’s file manager, and upload these files.
/public_html/TestApplet/Adrian.html
/public_html/TestApplet/Webpages$1.class
/public_html/TestApplet/Webpages.class
.
Open web browser and go to the webpage
http://howtochangelife.com/TestApplet/Adrian.html
.
Java Programming Tutorial for Intermediate – 34 ~ 37 / 59 – Web Browser
.
BrowseToSet.java __________________________________________________________________________
.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
.
public class BrowserToSet extends JFrame{
private JTextField addressBar;
private JEditorPane displayPane;
.
public BrowserToSet( ){
super(“Shine Browser”);
addressBar = new JTextField(“Enter a URL, please”);
addressBar.addActionListener(
new ActionListener( ){
public void actionPerformed(ActionEvent AE){
loadContent(AE.getActionCommand( ));
}
}
);
add(addressBar, BorderLayout.NORTH);
.
displayPane = new JEditorPane ( );
displayPane.setEditable(false);
displayPane.addHyperlinkListener(
new HyperlinkListener( ){
public void hyperlinkUpdate(HyperlinkEvent HE){
if(HE.getEventType( )==HyperlinkEvent.EventType.ACTIVATED){
loadContent(HE.getURL( ).toString( ));
}
}
}
);
add(new JScrollPane(displayPane), BorderLayout.CENTER);
setSize(500, 300);
setVisible(true);
}
.
private void loadContent(String userText){
try{
addressBar.setText(userText);
displayPane.setPage(userText);
}catch(Exception E){
System.out.println(“Check the URL, again”);
}
}
}
.
BrowseToRun.java __________________________________________________________________________
.
import javax.swing.JFrame;
.
public class BrowserToRun{
public static void main(String[ ] args){
BrowserToSet BTS = new BrowserToSet();
BTS.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
.
Java Programming Tutorial for Intermediate – 38 ~ 48 / 59 – Messenger Server
.
MessengerServerToSet.java ______________________________________________________________
.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
.
public class MessengerServerToSet extends JFrame{
.
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
.
public MessengerServerToSet(){
super(“Shine’s Instant Messenger”);
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent AE){
sendMessage(AE.getActionCommand());
userText.setText(“”);
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300, 150);
setVisible(true);
}
.
public void startRunning(){
try{
server = new ServerSocket(6789, 100);
while(true){
try{
waitForConnection();
setupStreams();
keepChatting();
}catch(EOFException EOFE){
showMessage(“\n Server ended the connection!”);
}finally{
closeChatting();
}
}
}catch(IOException IOE){
IOE.printStackTrace();
}
}
.
private void waitForConnection() throws IOException{
showMessage(“Waiting for someone to connect…\n”);
connection = server.accept();
showMessage(“Now connected to “ + connection.getInetAddress().getHostName());
}
.
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage(“\n Streams are now setup.\n”);
}
.
private void keepChatting() throws IOException{
String message = “You are now connected!”;
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage(“\n” + message);
}catch(ClassNotFoundException CNFE){
showMessage(“\n I don’t get it.”);
}
}while(!message.equals(“CLIENT – END”));
}
.
private void closeChatting(){
showMessage(“\n Closing connection….\n”);
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException IOE){
IOE.printStackTrace();
}
}
.
private void sendMessage(String message){
try{
output.writeObject(“SERVER – “ + message);
output.flush();
showMessage(“\nSERVER – “ + message);
}catch(IOException IOE){
chatWindow.append(“\n Error: I can’t send that message”);
}
}
.
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
.
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
.
MessengerServerToRun.java _____________________________________________________________
.
import javax.swing.JFrame;
.
public class MessengerServerToRun {
public static void main(String[ ] args){
MessengerServerToSet MSTS = new MessengerServerToSet();
MSTS.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MSTS.startRunning();
}
}
.
Java Programming Tutorial for Intermediate – 49 ~ 59 / 59 – Messenger Client
.
MessengerClientToSet.java _______________________________________________________________
.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
.
public class MessengerClientToSet extends JFrame{
.
private String message = ” “;
private String serverIP;
private Socket connection;
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
.
public MessengerClientToSet(String host){
super(“Messenger Client”);
serverIP = host;
.
userText = new JTextField ( );
userText.setEditable(false);
userText.addActionListener(
new ActionListener( ){
public void actionPerformed(ActionEvent AE){
sendMessage(AE.getActionCommand( ));
userText.setText(” “);
}
}
);
add(userText, BorderLayout.NORTH);
.
chatWindow = new JTextArea ( );
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
.
public void startRunning( ){
try{
connectToServer( );
setupStreams( );
keepChatting( );
}catch(EOFException EOFE){
showMessage(“\n Client Terminated Connection.”);
}catch(IOException IOE){
IOE.printStackTrace( );
}finally{
closeChatting( );
}
}
.
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
.
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
.
private void sendMessage(String message){
try{
output.writeObject(“CLIENT – ” + message);
output.flush( );
showMessage(“\nCLIENT – ” + message);
}catch(IOException IOE){
chatWindow.append(“\n something went wrong.”);
}
}
.
private void connectToServer( ) throws IOException{
showMessage(“Connecting…\n”);
connection = new Socket(InetAddress.getbyName(serverIP), 6789);
showMessage(“Connected: ” + connection.getInetAddress( ).getHostName( ));
}
.
private void setupStreams( ) throws IOException{
output = new ObjectOutputStream(connection.getOutputStream( ));
output.flush( );
input = new ObjectInputStream(connection.getInputStream( ));
showMessage(“\n Your streams are now good to go! \n”);
}
.
private void keepChatting( ) throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject( );
showMessage(“\n” + message);
}catch(ClassNotFoundException CNFE){
showMessage(“\n I don’t know what object type it is.”);
}
}while(!message.equals(“SERVER – END”));
}
.
public void closeChatting( ){
showMessage(“\n closing connection…”);
ableToType(false);
try{
output.close( );
input.close( );
connection.close( );
}catch(IOException IOE){
IOE.printStackTrace( );
}
}
}
.
MessengerClientToRun.java _______________________________________________________________
.
import javax.swing.JFrame;
public class MessengerClientToRun {
public static void main(String[] args){
MessengerClientToSet mcts;
mcts = new MessengerClientToSet(“127.0.0.1”);
mcts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mcts.startRunning();
}
}
.