SlideShare a Scribd company logo
1 of 13
Download to read offline
Implement threads and a GUI interface using advanced Java Swing classes.
Required data structure - the advanced data structure uses implementation of a multi-tree with
the following levels: Cave - level 0 Party - Level 1 Creature - Level 2 Artifacts - Level 3
Treasures - Level 3 Jobs
Use the Swing class JTree effectively to display the contents of the data file. Implement a JTable
to also show the contents of the data file.
Threads: Implement a thread for each job representing a task that creature will perform. Use the
synchronize directive to avoid race conditions and insure that a creature is performing only one
job at a time. The thread for each job should be started as the job is read in from the data file.
Only one job should be progressing for each creature at any moment. Use delays to show the
creature doing the task.
Use a JProgressBar for each creature to show the creature performing the task. Use JButton's on
the Job panel to allow the task to be suspended and cancelled. The GUI elements should be
distinct from the other classes in the program.
Solution
Please find the code below for the above problem :
import java.util.ArrayList;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Random;
import java.io.File;
import java.io.FileNotFoundException;
import javax.swing.JProgressBar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Cave2 {
ArrayList parties = new ArrayList (); // the parties
ArrayList loners = new ArrayList (); // creatures not in parties
ArrayList drops = new ArrayList (); // Treasures not carried
ArrayList magics = new ArrayList (); // Artifacts not carried
ArrayList jobs = new ArrayList (); // Jobs to be performed
JFrame jf = new JFrame ();
JPanel jrun = new JPanel ();
JTextArea jta = new JTextArea (10, 10);
// hashmap of everything by index
HashMap hmElements = new HashMap ();
public Cave2 () {
Scanner sf = null;
String fileName = "dataC.txt";
try {
// sf = new Scanner (new File (fileName));
// getResourceAsStream is the way to access a data file in a jar package file
// this works in general, so leave it here as is.
sf = new Scanner (getClass().getResourceAsStream (fileName));
}
catch (Exception e) {
System.out.println (e + " File bummer: " + fileName);
} // end open file try/catch block
if (sf == null)
return;
readFile (sf);
jta.setText (toString ());
jf.setTitle ("Cave2");
jf.add (jrun, BorderLayout.PAGE_END);
jrun.setLayout (new GridLayout (0, 5, 2, 5));
jf.add (new JScrollPane (jta), BorderLayout.CENTER);
jta.setFont (new Font ("Monospaced", 0, 12));
jf.pack ();
jf.setVisible (true);
jf.setLocationRelativeTo (null);
} // end no-parameter constructor
public static void main (String args []) {
Cave2 cv = new Cave2 ();
cv.jf.add (new JLabel (" Close this window to end program "),
BorderLayout.PAGE_START);
cv.jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// System.out.println (cv);
} // end main
public String toString () {
String sb = "";
sb += toString (parties, "Party List");
sb += toString (loners , "Unaligned Creatures");
sb += toString (drops , "Unheld Treasures");
sb += toString (magics , "Unheld Artifacts");
sb += toString (jobs , "Jobs");
// sb += toString (hmElements.values (), "HashMap");
return sb;
} // end method dump
String toString (Iterable it, String label) {
String sb = " ----- DUMP " + label + " -------";
for (CaveElement c: it)
sb += " " + c.toString ();
return sb;
} // end method dump Iterable String
void readFile (Scanner sf) {
String inline;
Scanner line;
while (sf.hasNext()) {
inline = sf.nextLine().trim();
if (inline.length() == 0) continue;
line = new Scanner (inline).useDelimiter ("s*:s*"); // compress white space also, else
nextInt fails
switch (inline.charAt (0)) {
case 'p': addParty (line); break;
case 'c': addCreature (line); break;
case 't': addTreasure (line); break;
case 'a': addArtifact (line); break;
case 'j': addJob (line); break;
} // end switch
} // end while reading data file
jf.pack ();
} // end readFile
public void addJob (Scanner sc) {
Job job = new Job (hmElements, jrun, sc);
// (new Thread (job)).start();
// jobs.add (job);
} // end method addJob
public void addParty (Scanner sc){
Party pt = new Party (sc);
parties.add (pt);
hmElements.put (pt.index, pt);
} // end method addParty
public void addCreature (Scanner sc) {
Creature c = new Creature ();
int target = c.makeCreature (sc);
Party p = (Party)(hmElements.get (target));
if (p == null)
loners.add (c);
else {
p.addCreature (c);
c.party = p;
}
hmElements.put (c.index, c);
} // end method addToParty
public void addTreasure (Scanner sc) {
Treasure t = new Treasure ();
int target = t.makeTreasure (sc);
Creature c = (Creature)(hmElements.get (target));
if (c == null)
drops.add (t);
else {
c.addTreasure (t);
t.holder = c;
}
hmElements.put (t.index, t);
} // end method addTreasure
public void addArtifact (Scanner sc) {
Artifact a = new Artifact ();
int target = a.makeArtifact (sc);
Creature c = (Creature)(hmElements.get (target));
if (a == null)
magics.add (a);
else {
c.addArtifact (a);
a.holder = c;
}
hmElements.put (a.index, a);
} // end method addArtifact
} // end class Cave
class CaveElement {}
// j::::[::]*
class Job extends CaveElement implements Runnable {
static Random rn = new Random ();
JPanel parent;
Creature worker = null;
int jobIndex;
long jobTime;
String jobName = "";
JProgressBar pm = new JProgressBar ();
boolean goFlag = true, noKillFlag = true;
JButton jbGo = new JButton ("Stop");
JButton jbKill = new JButton ("Cancel");
Status status = Status.SUSPENDED;
enum Status {RUNNING, SUSPENDED, WAITING, DONE};
public Job (HashMap hmElements, JPanel cv, Scanner sc) {
parent = cv;
sc.next (); // dump first field, j
jobIndex = sc.nextInt ();
jobName = sc.next ();
int target = sc.nextInt ();
worker = (Creature) (hmElements.get (target));
jobTime = sc.nextInt ();
pm = new JProgressBar ();
pm.setStringPainted (true);
parent.add (pm);
parent.add (new JLabel (worker.name, SwingConstants.CENTER));
parent.add (new JLabel (jobName , SwingConstants.CENTER));
parent.add (jbGo);
parent.add (jbKill);
jbGo.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
toggleGoFlag ();
}
});
jbKill.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
setKillFlag ();
}
});
new Thread (this).start();
} // end constructor
// JLabel jln = new JLabel (worker.name);
// following shows how to align text relative to icon
// jln.setHorizontalTextPosition (SwingConstants.CENTER);
// jln.setHorizontalAlignment (SwingConstants.CENTER);
// parent.jrun.add (jln);
public void toggleGoFlag () {
goFlag = !goFlag;
} // end method toggleRunFlag
public void setKillFlag () {
noKillFlag = false;
jbKill.setBackground (Color.red);
} // end setKillFlag
void showStatus (Status st) {
status = st;
switch (status) {
case RUNNING:
jbGo.setBackground (Color.green);
jbGo.setText ("Running");
break;
case SUSPENDED:
jbGo.setBackground (Color.yellow);
jbGo.setText ("Suspended");
break;
case WAITING:
jbGo.setBackground (Color.orange);
jbGo.setText ("Waiting turn");
break;
case DONE:
jbGo.setBackground (Color.red);
jbGo.setText ("Done");
break;
} // end switch on status
} // end showStatus
public void run () {
long time = System.currentTimeMillis();
long startTime = time;
long stopTime = time + 1000 * jobTime;
double duration = stopTime - time;
synchronized (worker.party) { // party since looking forward to P4 requirements
while (worker.busyFlag) {
showStatus (Status.WAITING);
try {
worker.party.wait();
}
catch (InterruptedException e) {
} // end try/catch block
} // end while waiting for worker to be free
worker.busyFlag = true;
} // end sychronized on worker
while (time < stopTime && noKillFlag) {
try {
Thread.sleep (100);
} catch (InterruptedException e) {}
if (goFlag) {
showStatus (Status.RUNNING);
time += 100;
pm.setValue ((int)(((time - startTime) / duration) * 100));
} else {
showStatus (Status.SUSPENDED);
} // end if stepping
} // end runninig
pm.setValue (100);
showStatus (Status.DONE);
synchronized (worker.party) {
worker.busyFlag = false;
worker.party.notifyAll ();
}
} // end method run - implements runnable
public String toString () {
String sr = String.format ("j:%7d:%15s:%7d:%5d", jobIndex, jobName, worker.index,
jobTime);
return sr;
} //end method toString
} // end class Job
// p::
class Party extends CaveElement {
ArrayList members = new ArrayList ();
int index;
String name;
public Party (Scanner s) {
s.next (); // dump first field, p
index = s.nextInt ();
name = s.next();
} // String constructor
public void addCreature (Creature c) {
members.add (c);
} // end method addCreature
public String toString () {
String sr = String.format ("p:%6d:%s", index, name);
for (Creature c: members)
sr += " " + c;
return sr;
} // end toString method
} // end class Party
// c:::::::
class Creature extends CaveElement
// implements Runnable
{
ArrayList treasures = new ArrayList ();
ArrayList artifacts = new ArrayList ();
int index;
String type, name;
Party party = null;
double empathy, fear, capacity;
boolean busyFlag = false;
public int makeCreature (Scanner s) {
int partyInd;
s.next (); // dump first field, c
index = s.nextInt ();
type = s.next ();
name = s.next ();
partyInd = s.nextInt ();
empathy = s.nextDouble ();
fear = s.nextDouble ();
capacity = s.nextDouble ();
return partyInd;
} // Scanner Creature factory method
public void addTreasure (Treasure t) {treasures.add (t);}
public void addArtifact (Artifact a) {artifacts.add (a);}
// public void addJob (long t, Scanner sc) {
// jobTime = t;
// } // end addJob
public String toString () {
String sb = "";
if (party == null)
sb += String.format ("c:%6d: %s : %s : %6d : %4.1f : %4.1f : %4.1f", index, type,
name, 0, empathy, fear, capacity);
else sb += String.format ("c:%6d: %s : %s : %6d : %4.1f : %4.1f : %4.1f", index, type,
name, party.index, empathy, fear, capacity);
for (Treasure t: treasures) sb += " " + t;
for (Artifact a: artifacts) sb += " " + a;
return sb;
} // end toString method
} // end class CaveElement
// t:::::
class Treasure extends CaveElement {
int index;
String type;
double weight, value;
Creature holder;
public int makeTreasure (Scanner s) {
int partyInd;
s.next (); // dump first field, c
index = s.nextInt ();
type = s.next ();
partyInd = s.nextInt ();
weight = s.nextDouble ();
value = s.nextDouble ();
return partyInd;
} // Scanner Treasure factory method
public String toString () {
if (holder == null)
return String.format ("t:%6d: %s : %6d : %4.1f : %4.1f", index, type, 0, weight,
value);
return String.format ("t:%6d: %s : %6d : %4.1f : %4.1f", index, type, holder.index, weight,
value);
} // end toString method
} // end class Treasure
// a:::[:]
class Artifact extends CaveElement {
int index;
String type, name = "";
Creature holder;
public int makeArtifact (Scanner s) {
int partyInd;
s.next (); // dump first field, c
index = s.nextInt ();
type = s.next ();
partyInd = s.nextInt ();
if (s.hasNext()) name = s.next ();
return partyInd;
} // Scanner Artifact factory method
public String toString () {
if (holder == null)
return String.format ("a:%6d: %s : %6d : %s", index, type, 0, name);
return String.format ("a:%6d: %s : %6d : %s", index, type, holder.index, name);
} // end toString method
} // end class Artifact

