A)
Write a java program to scroll the text from left to right and vice versa
continuously.
import java.applet.Applet;
import java.awt.*;
public class Slip1A extends Applet implements Runnable {
int x, y, z;
Thread t;
public void init() {
x = 50;
y = 50;
z = 1;
t = new Thread(this);
t.start();
}
public void mpostion() {
x = x + 10 * z;
if (x > this.getWidth())
z = -1;
if (x < 0)
z = 1;
}
public void run() {
while (true) {
repaint();
mpostion();
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
public void paint(Graphics g) {
g.drawString("SVPM", x, y);
}
}
/*
* <applet code="Slip1A.class"
width="300" height="300">
* </applet>
*/
B)
Write a socket program in java for chatting application.(Use Swing)
Answer :
//Server
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Slip1B extends Frame implements ActionListener, Runnable {
Button b1;
TextField t1;
TextArea ta;
Thread t;
BufferedReader br;
PrintWriter pw;
public Slip1B() {
Frame f = new Frame("Server");
f.setLayout(new FlowLayout());
b1 = new Button("Send");
b1.addActionListener(this);
t1 = new TextField(15);
ta = new TextArea(12, 20);
f.add(t1);
f.add(ta);
f.add(b1);
try {
ServerSocket ss = new ServerSocket(2000);
Socket s = ss.accept();
System.out.println(s);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
} catch (Exception e) {
}
t = new Thread(this);
t.start();
f.setSize(400, 400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
pw.println(t1.getText());
t1.setText("");
}
public void run() {
while (true) {
try {
String str = br.readLine();
ta.append(str + "\n");
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
Slip1B c = new Slip1B();
}
}
//Client
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Slip1B1 extends Frame implements ActionListener, Runnable {
Button b1;
TextField t1;
TextArea ta;
Thread t;
Socket s;
BufferedReader br;
PrintWriter pw;
public Slip1B1() {
Frame f = new Frame("Client");
f.setLayout(new FlowLayout());
b1 = new Button("Send");
b1.addActionListener(this);
t1 = new TextField(15);
ta = new TextArea(12, 20);
f.add(t1);
f.add(ta);
f.add(b1);
try {
s = new Socket("localhost",2000);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream(), true);
} catch (Exception e) {
}
t = new Thread(this);
t.start();
f.setSize(400, 400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
pw.println(t1.getText());
t1.setText("");
}
public void run() {
while (true) {
try {
String str = br.readLine();
ta.append(str + "\n");
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
Slip1B1 c = new Slip1B1();
}
}
No comments:
Post a Comment