Im having a problem getting my server to send image over a socket. I need to have 10 1920x1080 images sent to the client in a timecrunch of atleast 5-10 seconds. I seem to get an error anywhere I go or my client/server failsafes go off and make it impossible to send in those certain ways. Could anyone point me in the right direction and tell me a way to implement this without messing up other proccesses?
Client code for nonobject things, and used for UTF packets.
DataInputStream in ;
Client client;
public boolean enabled = true;
Object packet;
String[] tempData;
public Thread thread;
public Data(DataInputStream in , Client client) {
this. in = in ;
this.client = client;
}
#
Override
public void run() {
while (enabled) {
int x = 0, y = 0, width = 0, height = 0, r = 0, g = 0, b = 0, id = 0, mousex = 0, mousey = 0, alpha = 0;
String data = "Invalid";
try {
data = in.readUTF().trim();
} catch(Exception e){
client.comp.printErr("Disconnected from server, " + e.toString());
client.disconnectClient("Socket Closed.");
enabled = false;
}
try{
if (data.contains("id/")) {
data = data.split("id/")[1];
client.id = Integer.valueOf(data);
client.serverHasResponded = true;
client.comp.printOut("Client ID: " + data);
}
if (data.contains("rejected/")) {
data = data.split("rejected/")[1];
//Check to see if server sent packet info;
packet = "null";
try {
if (data.contains("/")) {
tempData = data.split("/");
data = tempData[0];
packet = "null";
for (int i = 1; i < tempData.length; i++) {
if (!packet.equals("null")) {
packet = packet + "/" + tempData[i];
} else packet = tempData[i];
}
}
// Packet info done.
} catch (Exception e) {
client.comp.printErr("Error while splitting packet: " + e.toString());
}
if (Integer.valueOf(data) == 0) {
client.disconnectClient("No Slots Open.");
client.comp.printErr("Rejected from server, no slots open.");
enabled = false;
}
if (Integer.valueOf(data) == 1) {
client.disconnectClient("Invalid Version.");
client.comp.printErr("Rejected from server, invalid version.");
enabled = false;
}
if (Integer.valueOf(data) == 2) {
client.disconnectClient("Kicked.");
client.comp.printErr("Rejected from server, kicked.");
enabled = false;
}
if (Integer.valueOf(data) == 3) {
client.disconnectClient("Unknown Packet.");
client.comp.printErr("Rejected from server, client sent unknown packet on connection? Packet: " + packet);
enabled = false;
}
if (Integer.valueOf(data) == 4) {
client.disconnectClient("Already Logged in.");
client.comp.printErr("Rejected from server, the username " + client.comp.username + " is already logged on?");
enabled = false;
}
if (Integer.valueOf(data) == 5) {
client.disconnectClient("Not Authenticated");
client.comp.printErr("Rejected from server, server requires authentication and were not authenticated?");
enabled = false;
}
if (Integer.valueOf(data) == 6) {
client.disconnectClient("No tick from client.");
client.comp.printErr("Rejected from server, server didnt recieve a tick?");
enabled = false;
}
if (Integer.valueOf(data) == 7) {
client.disconnectClient("No open Canvases.");
client.comp.printErr("Rejected from server, all canvases blacklisted?");
enabled = false;
}
if (Integer.valueOf(data) == 8) {
client.disconnectClient("Banned.");
client.comp.printErr("Rejected from server, Banned.");
enabled = false;
}
}
if(data.contains("servertick/")){
data = data.split("servertick/")[1];
if(Integer.valueOf(data) == client.id){
client.heartbeatManager.serverTicked();
} else {
client.comp.printErr("Server sent an invalid tick.");
}
}
if(data.contains("changeCanvas/")){
data = data.split("changeCanvas/")[1];
client.currentCanvas = Integer.parseInt(data);
}
if(data.contains("changeCanvasFailed/")){
data = data.split("changeCanvasFailed/")[1];
client.popups.add(new Popup(client, "Error", "Access denied to canvas "+data+"."));
}
if(data.contains("overrideChangeCanvas/")){
data = data.split("overrideChangeCanvas/")[1];
client.currentCanvas = Integer.parseInt(data);
client.comp.printOut(data);
}
if(data.contains("broadcastToClient/")){
data = data.split("broadcastToClient/")[1];
client.chat.addChatMessage(data, Color.white);
}
if (data.contains("chatmessage/")) {
data = data.split("chatmessage/")[1];
String[] tokens = data.split("/");
String user = "";
String message = "";
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
user = tokens[0];
if (i == 1)
message = tokens[1];
}
client.chat.addChatMessage(user + ": " + message, Color.white);
}
if (data.contains("drawcircle/")) {
data = data.split("drawcircle/")[1];
String[] tokens = data.split("/");
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 4)
r = Integer.valueOf(tokens[i]);
if (i == 5)
g = Integer.valueOf(tokens[i]);
if (i == 6)
b = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
if (i == 8)
alpha = Integer.valueOf(tokens[i]);
}
client.canvas[id].draw(x, y, width, height, r, g, b, alpha);
}
if (data.contains("erasecircle/")) {
data = data.split("erasecircle/")[1];
String[] tokens = data.split("/");
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
}
client.canvas[id].erase(x, y, width, height);
}
if (data.contains("playerjoin/")) {
data = data.split("playerjoin/")[1];
client.chat.addChatMessage(data+" has joined the game.", Color.yellow);
}
if (data.contains("playerleave/")) {
data = data.split("playerleave/")[1];
client.chat.addChatMessage(data+" has left the game.", Color.yellow);
}
} catch (Exception e) {
client.comp.printErr("Failed to process a packet, " + e.toString());
}
}
}
public void close() throws Exception{
thread.stop();
enabled = false;
}
public void setThread(Thread t){
thread = t;
}
Client code ment for images (not modified yet) :
Client client;
DataInputStream in;
Thread thread;
public DataObjects(DataInputStream in, Client c){
client = c;
this.in = in;
thread = new Thread(this);
thread.start();
}
#Override
public void run() {
boolean enabled = true;
while(enabled){
}
}
Server code ment to send/recieve and reroute both UTF and Object packets
public DataOutputStream out;
public DataInputStream in;
public User[] user;
public int slots;
public int id;
InetAddress address;
Server server;
public String username = "";
public boolean enabled;
public boolean ticking;
public boolean allDataSent;
int currentCanvas = 0;
private boolean playerConnected;
public boolean imageByteReady=true;
private boolean sendImage;
public User(DataOutputStream out, DataInputStream in, User[] user, int slots, int i, InetAddress inetAddress, Server server, String username){
this.out = out;
this.in = in;
this.user = user;
this.slots = slots;
this.id = i;
address = inetAddress;
this.server = server;
this.username = username;
ticking = true;
}
#Override
public void run() {
enabled = true;
while(enabled){
try {
String data = in.readUTF();
if(valid(data)){
for(int i = 0; i < slots; i++){
if(user[i]!=null){
if(data.contains("timedout/")){
data = data.split("timedout/")[1];
if(Integer.valueOf(data) == 1){
server.printOut(server.disconnectMessage(id, "Client disconnected because server didnt tick."));
user[id] = null;
enabled = false;
} else {
server.printErr("Got an invalid timeout packet. Packet: timedout/"+data);
}
}
if(data.contains("clienttick/")){
data = data.split("clienttick/")[1];
out.writeUTF("servertick/"+data);
server.packetManager.resetClientWithID(Integer.valueOf(data));
}
if(data.contains("drawcircle/") || data.contains("erasecircle/") || data.contains("chatmessage/"))
user[i].out.writeUTF(data);
}
}
if(data.contains("switchcanvas/")){
data = data.split("switchcanvas/")[1];
if(server.canvasaccessmanager.playerCanBeOnCanvas(id, Integer.valueOf(data)) && Integer.valueOf(data) != currentCanvas){
out.writeUTF("changeCanvas/"+data);
currentCanvas = Integer.valueOf(data);
server.printOut(user[id].username+" switched to canvas "+(Integer.valueOf(data)+1));
} else if(!server.canvasaccessmanager.playerCanBeOnCanvas(id, Integer.valueOf(data))){
out.writeUTF("changeCanvasFailed/"+data);
server.printOut(user[id].username+" was denied access to canvas "+(Integer.valueOf(data)+1));
}
}
if(data.contains("sendImage/")){
data = data.split("sendImage/")[1];
sendImage = Boolean.valueOf(data);
}
if (data.contains("drawcircle/")) {
data = data.split("drawcircle/")[1];
String[] tokens = data.split("/");
int x = 0, y = 0, width = 0, height = 0, r = 0, g = 0, b = 0, id = 0, alpha = 0;
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 4)
r = Integer.valueOf(tokens[i]);
if (i == 5)
g = Integer.valueOf(tokens[i]);
if (i == 6)
b = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
if (i == 8)
alpha = Integer.valueOf(tokens[i]);
}
server.canvasManager.drawCircle(x, y, width, height, r, g, b, alpha, id);
}
if (data.contains("erasecircle/")) {
data = data.split("erasecircle/")[1];
String[] tokens = data.split("/");
int x = 0, y = 0, width = 0, height = 0, id = 0;
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
}
server.canvasManager.eraseCircle(x, y, width, height, id);
}
if(data.contains("chatmessage/")){
data = data.split("chatmessage/")[1];
String[] tokens = data.split("/");
String user = "";
String message = "";
for (int x = 0; x < tokens.length; x++) {
if (x == 0)
user = tokens[0];
if (x == 1)
message = tokens[1];
}
server.printOut(user + " said '" + message+"'");
}
} else {
server.printErr("Caught an overlapped packet from client "+id);
server.packetManager.resetClientWithID(id);
}
} catch (IOException e) {
if(enabled){
server.printOut(server.disconnectMessage(id, "Client socket closed. Manual disconnect?"));
user[id] = null;
enabled = false;
}
}
}
saveUserData();
if(playerConnected)
sendLeaveMessage();
}
private boolean valid(String data) {
String[] tokens = data.split("/");
if(tokens[1].toLowerCase().contains(inputFix(tokens[0]))){
return false;
}
return true;
}
private String inputFix(String data) {
return data.replaceAll("[^a-zA-Z]", "").toLowerCase().trim();
}
private void saveUserData() {
server.playermanager.setUserProperty(username, "currentCanvas", String.valueOf(currentCanvas));
}
public void sendID() {
try {
out.writeUTF("id/"+id);
playerConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendCanvases() {
try{
sendCanvas(0);
server.printOut("Sent canvas 0");
Thread.sleep(1);
} catch(Exception e){
server.printErr("Failed to send canvas 0");
sendCanvases();
}
}
public void sendCanvas(int id) throws Exception{
}
public void sendLeaveMessage(){
for(int i = 0; i < slots; i++){
if(i != id){
if(user[i] != null){
try {
user[i].out.writeUTF("playerleave/"+username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
public void sendJoinMessage() {
for(int i = 0; i < slots; i++){
if(i != id){
if(user[i] != null){
try {
user[i].out.writeUTF("playerjoin/"+username);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void sendData() {
if(server.playermanager.userExists(username)){
int x = Integer.parseInt(server.playermanager.loadUserProperty(username, "currentCanvas"));
currentCanvas = x;
try {
out.writeUTF("overrideChangeCanvas/"+x);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//If user is new;
int x = server.canvasaccessmanager.nextOpenCanvas(username);
try {
currentCanvas = x;
out.writeUTF("overrideChangeCanvas/"+x);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setUpUserData() {
if(!server.playermanager.userExists(username)){
server.playermanager.createUser(username);
}
}
Client code:
public Dimension dimension;
static final long serialVersionUID = 1L;
public Thread thread;
public int currentfps;
public long start;
public int fps;
static Socket socket;
public static DataInputStream in ;
public Listener listener = null;
public boolean isRunning = true;
public boolean justClicked;
public static int canvasMax = 10;
public Canvas[] canvas = new Canvas[canvasMax];
public int currentCanvas;
public Graphics canvasGraphics;
public Player player;
public DataOutputStream out;
public boolean connectedToServer = false;
public boolean click;
public int id;
public Image screen;
public static Toolkit toolkit = Toolkit.getDefaultToolkit();
public static Image cursor = toolkit.getImage("res/icons/cursor.png");
public static Image tabCanvas = toolkit.getImage("res/image/tabs/tabCanvas.png");
public static Image tabColor = toolkit.getImage("res/image/tabs/tabColor.png");
public Image tabGuide = toolkit.getImage("res/image/tabs/tabGuide.png");;
public static Image[] guideImages = new Image[canvasMax];
public int tabOffset = 0, tabWidth = 200, currentTabWidth = 0, tabHeight = 0;
public boolean ChatOpen;
public CanvasGUI canvasgui;
public int currentColor;
public int colorMax = 10;
public boolean serverHasResponded = false;
public int wait;
public Data data;
public Chat chat;
public int defaultPort = 58828;
public int port = 0;
public String ip = "";
public ColorGUI colorgui;
public GuideGUI guidegui;
public int currentGuide;
public int waitMax = 1000000;
public HeartbeatManager heartbeatManager;
public ArrayList<Popup> popups;
public Integer lastCanvasClick;
private boolean debug;
public ServerLogin serverLogin;
public boolean serverLoginOpen;
public Component comp;
int index;
public boolean started;
private boolean disconnecting;
public boolean clientHasRecieved;
public Client(Component component) {
this.comp = component;
}
public void connectClient(String ip, int port) {
try {
this.ip = ip;
this.port = port;
socket = new Socket(ip, port);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
connectedToServer = true;
out.writeUTF("authenticate/" + comp.authenticated);
out.writeUTF("username/" + comp.username);
out.writeUTF("version/" + comp.version);
data = new Data( in , this);
Thread thread = new Thread(data);
data.setThread(thread);
thread.start();
DataObjects dataObjects = new DataObjects(in, this);
} catch (Exception e) {
comp.printErr("Failed to connect to server, " + e.toString());
disconnectClient("Failed to connect");
}
}
public void disconnectClient(String var1) {
if(!disconnecting){
disconnecting = true;
try {
in = null;
out = null;
if (data != null){
data.enabled = false;
data = null;
};
if(connectedToServer)
socket.close();
socket = null;
connectedToServer = false;
serverHasResponded = false;
wait = 0;
String str = "Disconnected from server "+ip+":"+port+", "+var1;
comp.printOut(str);
ip = "";
port = 0;
comp.stopGame();
comp.startWarningMenu(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
void initializing(int i) {
index = i;
comp.printOut("Index: "+i+".");
tabHeight = comp.height;
isRunning = true;
comp.printOut("Creating Canvases.");
for (int x = 0; x < canvasMax; x++) {
canvas[x] = new Canvas(this);
canvas[x].clear(0, 0, comp.width, comp.height);
comp.printOut("Creating Canvas"+(x+1)+".");
}
comp.printOut("Canvases Created.");
comp.printOut("Loading Guides.");
for (int x = 0; x < guideImages.length; x++) {
guideImages[x] = toolkit.getImage("res/image/guides/guides_" + x + ".png");
if (!new File("res/image/guides/guides_" + x + ".png").exists()) {
guideImages[x] = toolkit.getImage("res/image/guides/guides_0.png");
comp.printErr("Couldnt Locate Guide"+(x+1)+".");
} else {
comp.printOut("Loaded Guide"+(x+1)+".");
}
}
colorgui = new ColorGUI(this);
comp.printOut("Loaded ColorGUI.");
guidegui = new GuideGUI(this);
comp.printOut("Loaded GuideGUI.");
chat = new Chat(this);
comp.printOut("Loaded Chatting Class.");
popups = new ArrayList<Popup>();
comp.printOut("Loaded ArrayList<Popup>.");
currentCanvas = 0;
heartbeatManager = new HeartbeatManager(this);
comp.printOut("Loaded Heartbeat Manager.");
canvasgui = new CanvasGUI(this);
comp.printOut("Loaded CanvasGUI.");
screen = comp.createImage(comp.pixel.width, comp.pixel.height);
comp.printOut("Loaded Screen Component.");
player = new Player(this);
comp.printOut("Loaded Player Class.");
serverLogin = new ServerLogin(this);
comp.printOut("Loaded Server Login GUI.");
started = true;
comp.printOut("Starting Threads. Game Loading done!");
thread = new Thread(this);
thread.setPriority(6);
thread.start();
}
Looks like a case for buffering to get better throughput. I see you instantiating DataInputStream/DataOutputStream, but those aren't buffered so I think you could get a big boost by adding BufferedInput/OutputStream to each side. I don't see your code where you copy the image to the stream. So the following should help:
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
Just remember to flush(). The other option you can do is compress your data before sending it over the stream. If you are sending a 1920x1080 image uncompressed would be around 8MB (=1920px * 1080px * 4 bytes / pixel) so 5-10s is not a surprising. Adding a GZipInputStream on top of that is pretty simple, and would compress all data sent. Image specific compression would probably achieve a higher compression, but more involved.
Related
I tried to create exe file from my code but it's get me error
java.lang.ClassNotFoundException: Access2
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
I used exe4j tool to generate exe from jar file
I used Jdk 1.8.0_25
and this a part of my main class (Access2)
public class Access2
{
BufferedReader in;
Writer out;
String CommData = "";
String TextData = "";
int FrameNo = 1;
String STX = String.valueOf('\002');
String ETX = String.valueOf('\003');
String EOT = String.valueOf('\004');
String ENQ = String.valueOf('\005');
String ACK = String.valueOf('\006');
String LF = String.valueOf('\n');
String CR = String.valueOf('\r');
String DEL = String.valueOf('\007');
String NAK = String.valueOf('\025');
String SYN = String.valueOf('\026');
String ETB = String.valueOf('\027');
String CRLF = this.CR + this.LF;
String enc;
String LastType = "";
String PatientID;
String PatientName;
String SampleID;
String Result = "";
String Parameter = "";
String PatientComment;
String SampleComment;
String ResultComment = "";
String QuerySampleID;
boolean QueryAsked = false;
Connection connection = null;
Statement stmt = null;
PreparedStatement prepStatement = null;
ResultSet rs = null;
String machine = Setting.GetPropVal("MachineName");
ArrayList<String> DataToSend = new ArrayList();
int Max_Farme_Size = 240;
int FIndex = 1;
int CurIndex = 0;
int RowIndex = 1;
String Frame_Sep;
int retries = 6;
Connection connection2 = null;
Statement stmt2 = null;
PreparedStatement prepStatement2 = null;
ResultSet rs2 = null;
public Access2(Socket s)
{
try
{
this.enc = Setting.GetPropVal("Encoding");
this.in = new BufferedReader(new InputStreamReader(s.getInputStream(), this.enc));
this.out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), this.enc));
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public Access2(SerialPort ser)
{
try
{
this.enc = Setting.GetPropVal("Encoding");
this.in = new BufferedReader(new InputStreamReader(ser.getInputStream(), this.enc));
this.out = new BufferedWriter(new OutputStreamWriter(ser.getOutputStream(), this.enc));
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void NextFrameNo()
{
this.FrameNo += 1;
if (this.FrameNo > 7) {
this.FrameNo = 0;
}
}
public void SaveData(String data)
{
String data2save = data.replaceAll(this.ENQ, "<ENQ>").replaceAll(this.STX, "<STX>").replaceAll(this.ETX, "<ETX>").replaceAll(this.EOT, "<EOT>").replaceAll(this.CR, "<CR>").replaceAll(this.CRLF, "<CRLF>").replaceAll(this.ETB, "<ETB>");
LogFile.createLog(this.machine + "_" + CurrentDate.getDate(2) + ".txt", "\r\n[" + CurrentDate.getDate(1) + "]" + ":" + data2save);
}
public String[] ParseFrames(String Data)
{
String[] Frame = Data.split(this.CR);
return Frame;
}
public boolean CheckSumCorrect()
{
String Frame = GetFrameData(this.CommData, 1);
String CalculatedSum = GetCheckSum(Frame);
String FrameSum = GetFrameData(this.CommData, 3);
boolean Status = CalculatedSum.equals(FrameSum);
return Status;
}
public boolean CheckFarmeNum()
{
String FN = GetFrameData(this.CommData, 4);
boolean Status;
if (Integer.toString(this.FrameNo).equals(FN))
{
Status = true;
NextFrameNo();
}
else
{
Status = false;
}
return Status;
}
public String GetCheckSum(String Dat)
{
int x = 0;
for (int i = 0; i < Dat.length(); i++) {
x += Dat.charAt(i);
}
String S = "00" + Integer.toHexString(x % 256);
String CheckSum = S.substring(S.length() - 2).toUpperCase();
return CheckSum;
}
public String GetFrameData(String Data, int FrameType)
{
String Frame = "";
int pos1 = Data.indexOf(this.STX);
int pos2 = Data.indexOf(this.ETX);
int pos3 = Data.indexOf(this.ETB);
if (FrameType == 1)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos1 + 1, pos2 + 1);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos1 + 1, pos3 + 1);
}
}
else if (FrameType == 2)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos1 + 2, pos2);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos1 + 2, pos3);
}
}
else if (FrameType == 3)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos2 + 1, pos2 + 3);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos3 + 1, pos3 + 3);
}
}
else if (FrameType == 4) {
Frame = Data.substring(pos1 + 1, pos1 + 2);
}
return Frame;
}
public void sendtoport(String Sample_ID)
{
try
{
int sent = 0;
for (String DataToSend1 : this.DataToSend)
{
this.out.write(DataToSend1);
this.out.flush();
SaveData(DataToSend1);
char c = (char)this.in.read();
String control = String.valueOf(c);
if (control.equals(this.ACK))
{
sent = 1;
}
else if (control.equals(this.NAK))
{
for (int x = 1; x <= this.retries; x++)
{
this.out.write(DataToSend1);
this.out.flush();
SaveData(DataToSend1);
}
sent = 0;
break;
}
}
this.DataToSend.clear();
this.FIndex = 1;
this.out.write(this.EOT);
this.out.flush();
SaveData(this.EOT);
try
{
this.connection2 = DBconnection.getConnection();
String ExecProc = "HK_Update_SCH ?,?,?";
this.connection2.setAutoCommit(false);
this.prepStatement = this.connection2.prepareStatement(ExecProc);
this.prepStatement2.setString(1, Sample_ID);
this.prepStatement2.setString(2, "Access2");
this.prepStatement2.setString(3, "");
this.prepStatement2.executeUpdate();
this.connection2.commit();
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e, "SQLException", 1);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
}
Thread.sleep(10L);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (HeadlessException|InterruptedException e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void SplitFrames(String Frame)
{
int NumSplit = Frame.length() / this.Max_Farme_Size;
for (int i = 0; i <= NumSplit; i++) {
if (i < NumSplit)
{
String part = Frame.substring(i * this.Max_Farme_Size, i * this.Max_Farme_Size + this.Max_Farme_Size);
String IntermdiateFrame = this.STX + this.FIndex + part + this.ETB + GetCheckSum(new StringBuilder().append(this.FIndex).append(part).append(this.ETB).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), IntermdiateFrame);
NextFIndexNo();
}
else
{
String part = Frame.substring(i * this.Max_Farme_Size);
String LastFrame = this.STX + this.FIndex + part + this.ETX + GetCheckSum(new StringBuilder().append(this.FIndex).append(part).append(this.ETX).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), LastFrame);
NextFIndexNo();
}
}
}
public void NextFIndexNo()
{
this.FIndex += 1;
if (this.FIndex > 7) {
this.FIndex = 0;
}
}
public void SendOrder(String[] OrderFrame)
{
this.DataToSend.clear();
this.DataToSend.add(0, this.ENQ);
for (int i = 0; i < OrderFrame.length; i++) {
if (OrderFrame[i].length() > this.Max_Farme_Size)
{
SplitFrames(OrderFrame[i]);
}
else
{
String SingleFrame = this.STX + this.FIndex + OrderFrame[i] + this.ETX + GetCheckSum(new StringBuilder().append(this.FIndex).append(OrderFrame[i]).append(this.ETX).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), SingleFrame);
NextFIndexNo();
}
}
}
public void SendOrderData(String SampleData, String TestCodes)
{
HeaderRecord HRec = new HeaderRecord();
PatientRecord PRec = new PatientRecord();
OrderRecord ORec = new OrderRecord();
MessageTerminatorRecord LRec = new MessageTerminatorRecord();
PRec.SetPropertyValue("PracticePatientID", SampleData);
PRec.SetPropertyValue("LabPatientID", SampleData);
PRec.SetPropertyValue("PatientSex", "M");
ORec.SetPropertyValue("SampleID", SampleData);
ORec.SetPropertyValue("ActionCode", "N");
ORec.SetPropertyValue("UniversalTestID", "^^^" + TestCodes.replace(",", "\\^^^"));
ORec.SetPropertyValue("SampleType", "Serum");
ORec.SetPropertyValue("ReportTypes", "O");
String[] records = new String[4];
records[0] = HRec.FormatFrame();
records[1] = PRec.FormatFrame();
records[2] = ORec.FormatFrame();
records[3] = LRec.FormatFrame();
String Msg = HRec.FormatFrame() + PRec.FormatFrame() + ORec.FormatFrame() + LRec.FormatFrame();
System.out.println(">>>>>>>>" + Msg);
try
{
SendOrder(records);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void FramesReady(String[] Frame)
{
}
public void ManageData()
{
try
{
if (this.CommData.contains(this.ENQ))
{
SaveData(this.CommData);
this.CommData = "";
this.out.write(this.ACK);
this.out.flush();
}
else if (this.CommData.contains(this.CRLF))
{
SaveData(this.CommData);
if ((CheckSumCorrect()) && (CheckFarmeNum()))
{
this.TextData += GetFrameData(this.CommData, 2);
this.CommData = "";
this.out.write(this.ACK);
this.out.flush();
}
else if ((!CheckSumCorrect()) || (!CheckFarmeNum()))
{
this.CommData = "";
this.out.write(this.NAK);
this.out.flush();
}
}
else if (this.CommData.contains(this.EOT))
{
SaveData(this.CommData);
String[] x = ParseFrames(this.TextData);
FramesReady(x);
this.TextData = "";
this.FrameNo = 1;
this.CommData = "";
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void Server()
{
try
{
for (;;)
{
char c = (char)this.in.read();
System.out.print(c);
this.CommData += c;
ManageData();
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public static void main(String[] args)
throws Exception
{
switch (Setting.GetPropVal("Socket"))
{
case "TCPIP":
String IP = Setting.GetPropVal("IPaddress");
int Port2Rec = Integer.parseInt(Setting.GetPropVal("INport"));
InetAddress addr = InetAddress.getByName(IP);
String host = addr.getHostName();
Socket s = new Socket(host, Port2Rec);
System.out.println("Connected to :" + host + "/" + Port2Rec);
Access2 TcpChat = new Access2(s);
TcpChat.Server();
break;
case "Serial":
SerialPort serialPort = null;
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier)portList.nextElement();
if ((portId.getPortType() == 1) &&
(portId.getName().equals(Setting.GetPropVal("ComPort"))))
{
serialPort = (SerialPort)portId.open("HPS", 10);
serialPort.setSerialPortParams(9600, 8, 1, 0);
}
}
System.out.println("Connected to :" + serialPort.getName());
Access2 SerialChat = new Access2(serialPort);
SerialChat.Server();
}
}
}
when i run the program from eclipse
"Wrong Path OR file Lost" is shown
public class Setting
{
public static Properties props;
public static String propVal;
public static String GetPropVal(String param)
{
try
{
props = new Properties();
props.load(new FileInputStream("Access2.ini"));
propVal = props.getProperty(param);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "Wrong Path OR file Lost", "Alert", 1);
System.exit(0);
}
return propVal;
}
}
how can i solve that ? It said my class is not found but it exist what is the solution ?
This happens because of improper packaging of class files or rather, improper compilation of Java files inside a package.
Go for a build tool such as Maven with a clean directory including Java files and then generate a .jar.
Basically, if you can, create a fresh Maven or Ant project and create Java files with same names and paste the content into new ones, one by one.
EDIT: Make sure that there is only ONE public class in the main package.
I have JFrame with a start button, which triggers the calculation of a Julia Set.
The code that is executed when the start button is clicked is as follows:
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.handleCalculation();
}
else if (aActionEvent.getSource() == m_cTReal)
Which used to work fine, except that the application could not be closed anymore. So I tried to use m_bRunning in a separate method so that actionPerformed() isn't blocked all the time to see if that would help, and then set m_bRunning = false in the method stop() which is called when the window is closed:
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
The method run() is called from the main class in a while(true) loop.
Yet unfortunately, neither did that solve the problem, nor do I now have any output to the canvas or any debug traces with System.out.println(). Could anyone point me in the right direction on this?
EDIT:
Here are the whole files:
// cMain.java
package juliaSet;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
public class cMain {
public static void main(String[] args)
{
int windowWidth = 1000;//(int)screenSize.getWidth() - 200;
int windowHeight = 800;//(int)screenSize.getHeight() - 50;
int plotWidth = 400;//(int)screenSize.getWidth() - 600;
int plotHeight = 400;//(int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
while(true)
{
cJuliaSet.run();
}
}
}
// JuliaSet.java
package juliaSet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;
import java.io.*;
import java.lang.ref.*;
public class JuliaSet extends JFrame implements ActionListener
{
private JButton m_cBStart;
private JTextField m_cTReal;
private JTextField m_cTImag;
private JTextField m_cTDivergThresh;
private JLabel m_cLReal;
private JLabel m_cLImag;
private JLabel m_cLDivergThresh;
private int m_iDivergThresh = 10;
private String m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
private JuliaCanvas m_cCanvas;
private int m_iPlotWidth; // number of cells
private int m_iPlotHeight; // number of cells
private Boolean m_bRunning = false;
private double m_dReal = 0.3;
private double m_dImag = -0.5;
private String m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
private String m_cMsgIter = "x = 0, y = 0";
private Complex m_cCoordPlane[][];
private double m_dAbsSqValues[][];
private int m_iIterations[][];
private Complex m_cSummand;
private BufferedImage m_cBackGroundImage = null;
private FileWriter m_cFileWriter;
private BufferedWriter m_cBufferedWriter;
private String m_sFileName = "log.txt";
private Boolean m_bWriteLog = false;
private static final double PLOTMAX = 2.0; // we'll have symmetric axes
// ((0,0) at the centre of the
// plot
private static final int MAXITER = 0xff;
JuliaSet(String aTitle, int aFrameWidth, int aFrameHeight, int aPlotWidth, int aPlotHeight)
{
super(aTitle);
this.setSize(aFrameWidth, aFrameHeight);
m_iPlotWidth = aPlotWidth;
m_iPlotHeight = aPlotHeight;
m_cSummand = new Complex(m_dReal, m_dImag);
m_cBackGroundImage = new BufferedImage(aFrameWidth, aFrameHeight, BufferedImage.TYPE_INT_RGB);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
stop();
super.windowClosing(e);
System.exit(0);
}
});
GridBagLayout cLayout = new GridBagLayout();
GridBagConstraints cConstraints = new GridBagConstraints();
this.setLayout(cLayout);
m_cCanvas = new JuliaCanvas(m_iPlotWidth, m_iPlotHeight);
m_cCanvas.setSize(m_iPlotWidth, m_iPlotHeight);
m_cBStart = new JButton("Start");
m_cBStart.addActionListener(this);
m_cTReal = new JTextField(5);
m_cTReal.addActionListener(this);
m_cTImag = new JTextField(5);
m_cTImag.addActionListener(this);
m_cTDivergThresh = new JTextField(5);
m_cTDivergThresh.addActionListener(this);
m_cLReal = new JLabel("Re(c):");
m_cLImag = new JLabel("Im(c):");
m_cLDivergThresh = new JLabel("Divergence Threshold:");
cConstraints.insets.top = 3;
cConstraints.insets.bottom = 3;
cConstraints.insets.right = 3;
cConstraints.insets.left = 3;
// cCanvas
cConstraints.gridx = 0;
cConstraints.gridy = 0;
cLayout.setConstraints(m_cCanvas, cConstraints);
this.add(m_cCanvas);
// m_cLReal
cConstraints.gridx = 0;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cLReal, cConstraints);
this.add(m_cLReal);
// m_cTReal
cConstraints.gridx = 1;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cTReal, cConstraints);
this.add(m_cTReal);
// m_cLImag
cConstraints.gridx = 0;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cLImag, cConstraints);
this.add(m_cLImag);
// m_cTImag
cConstraints.gridx = 1;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cTImag, cConstraints);
this.add(m_cTImag);
// m_cLDivergThresh
cConstraints.gridx = 0;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cLDivergThresh, cConstraints);
this.add(m_cLDivergThresh);
// m_cTDivergThresh
cConstraints.gridx = 1;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cTDivergThresh, cConstraints);
this.add(m_cTDivergThresh);
// m_cBStart
cConstraints.gridx = 0;
cConstraints.gridy = 4;
cLayout.setConstraints(m_cBStart, cConstraints);
this.add(m_cBStart);
if (m_bWriteLog)
{
try
{
m_cFileWriter = new FileWriter(m_sFileName, false);
m_cBufferedWriter = new BufferedWriter(m_cFileWriter);
} catch (IOException ex) {
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
this.repaint();
this.transformCoordinates();
}
public synchronized void stop()
{
if (m_bRunning)
{
m_bRunning = false;
boolean bRetry = true;
}
if (m_bWriteLog)
{
try {
m_cBufferedWriter.close();
m_cFileWriter.close();
} catch (IOException ex) {
System.out.println("Error closing file '" + m_sFileName + "'");
}
}
}
public void collectGarbage()
{
Object cObj = new Object();
WeakReference ref = new WeakReference<Object>(cObj);
cObj = null;
while(ref.get() != null) {
System.gc();
}
}
public void setSummand(Complex aSummand)
{
m_cSummand.setIm(aSummand.getIm());
m_dImag = aSummand.getIm();
m_cSummand.setRe(aSummand.getRe());
m_dReal = aSummand.getRe();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
}
public void paint(Graphics aGraphics)
{
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
this.paintComponents(aGraphics);
// drawString() calls are debug code only....
aGraphics.setColor(Color.BLACK);
aGraphics.drawString(m_cSMsg, 10, 450);
aGraphics.drawString(m_cMsgIter, 10, 465);
aGraphics.drawString(m_cMsgDivThresh, 10, 480);
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 0, 0, null);
}
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
}
else if (aActionEvent.getSource() == m_cTReal)
{
m_dReal = Double.parseDouble(m_cTReal.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setRe(m_dReal);
}
else if (aActionEvent.getSource() == m_cTImag)
{
m_dImag = Double.parseDouble(m_cTImag.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setIm(m_dImag);
}
else if (aActionEvent.getSource() == m_cTDivergThresh)
{
m_iDivergThresh = Integer.parseInt(m_cTDivergThresh.getText());
m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
}
this.update(this.getGraphics());
}
public void transformCoordinates()
{
double dCanvasHeight = (double) m_cCanvas.getHeight();
double dCanvasWidth = (double) m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_cCoordPlane = new Complex[(int) dCanvasHeight][(int) dCanvasWidth];
double iPlotRange = 2 * PLOTMAX;
for (int i = 0; i < dCanvasHeight; i++)
{
for (int j = 0; j < dCanvasWidth; j++)
{
m_cCoordPlane[i][j] = new Complex((i - (dCanvasWidth / 2)) * iPlotRange / dCanvasWidth,
(j - (dCanvasHeight / 2)) * iPlotRange / dCanvasHeight);
}
}
}
public void calcAbsSqValues()
{
int iCanvasHeight = m_cCanvas.getHeight();
int iCanvasWidth = m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_dAbsSqValues = new double[iCanvasHeight][iCanvasWidth];
m_iIterations = new int[iCanvasHeight][iCanvasWidth];
Complex cSum = new Complex();
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write("m_iIterations[][] =");
m_cBufferedWriter.newLine();
}
catch (IOException ex)
{
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
for (int i = 0; i < iCanvasHeight; i++)
{
for (int j = 0; j < iCanvasWidth; j++)
{
cSum.setRe(m_cCoordPlane[i][j].getRe());
cSum.setIm(m_cCoordPlane[i][j].getIm());
m_iIterations[i][j] = 0;
do
{
m_iIterations[i][j]++;
cSum.square();
cSum.add(m_cSummand);
m_dAbsSqValues[i][j] = cSum.getAbsSq();
} while ((m_iIterations[i][j] < MAXITER) && (m_dAbsSqValues[i][j] < m_iDivergThresh));
this.calcColour(i, j, m_iIterations[i][j]);
m_cMsgIter = "x = " + i + " , y = " + j;
if(m_bWriteLog)
{
System.out.println(m_cMsgIter);
System.out.flush();
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write(Integer.toString(m_iIterations[i][j]));
m_cBufferedWriter.write(" ");
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.newLine();
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
m_dAbsSqValues = null;
m_iIterations = null;
cSum = null;
}
private void calcColour(int i, int j, int aIterations)
{
Color cColour = Color.getHSBColor((int) Math.pow(aIterations, 4), 0xff,
0xff * ((aIterations < MAXITER) ? 1 : 0));
m_cCanvas.setPixelColour(i, j, cColour);
cColour = null;
}
private void handleCalculation()
{
Complex cSummand = new Complex();
for(int i = -800; i <= 800; i++)
{
for(int j = -800; j <= 800; j++)
{
cSummand.setRe(((double)i)/1000.0);
cSummand.setIm(((double)j)/1000.0);
this.setSummand(cSummand);
this.calcAbsSqValues();
this.getCanvas().paint(m_cCanvas.getGraphics());
this.paint(this.getGraphics());
}
}
cSummand = null;
this.collectGarbage();
System.gc();
System.runFinalization();
}
public boolean isRunning()
{
return m_bRunning;
}
public void setRunning(boolean aRunning)
{
m_bRunning = aRunning;
}
public Canvas getCanvas()
{
return m_cCanvas;
}
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
}
class JuliaCanvas extends Canvas
{
private int m_iWidth;
private int m_iHeight;
private Random m_cRnd;
private BufferedImage m_cBackGroundImage = null;
private int m_iRed[][];
private int m_iGreen[][];
private int m_iBlue[][];
JuliaCanvas(int aWidth, int aHeight)
{
m_iWidth = aWidth;
m_iHeight = aHeight;
m_cRnd = new Random();
m_cRnd.setSeed(m_cRnd.nextLong());
m_cBackGroundImage = new BufferedImage(m_iWidth, m_iHeight, BufferedImage.TYPE_INT_RGB);
m_iRed = new int[m_iHeight][m_iWidth];
m_iGreen = new int[m_iHeight][m_iWidth];
m_iBlue = new int[m_iHeight][m_iWidth];
}
public void init() {
}
public void setPixelColour(int i, int j, Color aColour)
{
m_iRed[i][j] = aColour.getRed();
m_iGreen[i][j] = aColour.getGreen();
m_iBlue[i][j] = aColour.getBlue();
}
private int getRandomInt(double aProbability)
{
return (m_cRnd.nextDouble() < aProbability) ? 1 : 0;
}
#Override
public void paint(Graphics aGraphics)
{
// store on screen graphics
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
for (int i = 0; i < m_iWidth; i++)
{
for (int j = 0; j < m_iHeight; j++)
{
Color cColor = new Color(m_iRed[i][j], m_iGreen[i][j], m_iBlue[i][j]);
aGraphics.setColor(cColor);
aGraphics.drawRect(i, j, 0, 0);
cColor = null;
}
}
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 1, 1, null);
}
#Override
public void update(Graphics aGraphics)
{
paint(aGraphics);
}
}
class Complex {
private double m_dRe;
private double m_dIm;
public Complex()
{
m_dRe = 0;
m_dIm = 0;
}
public Complex(double aRe, double aIm)
{
m_dRe = aRe;
m_dIm = aIm;
}
public Complex(Complex aComplex)
{
m_dRe = aComplex.m_dRe;
m_dIm = aComplex.m_dIm;
}
public double getRe() {
return m_dRe;
}
public void setRe(double adRe)
{
m_dRe = adRe;
}
public double getIm() {
return m_dIm;
}
public void setIm(double adIm)
{
m_dIm = adIm;
}
public void add(Complex acComplex)
{
m_dRe += acComplex.getRe();
m_dIm += acComplex.getIm();
}
public void square()
{
double m_dReSave = m_dRe;
m_dRe = (m_dRe * m_dRe) - (m_dIm * m_dIm);
m_dIm = 2 * m_dReSave * m_dIm;
}
public double getAbsSq()
{
return ((m_dRe * m_dRe) + (m_dIm * m_dIm));
}
}
I'm quoting a recent comment from #MadProgrammer (including links)
"Swing is single threaded, nothing you can do to change that, all events are posted to the event queue and processed by the Event Dispatching Thread, see Concurrency in Swing for more details and have a look at Worker Threads and SwingWorker for at least one possible solution"
There is only one thread in your code. That thread is busy doing the calculation and can not respond to events located in the GUI. You have to separate the calculation in another thread that periodically updates the quantities that appears in the window. More info about that in the links, courtesy of #MadProgrammer, I insist.
UPDATED: As pointed by #Yusuf, the proper way of launching the JFrame is
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
}
});
Set the frame visible on construction and start calculation when the start button is pressed.
First;
Endless loop is not a proper way to do this. This part is loops and taking CPU and never give canvas to refresh screen. if you add below code your code will run as expected. but this is not the proper solution.
cMain.java:
while (true) {
cJuliaSet.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Second: you could call run method when start button clicked. But you should create a thread in run method to not freeze screen.
public static void main(String[] args) {
int windowWidth = 1000;// (int)screenSize.getWidth() - 200;
int windowHeight = 800;// (int)screenSize.getHeight() - 50;
int plotWidth = 400;// (int)screenSize.getWidth() - 600;
int plotHeight = 400;// (int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
//While loop removed
}
actionPerformed:
if (strCmd.equals("Start")) {
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.run(); // added call run method.
} else if (aActionEvent.getSource() == m_cTReal) {
run method:
public void run()
{
if(m_bRunning)
{
new Thread(){ //Thread to release screen
#Override
public void run() {
JuliaSet.this.handleCalculation();
}
}.start(); //also thread must be started
}
}
As said by #RubioRic, SwingUtilities.invokeLater method is also a part of solution. But you need to check whole of your code and you should learn about Threads.
i'm having trouble from fetching data from my TimerCan class. like String and integers.
i have a method(static method) for getting this data and set it to another class. but every time i run my program i always get NULLPOINTEREXCEPTION in line..
if(opp.equalsIgnoreCase("incrementing")){///heree
startTimer();
if(hour[current]==hhh&&min[current]==mmm&&sec[current]==sss)
{
this.start = false;
this.stop = true;
this.timer.cancel();
}
else if(opp.equalsIgnoreCase("decrementing")){
startTimerD();
if(hour[current]==0&&min[current]==0&&sec[current]==0)
{
this.start = false;
this.stop = true;
this.timer.cancel();
and heres the full code my TimerCan class
public class TimerCan extends Canvas
{
private Timer timer;
private Midlet myMid;
private Player z;
private int hour[],sec[],min[],msec[],maxX,maxY,current,length,x,y;
private String time,opp;
private int strWid,hhh,mmm,sss;
private int strht;
private boolean start;
private boolean stop;
public Image img;
Data data;
public TimerCan(Midlet midlet)
{
this.myMid= midlet;
data = new Data();
opp=data.getData();
hhh=data.getDatah();
mmm=data.getDatam();
sss=data.getDatas();
try
{
this.maxX = this.getWidth();
this.maxY = this.getHeight();
this.current = 0;
this.hour = new int[30];
this.min = new int[30];
this.sec = new int[30];
this.msec = new int[30];
this.start = false;
this.stop = true;
for(int j = 0 ; j <= 30 ; j++)
{
this.hour[j] = 0;
this.min[j] = 0;
this.sec[j] = 0;
this.msec[j] = 0;
}
}catch(Exception e)
{}
}
public void paint(Graphics g)
{
Font font = Font.getFont(0,1,16);
this.strWid = font.stringWidth("this.time");
this.strht = font.getHeight();
if(hour[current] < 10)
{
time = "0"+String.valueOf(this.hour[current])+":";
}
else
{
time = String.valueOf(this.hour[current]) + ":";
}
if(min[current] < 10)
{
time = time+"0"+String.valueOf(this.min[current]) + ":";
}
else
{
time = time+String.valueOf(this.min[current]) + ":";
}
if(sec[current] < 10)
{
time = time+"0"+String.valueOf(this.sec[current]) + ":";
}
else
{
time = time + String.valueOf(this.sec[current]) + ":";
}
if(msec[current] < 10)
{
time = time+"0"+String.valueOf(this.msec[current]);
}
else
{
time = time+String.valueOf(this.msec[current]);
}
this.strWid = font.stringWidth(time);
this.length = this.maxX - this.strWid;
this.length /= 2;
try{
img = Image.createImage("/picture/aa.png");
}
catch(Exception error){
}
x = this.getWidth()/2;
y = this.getHeight()/2;
g.setColor(63,155,191);
g.fillRect(0,0,maxX, maxY);
g.drawImage(img, x, y, Graphics.VCENTER | Graphics.HCENTER);
g.setColor(0,0,0) ;
g.drawString(time,length+15,150,Graphics.TOP|Graphics.LEFT);
}
private void startTimer()
{
TimerTask task = new TimerTask()
{
public void run()
{
msec[current]++ ;
if(msec[current] == 100)
{
msec[current] = 0 ;
sec[current]++ ;
}
else if(sec[current] ==60)
{
sec[current] = 0 ;
min[current]++ ;
}
else if(min[current] == 60)
{
min[current] = 0 ;
hour[current]++ ;
}
else if(hour[current] == 24)
{
hour[current] = 0 ;
}
repaint();
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task,10,10) ;
}
private void startTimerD()
{
TimerTask task = new TimerTask()
{
public void run()
{
msec[current]-- ;
if(msec[current] == 0)
{
msec[current] = 100 ;
sec[current]-- ;
}
else if(sec[current] ==0)
{
sec[current] = sss;
min[current]--;
}
else if(min[current] == 0)
{
min[current] =mmm;
hour[current]--;
}
else if(hour[current] == 0)
{
hour[current] = hhh;
}
repaint();
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task,10,10) ;
}
protected void keyPressed(int keyCode)
{
if(keyCode == Canvas.KEY_NUM1)
{
if(this.start == false)
{
this.start=true;
this.stop=false;
}
else if(this.stop == false)
{
this.start = false ;
this.stop = true ;
this.timer.cancel();
}
if(start == true)
{
check();
}
}
if(keyCode == Canvas.KEY_NUM2)
{
this.min[current]=0;
this.sec[current]=0;
this.msec[current]=0;
this.start = false;
this.stop = true;
this.timer.cancel();
try{
z.deallocate();
}
catch(Exception e){}
repaint();
}
if(keyCode == Canvas.KEY_NUM3)
{
if(this.stop == false)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
}
if(keyCode==Canvas.KEY_NUM0)
{
try{
z.deallocate();
}
catch(Exception e){}
myMid.exit();
}
}
public void check()
{
if(opp.equalsIgnoreCase("incrementing")){
startTimer();
if(hour[current]==hhh&&min[current]==mmm&&sec[current]==sss)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
}
else if(opp.equalsIgnoreCase("decrementing")){
startTimerD();
if(hour[current]==0&&min[current]==0&&sec[current]==0)
{
this.start = false;
this.stop = true;
this.timer.cancel();
try{
InputStream inss = getClass().getResourceAsStream("alarm.wav");
InputStreamReader iis= new InputStreamReader(inss);
z = Manager.createPlayer(inss,"audio/x-wav");
z.prefetch();
z.setLoopCount(2);
z.start();
}
catch(Exception e){
}
}
and heres the Data classs
public class Data{
String nameD;
int hhD;
int mmD;
int ssD;
public void setData(String name){
this.nameD = name;
}
public String getData(){
return this.nameD;
}
//hour
public void setDatah(int hhh){
this.hhD = hhh;
}
public int getDatah(){
return this.hhD;
}
//
public void setDatam(int hhh){
this.mmD = hhh;
}
public int getDatam(){
return this.mmD;
}
//
public void setDatas(int sss){
this.ssD = sss;
}
public int getDatas(){
return this.ssD;
}
}
You wrote
data = new Data();
in your TimerCan class. This made a Data object that didn't have nameD set to anything; so when you wrote
opp = data.getData()
later, you were setting opp to null - that is, there wasn't actually an object referenced by opp. When you wrote
if (opp.equalsIgnoreCase("incrementing"))
this caused a problem. You can't call a method, when the object that you're trying to call it on is absent.
If it's legitimate for opp to be null, but you still have code that you want to run when opp is "incrementing" you can write it like this.
if (opp != null && opp.equalsIgnoreCase("incrementing"))
which will check whether opp is null before it calls the equalsIgnoreCase method - and you won't get the NullPointerException.
This happens because you have not initialized variable data, so it remains null. This is the obvious reason of NullPointerException.
You have to call data = new Data(); prior using it.
I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.
I am learning how to use Java and I want to make a text scroller for my website.
I have found a similar scroller that I want to add but I want to look at the code to see how it was done.
The applet can be found here: http://www.javascriptkit.com/java/java20.shtml
The problem is when I try to open the class file within notepad the encoding or text shows up with strange characters instead of showing me the code.
Please can someone let me know if there is any possible way of me seeing the code for this class.
Thanks
That is a class file meaning it is compiled code so you can not see it's source.
In order to see the source, you need the .java file which is the file which you compile to get the byte code.
It seems the site is just providing the compiled class, and you never know using it they might have some hidden functionality in the class as well e.g to send information to the owner servers etc.
EDIT:
So here is the de-compiled code of applet written by ProScroll version 2.3 by Slava Pestov
import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
public class ProScroll extends Applet
implements Runnable
{
private Thread thread;
private Image image;
private int scrollLength;
private int scrolled;
private int speed = 10;
private int imgsWidth;
private URL url;
private String target;
private Color bgColor;
public void init()
{
int i = 12; int j = 0;
String str2 = getParameter("TEXT");
String str3 = getParameter("TEXTURL");
if ((str2 == null) && (str3 == null)) {
str2 = "No TEXT or TEXTURL parameter specified";
}
if (str3 != null)
{
localObject = new StringBuffer();
try
{
InputStream localInputStream = new URL(str3)
.openConnection().getInputStream();
while (true)
{
int k = localInputStream.read();
if (k == -1) break;
if (k != 10) {
if (k == 9) { ((StringBuffer)localObject).append(' '); continue; }
((StringBuffer)localObject).append((char)k);
}
}
localInputStream.close();
str2 = ((StringBuffer)localObject).toString();
}
catch (Exception localException1)
{
if (str2 == null) {
str2 = "Error loading text from URL: " + localException1;
}
}
}
String str1 = getParameter("FONT");
if (str1 == null) str1 = "TimesRoman";
this.target = getParameter("TARGET");
if (this.target == null) this.target = "_self";
try
{
i = Integer.parseInt(getParameter("SIZE"));
}
catch (Exception localException2)
{
}
Object localObject = getParameter("STYLE");
if ("bold".equals(localObject)) j = 1;
else if ("italic".equals(localObject)) j = 2;
else if ("bolditalic".equals(localObject)) j = 3;
String str4 = getParameter("SPEED");
if ("slow".equals(str4)) this.speed = 20;
else if ("medium".equals(str4)) this.speed = 15; else {
this.speed = 10;
}
try
{
this.url = new URL(getDocumentBase(), getParameter("URL"));
}
catch (Exception localException3)
{
}
this.bgColor = parseColorName(getParameter("BGCOLOR"), Color.black);
Enumeration localEnumeration = parseAndLoadImages(getParameter("IMAGES"));
Font localFont = new Font(str1, j, i);
FontMetrics localFontMetrics = getToolkit().getFontMetrics(localFont);
this.image = createImage(localFontMetrics.stringWidth(str2) + this.imgsWidth + size().width, size().height);
this.scrolled = (-size().width);
parseAndDrawText(this.image.getGraphics(), str2, localFontMetrics, localFont, localEnumeration);
}
private void parseAndDrawText(Graphics paramGraphics, String paramString, FontMetrics paramFontMetrics, Font paramFont, Enumeration paramEnumeration)
{
paramGraphics.setFont(paramFont);
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, this.image.getWidth(this), this.image.getHeight(this));
paramGraphics.setColor(Color.white);
StringBuffer localStringBuffer = new StringBuffer();
int i = 0; int j = 0;
for (int k = 0; k < paramString.length(); k++)
{
char c = paramString.charAt(k);
if ((c == '#') && (j == 0))
{
if (i != 0)
{
paramGraphics.setColor(parseColorName(localStringBuffer.toString(), Color.white));
localStringBuffer.setLength(0);
i = 0;
}
else
{
i = 1;
}
}
else if ((c == '$') && (i == 0) && (j == 0))
{
try
{
Image localImage = (Image)paramEnumeration.nextElement();
paramGraphics.drawImage(localImage, this.scrollLength, 0, this);
this.scrollLength += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
else if ((c == '/') && (j == 0))
{
j = 1;
}
else if (i != 0)
{
localStringBuffer.append(c);
}
else
{
if (j == 1) j = 0;
paramGraphics.drawString(String.valueOf(c), this.scrollLength, paramFontMetrics.getAscent());
this.scrollLength += paramFontMetrics.charWidth(c);
}
}
}
private Color parseColorName(String paramString, Color paramColor)
{
if ("red".equals(paramString)) return Color.red;
if ("green".equals(paramString)) return Color.green;
if ("blue".equals(paramString)) return Color.blue;
if ("yellow".equals(paramString)) return Color.yellow;
if ("orange".equals(paramString)) return Color.orange;
if ("white".equals(paramString)) return Color.white;
if ("lightGray".equals(paramString)) return Color.lightGray;
if ("gray".equals(paramString)) return Color.gray;
if ("darkGray".equals(paramString)) return Color.darkGray;
if ("black".equals(paramString)) return Color.black;
if ("cyan".equals(paramString)) return Color.cyan;
if ("magenta".equals(paramString)) return Color.magenta;
if ("pink".equals(paramString)) return Color.pink;
return paramColor;
}
private Enumeration parseAndLoadImages(String paramString)
{
if (paramString == null) return null;
int i = 0;
Vector localVector = new Vector();
StringTokenizer localStringTokenizer = new StringTokenizer(paramString);
MediaTracker localMediaTracker = new MediaTracker(this);
while (localStringTokenizer.hasMoreTokens())
{
try
{
Image localImage = getImage(new URL(getDocumentBase(), localStringTokenizer.nextToken()));
localVector.addElement(localImage);
localMediaTracker.addImage(localImage, i);
localMediaTracker.waitForID(i++);
this.imgsWidth += localImage.getWidth(this);
}
catch (Exception localException)
{
}
}
return localVector.elements();
}
public void start()
{
this.thread = new Thread(this);
this.thread.start();
}
public void stop()
{
this.thread = null;
this.scrolled = (-size().width);
}
public void run()
{
while (Thread.currentThread() == this.thread)
{
long l = System.currentTimeMillis();
if (++this.scrolled > this.scrollLength) this.scrolled = (-size().width);
repaint();
try
{
Thread.sleep(Math.max(this.speed - (System.currentTimeMillis() - l), 0L));
}
catch (InterruptedException localInterruptedException)
{
}
}
}
public boolean mouseEnter(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("Link: " + this.url.toString());
return true;
}
public boolean mouseExit(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showStatus("");
return true;
}
public boolean mouseUp(Event paramEvent, int paramInt1, int paramInt2)
{
if (this.url != null) getAppletContext().showDocument(this.url, this.target);
return true;
}
public void update(Graphics paramGraphics)
{
paramGraphics.setColor(this.bgColor);
if (this.scrolled < 0)
{
paramGraphics.setColor(this.bgColor);
paramGraphics.fillRect(0, 0, -this.scrolled, size().height);
}
paramGraphics.drawImage(this.image, -this.scrolled, 0, this);
}
public void paint(Graphics paramGraphics)
{
update(paramGraphics);
}
public String getAppletInfo()
{
return "ProScroll version 2.3 by Slava Pestov";
}
}
a java .class file is a compiled file that you cannot read with notepad.
if you want the source code you should try to ask it to the author of the article or you could decompile it.