More Related Content

Similar to Implement threads and a GUI interface using advanced Java Swing clas.pdf

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfforwardcom41
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
 
TASK #1In the domain class you will create a loop that will prompt.pdf
TASK #1In the domain class you will create a loop that will prompt.pdfTASK #1In the domain class you will create a loop that will prompt.pdf
TASK #1In the domain class you will create a loop that will prompt.pdfindiaartz
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival GuideGiordano Scalzo
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersFITC
 

Similar to Implement threads and a GUI interface using advanced Java Swing clas.pdf (20)

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdf
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
TASK #1In the domain class you will create a loop that will prompt.pdf
TASK #1In the domain class you will create a loop that will prompt.pdfTASK #1In the domain class you will create a loop that will prompt.pdf
TASK #1In the domain class you will create a loop that will prompt.pdf
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
ES6 generators
ES6 generatorsES6 generators
ES6 generators
 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End Developers
 

More from amrishinda

JAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdfJAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdfamrishinda
 
Let f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdf
Let f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdfLet f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdf
Let f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdfamrishinda
 
If a cells contents are greatly hypo-osmotic to the surrounding env.pdf
If a cells contents are greatly hypo-osmotic to the surrounding env.pdfIf a cells contents are greatly hypo-osmotic to the surrounding env.pdf
If a cells contents are greatly hypo-osmotic to the surrounding env.pdfamrishinda
 
How are the forelimbs of humans, the wings of birds, the wings of ba.pdf
How are the forelimbs of humans, the wings of birds, the wings of ba.pdfHow are the forelimbs of humans, the wings of birds, the wings of ba.pdf
How are the forelimbs of humans, the wings of birds, the wings of ba.pdfamrishinda
 
Fom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdf
Fom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdfFom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdf
Fom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdfamrishinda
 
Germ cells are set aside during animal development and give rise to .pdf
Germ cells are set aside during animal development and give rise to .pdfGerm cells are set aside during animal development and give rise to .pdf
Germ cells are set aside during animal development and give rise to .pdfamrishinda
 
Determine the missing amounts. (Hint For example, to solve for (a), .pdf
Determine the missing amounts. (Hint For example, to solve for (a), .pdfDetermine the missing amounts. (Hint For example, to solve for (a), .pdf
Determine the missing amounts. (Hint For example, to solve for (a), .pdfamrishinda
 
Discuss the various methods of intellectual property protection avai.pdf
Discuss the various methods of intellectual property protection avai.pdfDiscuss the various methods of intellectual property protection avai.pdf
Discuss the various methods of intellectual property protection avai.pdfamrishinda
 
devise a hypothesis that explains the geographical distribution of m.pdf
devise a hypothesis that explains the geographical distribution of m.pdfdevise a hypothesis that explains the geographical distribution of m.pdf
devise a hypothesis that explains the geographical distribution of m.pdfamrishinda
 
Describe a diode array detector and CCD camera. Differentiate betwee.pdf
Describe a diode array detector and CCD camera. Differentiate betwee.pdfDescribe a diode array detector and CCD camera. Differentiate betwee.pdf
Describe a diode array detector and CCD camera. Differentiate betwee.pdfamrishinda
 
Connect a motor, two push buttons and two LEDS to the Arduino as sho.pdf
Connect a motor, two push buttons and two LEDS to the Arduino as sho.pdfConnect a motor, two push buttons and two LEDS to the Arduino as sho.pdf
Connect a motor, two push buttons and two LEDS to the Arduino as sho.pdfamrishinda
 
Consider managers (supervisors) that you have worked for in the past.pdf
Consider managers (supervisors) that you have worked for in the past.pdfConsider managers (supervisors) that you have worked for in the past.pdf
Consider managers (supervisors) that you have worked for in the past.pdfamrishinda
 
Caterpillar is one of the Americas major exporters. The company sell.pdf
Caterpillar is one of the Americas major exporters. The company sell.pdfCaterpillar is one of the Americas major exporters. The company sell.pdf
Caterpillar is one of the Americas major exporters. The company sell.pdfamrishinda
 
what numbers go with these descriptions.1. Uses ATP hydrolysis2..pdf
what numbers go with these descriptions.1. Uses ATP hydrolysis2..pdfwhat numbers go with these descriptions.1. Uses ATP hydrolysis2..pdf
what numbers go with these descriptions.1. Uses ATP hydrolysis2..pdfamrishinda
 
What are the three forms of Business Organizations Answer the follow.pdf
What are the three forms of Business Organizations Answer the follow.pdfWhat are the three forms of Business Organizations Answer the follow.pdf
What are the three forms of Business Organizations Answer the follow.pdfamrishinda
 
Anatomy Question Use your own words.A girl with a defective heart.pdf
Anatomy Question Use your own words.A girl with a defective heart.pdfAnatomy Question Use your own words.A girl with a defective heart.pdf
Anatomy Question Use your own words.A girl with a defective heart.pdfamrishinda
 
Why parkinsons disease is special among the different neurological.pdf
Why parkinsons disease is special among the different neurological.pdfWhy parkinsons disease is special among the different neurological.pdf
Why parkinsons disease is special among the different neurological.pdfamrishinda
 
Which statement is not true promoters are transcribed the Pribnow .pdf
Which statement is not true  promoters are transcribed  the Pribnow .pdfWhich statement is not true  promoters are transcribed  the Pribnow .pdf
Which statement is not true promoters are transcribed the Pribnow .pdfamrishinda
 
When extracting DNA of an fruit how does the environemnt (how hot or.pdf
When extracting DNA of an fruit how does the environemnt (how hot or.pdfWhen extracting DNA of an fruit how does the environemnt (how hot or.pdf
When extracting DNA of an fruit how does the environemnt (how hot or.pdfamrishinda
 
Which ANN do you prefer amidst of the variety of ANNs Justify the r.pdf
Which ANN do you prefer amidst of the variety of ANNs Justify the r.pdfWhich ANN do you prefer amidst of the variety of ANNs Justify the r.pdf
Which ANN do you prefer amidst of the variety of ANNs Justify the r.pdfamrishinda
 

More from amrishinda (20)

JAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdfJAVA A double-ended queue is a list that allows the addition and.pdf
JAVA A double-ended queue is a list that allows the addition and.pdf
 
Let f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdf
Let f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdfLet f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdf
Let f(z) be an entire function such that fn+1(z) equivalent 0, Prove.pdf
 
If a cells contents are greatly hypo-osmotic to the surrounding env.pdf
If a cells contents are greatly hypo-osmotic to the surrounding env.pdfIf a cells contents are greatly hypo-osmotic to the surrounding env.pdf
If a cells contents are greatly hypo-osmotic to the surrounding env.pdf
 
How are the forelimbs of humans, the wings of birds, the wings of ba.pdf
How are the forelimbs of humans, the wings of birds, the wings of ba.pdfHow are the forelimbs of humans, the wings of birds, the wings of ba.pdf
How are the forelimbs of humans, the wings of birds, the wings of ba.pdf
 
Fom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdf
Fom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdfFom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdf
Fom 1120, Sched Mark for follow up Question 15 of 105. A corporat.pdf
 
Germ cells are set aside during animal development and give rise to .pdf
Germ cells are set aside during animal development and give rise to .pdfGerm cells are set aside during animal development and give rise to .pdf
Germ cells are set aside during animal development and give rise to .pdf
 
Determine the missing amounts. (Hint For example, to solve for (a), .pdf
Determine the missing amounts. (Hint For example, to solve for (a), .pdfDetermine the missing amounts. (Hint For example, to solve for (a), .pdf
Determine the missing amounts. (Hint For example, to solve for (a), .pdf
 
Discuss the various methods of intellectual property protection avai.pdf
Discuss the various methods of intellectual property protection avai.pdfDiscuss the various methods of intellectual property protection avai.pdf
Discuss the various methods of intellectual property protection avai.pdf
 
devise a hypothesis that explains the geographical distribution of m.pdf
devise a hypothesis that explains the geographical distribution of m.pdfdevise a hypothesis that explains the geographical distribution of m.pdf
devise a hypothesis that explains the geographical distribution of m.pdf
 
Describe a diode array detector and CCD camera. Differentiate betwee.pdf
Describe a diode array detector and CCD camera. Differentiate betwee.pdfDescribe a diode array detector and CCD camera. Differentiate betwee.pdf
Describe a diode array detector and CCD camera. Differentiate betwee.pdf
 
Connect a motor, two push buttons and two LEDS to the Arduino as sho.pdf
Connect a motor, two push buttons and two LEDS to the Arduino as sho.pdfConnect a motor, two push buttons and two LEDS to the Arduino as sho.pdf
Connect a motor, two push buttons and two LEDS to the Arduino as sho.pdf
 
Consider managers (supervisors) that you have worked for in the past.pdf
Consider managers (supervisors) that you have worked for in the past.pdfConsider managers (supervisors) that you have worked for in the past.pdf
Consider managers (supervisors) that you have worked for in the past.pdf
 
Caterpillar is one of the Americas major exporters. The company sell.pdf
Caterpillar is one of the Americas major exporters. The company sell.pdfCaterpillar is one of the Americas major exporters. The company sell.pdf
Caterpillar is one of the Americas major exporters. The company sell.pdf
 
what numbers go with these descriptions.1. Uses ATP hydrolysis2..pdf
what numbers go with these descriptions.1. Uses ATP hydrolysis2..pdfwhat numbers go with these descriptions.1. Uses ATP hydrolysis2..pdf
what numbers go with these descriptions.1. Uses ATP hydrolysis2..pdf
 
What are the three forms of Business Organizations Answer the follow.pdf
What are the three forms of Business Organizations Answer the follow.pdfWhat are the three forms of Business Organizations Answer the follow.pdf
What are the three forms of Business Organizations Answer the follow.pdf
 
Anatomy Question Use your own words.A girl with a defective heart.pdf
Anatomy Question Use your own words.A girl with a defective heart.pdfAnatomy Question Use your own words.A girl with a defective heart.pdf
Anatomy Question Use your own words.A girl with a defective heart.pdf
 
Why parkinsons disease is special among the different neurological.pdf
Why parkinsons disease is special among the different neurological.pdfWhy parkinsons disease is special among the different neurological.pdf
Why parkinsons disease is special among the different neurological.pdf
 
Which statement is not true promoters are transcribed the Pribnow .pdf
Which statement is not true  promoters are transcribed  the Pribnow .pdfWhich statement is not true  promoters are transcribed  the Pribnow .pdf
Which statement is not true promoters are transcribed the Pribnow .pdf
 
When extracting DNA of an fruit how does the environemnt (how hot or.pdf
When extracting DNA of an fruit how does the environemnt (how hot or.pdfWhen extracting DNA of an fruit how does the environemnt (how hot or.pdf
When extracting DNA of an fruit how does the environemnt (how hot or.pdf
 
Which ANN do you prefer amidst of the variety of ANNs Justify the r.pdf
Which ANN do you prefer amidst of the variety of ANNs Justify the r.pdfWhich ANN do you prefer amidst of the variety of ANNs Justify the r.pdf
Which ANN do you prefer amidst of the variety of ANNs Justify the r.pdf
 

Recently uploaded

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Implement threads and a GUI interface using advanced Java Swing clas.pdf

  • 1. Implement threads and a GUI interface using advanced Java Swing classes. Required data structure - the advanced data structure uses implementation of a multi-tree with the following levels: Cave - level 0 Party - Level 1 Creature - Level 2 Artifacts - Level 3 Treasures - Level 3 Jobs Use the Swing class JTree effectively to display the contents of the data file. Implement a JTable to also show the contents of the data file. Threads: Implement a thread for each job representing a task that creature will perform. Use the synchronize directive to avoid race conditions and insure that a creature is performing only one job at a time. The thread for each job should be started as the job is read in from the data file. Only one job should be progressing for each creature at any moment. Use delays to show the creature doing the task. Use a JProgressBar for each creature to show the creature performing the task. Use JButton's on the Job panel to allow the task to be suspended and cancelled. The GUI elements should be distinct from the other classes in the program. Solution Please find the code below for the above problem : import java.util.ArrayList; import java.util.Scanner; import java.util.HashMap; import java.util.Random; import java.io.File; import java.io.FileNotFoundException; import javax.swing.JProgressBar; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.Color;
  • 2. import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Cave2 { ArrayList parties = new ArrayList (); // the parties ArrayList loners = new ArrayList (); // creatures not in parties ArrayList drops = new ArrayList (); // Treasures not carried ArrayList magics = new ArrayList (); // Artifacts not carried ArrayList jobs = new ArrayList (); // Jobs to be performed JFrame jf = new JFrame (); JPanel jrun = new JPanel (); JTextArea jta = new JTextArea (10, 10); // hashmap of everything by index HashMap hmElements = new HashMap (); public Cave2 () { Scanner sf = null; String fileName = "dataC.txt"; try { // sf = new Scanner (new File (fileName)); // getResourceAsStream is the way to access a data file in a jar package file // this works in general, so leave it here as is. sf = new Scanner (getClass().getResourceAsStream (fileName)); } catch (Exception e) { System.out.println (e + " File bummer: " + fileName); } // end open file try/catch block if (sf == null) return; readFile (sf); jta.setText (toString ());
  • 3. jf.setTitle ("Cave2"); jf.add (jrun, BorderLayout.PAGE_END); jrun.setLayout (new GridLayout (0, 5, 2, 5)); jf.add (new JScrollPane (jta), BorderLayout.CENTER); jta.setFont (new Font ("Monospaced", 0, 12)); jf.pack (); jf.setVisible (true); jf.setLocationRelativeTo (null); } // end no-parameter constructor public static void main (String args []) { Cave2 cv = new Cave2 (); cv.jf.add (new JLabel (" Close this window to end program "), BorderLayout.PAGE_START); cv.jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // System.out.println (cv); } // end main public String toString () { String sb = ""; sb += toString (parties, "Party List"); sb += toString (loners , "Unaligned Creatures"); sb += toString (drops , "Unheld Treasures"); sb += toString (magics , "Unheld Artifacts"); sb += toString (jobs , "Jobs"); // sb += toString (hmElements.values (), "HashMap"); return sb; } // end method dump String toString (Iterable it, String label) { String sb = " ----- DUMP " + label + " -------"; for (CaveElement c: it) sb += " " + c.toString (); return sb; } // end method dump Iterable String
  • 4. void readFile (Scanner sf) { String inline; Scanner line; while (sf.hasNext()) { inline = sf.nextLine().trim(); if (inline.length() == 0) continue; line = new Scanner (inline).useDelimiter ("s*:s*"); // compress white space also, else nextInt fails switch (inline.charAt (0)) { case 'p': addParty (line); break; case 'c': addCreature (line); break; case 't': addTreasure (line); break; case 'a': addArtifact (line); break; case 'j': addJob (line); break; } // end switch } // end while reading data file jf.pack (); } // end readFile public void addJob (Scanner sc) { Job job = new Job (hmElements, jrun, sc); // (new Thread (job)).start(); // jobs.add (job); } // end method addJob public void addParty (Scanner sc){ Party pt = new Party (sc); parties.add (pt); hmElements.put (pt.index, pt); } // end method addParty public void addCreature (Scanner sc) { Creature c = new Creature (); int target = c.makeCreature (sc); Party p = (Party)(hmElements.get (target)); if (p == null)
  • 5. loners.add (c); else { p.addCreature (c); c.party = p; } hmElements.put (c.index, c); } // end method addToParty public void addTreasure (Scanner sc) { Treasure t = new Treasure (); int target = t.makeTreasure (sc); Creature c = (Creature)(hmElements.get (target)); if (c == null) drops.add (t); else { c.addTreasure (t); t.holder = c; } hmElements.put (t.index, t); } // end method addTreasure public void addArtifact (Scanner sc) { Artifact a = new Artifact (); int target = a.makeArtifact (sc); Creature c = (Creature)(hmElements.get (target)); if (a == null) magics.add (a); else { c.addArtifact (a); a.holder = c; } hmElements.put (a.index, a); } // end method addArtifact } // end class Cave
  • 6. class CaveElement {} // j::::[::]* class Job extends CaveElement implements Runnable { static Random rn = new Random (); JPanel parent; Creature worker = null; int jobIndex; long jobTime; String jobName = ""; JProgressBar pm = new JProgressBar (); boolean goFlag = true, noKillFlag = true; JButton jbGo = new JButton ("Stop"); JButton jbKill = new JButton ("Cancel"); Status status = Status.SUSPENDED; enum Status {RUNNING, SUSPENDED, WAITING, DONE}; public Job (HashMap hmElements, JPanel cv, Scanner sc) { parent = cv; sc.next (); // dump first field, j jobIndex = sc.nextInt (); jobName = sc.next (); int target = sc.nextInt (); worker = (Creature) (hmElements.get (target)); jobTime = sc.nextInt (); pm = new JProgressBar (); pm.setStringPainted (true); parent.add (pm); parent.add (new JLabel (worker.name, SwingConstants.CENTER)); parent.add (new JLabel (jobName , SwingConstants.CENTER)); parent.add (jbGo); parent.add (jbKill); jbGo.addActionListener (new ActionListener () {
  • 7. public void actionPerformed (ActionEvent e) { toggleGoFlag (); } }); jbKill.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { setKillFlag (); } }); new Thread (this).start(); } // end constructor // JLabel jln = new JLabel (worker.name); // following shows how to align text relative to icon // jln.setHorizontalTextPosition (SwingConstants.CENTER); // jln.setHorizontalAlignment (SwingConstants.CENTER); // parent.jrun.add (jln); public void toggleGoFlag () { goFlag = !goFlag; } // end method toggleRunFlag public void setKillFlag () { noKillFlag = false; jbKill.setBackground (Color.red); } // end setKillFlag void showStatus (Status st) { status = st; switch (status) { case RUNNING: jbGo.setBackground (Color.green); jbGo.setText ("Running"); break;
  • 8. case SUSPENDED: jbGo.setBackground (Color.yellow); jbGo.setText ("Suspended"); break; case WAITING: jbGo.setBackground (Color.orange); jbGo.setText ("Waiting turn"); break; case DONE: jbGo.setBackground (Color.red); jbGo.setText ("Done"); break; } // end switch on status } // end showStatus public void run () { long time = System.currentTimeMillis(); long startTime = time; long stopTime = time + 1000 * jobTime; double duration = stopTime - time; synchronized (worker.party) { // party since looking forward to P4 requirements while (worker.busyFlag) { showStatus (Status.WAITING); try { worker.party.wait(); } catch (InterruptedException e) { } // end try/catch block } // end while waiting for worker to be free worker.busyFlag = true; } // end sychronized on worker while (time < stopTime && noKillFlag) { try { Thread.sleep (100);
  • 9. } catch (InterruptedException e) {} if (goFlag) { showStatus (Status.RUNNING); time += 100; pm.setValue ((int)(((time - startTime) / duration) * 100)); } else { showStatus (Status.SUSPENDED); } // end if stepping } // end runninig pm.setValue (100); showStatus (Status.DONE); synchronized (worker.party) { worker.busyFlag = false; worker.party.notifyAll (); } } // end method run - implements runnable public String toString () { String sr = String.format ("j:%7d:%15s:%7d:%5d", jobIndex, jobName, worker.index, jobTime); return sr; } //end method toString } // end class Job // p:: class Party extends CaveElement { ArrayList members = new ArrayList (); int index; String name; public Party (Scanner s) { s.next (); // dump first field, p index = s.nextInt ();
  • 10. name = s.next(); } // String constructor public void addCreature (Creature c) { members.add (c); } // end method addCreature public String toString () { String sr = String.format ("p:%6d:%s", index, name); for (Creature c: members) sr += " " + c; return sr; } // end toString method } // end class Party // c::::::: class Creature extends CaveElement // implements Runnable { ArrayList treasures = new ArrayList (); ArrayList artifacts = new ArrayList (); int index; String type, name; Party party = null; double empathy, fear, capacity; boolean busyFlag = false; public int makeCreature (Scanner s) { int partyInd; s.next (); // dump first field, c index = s.nextInt (); type = s.next (); name = s.next (); partyInd = s.nextInt ();
  • 11. empathy = s.nextDouble (); fear = s.nextDouble (); capacity = s.nextDouble (); return partyInd; } // Scanner Creature factory method public void addTreasure (Treasure t) {treasures.add (t);} public void addArtifact (Artifact a) {artifacts.add (a);} // public void addJob (long t, Scanner sc) { // jobTime = t; // } // end addJob public String toString () { String sb = ""; if (party == null) sb += String.format ("c:%6d: %s : %s : %6d : %4.1f : %4.1f : %4.1f", index, type, name, 0, empathy, fear, capacity); else sb += String.format ("c:%6d: %s : %s : %6d : %4.1f : %4.1f : %4.1f", index, type, name, party.index, empathy, fear, capacity); for (Treasure t: treasures) sb += " " + t; for (Artifact a: artifacts) sb += " " + a; return sb; } // end toString method } // end class CaveElement // t::::: class Treasure extends CaveElement { int index; String type; double weight, value; Creature holder; public int makeTreasure (Scanner s) { int partyInd;
  • 12. s.next (); // dump first field, c index = s.nextInt (); type = s.next (); partyInd = s.nextInt (); weight = s.nextDouble (); value = s.nextDouble (); return partyInd; } // Scanner Treasure factory method public String toString () { if (holder == null) return String.format ("t:%6d: %s : %6d : %4.1f : %4.1f", index, type, 0, weight, value); return String.format ("t:%6d: %s : %6d : %4.1f : %4.1f", index, type, holder.index, weight, value); } // end toString method } // end class Treasure // a:::[:] class Artifact extends CaveElement { int index; String type, name = ""; Creature holder; public int makeArtifact (Scanner s) { int partyInd; s.next (); // dump first field, c index = s.nextInt (); type = s.next (); partyInd = s.nextInt (); if (s.hasNext()) name = s.next (); return partyInd; } // Scanner Artifact factory method public String toString () { if (holder == null)
  • 13. return String.format ("a:%6d: %s : %6d : %s", index, type, 0, name); return String.format ("a:%6d: %s : %6d : %s", index, type, holder.index, name); } // end toString method } // end class Artifact