Sie sind auf Seite 1von 13

//***************************************************************

// IFP Algorithm Demonstration


// Source: Demo.java
// Classes: Demo.class
// CompNamePool.class
// ImageCanvas.class (extends Canvas)
//
// Author: pawan kumar singh
// Date: 5, August 5, 2010
// Version: JAVA 1.0
//***************************************************************

import java.awt.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.applet.Applet;

public class Demo extends Applet{


//URL location of demo data including GUI and display rules
String DEMO_WEB_LOC_PARAMS =
"http://www.ifp.uiuc.edu/~krejcark/Demo/DemoParams.dat";
//ATTEN this must be unique
String DEMO_WEB_LOC_DATA =
"http://www.ifp.uiuc.edu/~krejcark/Demo/DemoData.dat";

//applet parameter file names


String imageFile;
String dataFile;
String paramsFile;

Vector drawables; //vector containing all the drawing


objects to the image
Vector drawinfo; //vector containing drawing string
info

Image dispImage; //original image


ImageCanvas imgcanvas; //canvas that ecapsulates image

URL demoLocation; //URL location of demo image specifications


DataInputStream demoParams; //data stream of demo GUI and rule
specifications
DataInputStream demoData; //data stream of specific demo image
data

int numRowsRHS = 0; //minimun number of rows to be displayed on


the right side of the image
int numRows; //total number of rows to accomodate
components in gui

int imageWidth = 0;
int imageHeight = 0;
int displayWidth = 0;
int displayHeight = 0;

int numComponents = 0;
String[] compValues; //parameter values
String dataTokValue; //temporary data token
StringTokenizer[] compTokValues; //tokenized parameter values
StringTokenizer compDataTokValues; //tokenized image data and drawing
rules
String compType; //temporary token variable

String dataLine; //temporary string to fill compValues


StringTokenizer dataLineTokValue; //holds temporary tokenized string
to parse out numComponents integer
String numComp; //temporary string to hold
numComponents integer

int dynCompIndex = 0; //index dynamic components to cross-


reference components in GUI to DemoDataXXXX.dat
int numDynComponents = 0; //number of dynamic components

Color [] colors = {Color.red, Color.blue, Color.cyan, Color.darkGray,


Color.gray, Color.green,
Color.lightGray,
Color.magenta, Color.orange, Color.pink, Color.red,
Color.white, Color.yellow};

protected void makescrollbar(String compID, StringTokenizer params,


GridBagLayout gridbag,
GridBagConstraints c){
String lhsLabel; //lhs label
String rhsLabel; //rhs label
String defaultState;
int lMin; //start value
int rMax; //end value
String sldrLength; //length (string)
String initSetting; //initial setting (string)
int sLength; //length
int iSetting; //initial setting

//row 1
c.gridwidth = 1; //spacer
c.gridheight = 1;
makelabel("", gridbag, c);

defaultState = params.nextToken();

c.gridwidth = 2; //description
c.gridheight = 1;
makelabel(params.nextToken(), gridbag, c);

c.gridwidth = GridBagConstraints.REMAINDER; //checkbox


c.gridheight = 1;
makecheckbox(compID, Integer.parseInt(defaultState), gridbag, c);

//set variables with tokens


initSetting = params.nextToken();
sldrLength = params.nextToken();
lhsLabel = params.nextToken();
rhsLabel = params.nextToken();

//convert strings to ints


iSetting = Integer.parseInt(initSetting);
sLength = Integer.parseInt(sldrLength);
lMin = Integer.parseInt(lhsLabel);
rMax = Integer.parseInt(rhsLabel);

//row 2
c.gridwidth = 1;
c.gridheight = 1;
makelabel(" "+lhsLabel, gridbag, c);

c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridheight = 1;

//create new scrollbar object in hash table with reference


compID
CompNamePool.baptize (new
Scrollbar(Scrollbar.HORIZONTAL,iSetting,sLength,lMin,rMax),compID);
Scrollbar sbar = (Scrollbar) (CompNamePool.component (compID));
gridbag.setConstraints(sbar, c);
add(sbar);

c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = 1;
makelabel(" "+rhsLabel, gridbag, c);
}

protected void makeheader(String compID, StringTokenizer params,


GridBagLayout gridbag,
GridBagConstraints c){
//row 1
c.gridwidth = 1; //spacer
c.gridheight = 1;
makelabel("", gridbag, c);

c.gridwidth = 2; //description
c.gridheight = 1;
makelabel(params.nextToken(), gridbag, c);

c.gridwidth = GridBagConstraints.REMAINDER; //spacer


c.gridheight = 1;
makelabel("", gridbag, c);
}

protected void makespacer(String compID, StringTokenizer params,


GridBagLayout gridbag,
GridBagConstraints c){

c.gridwidth = GridBagConstraints.REMAINDER; //spacer


c.gridheight = 1;
makelabel("", gridbag, c);
}

protected void makelabel(String name, //is called only by other


methods
GridBagLayout gridbag,
GridBagConstraints c){

Label label = new Label(name);


gridbag.setConstraints(label, c);
add(label);
}

protected void makecheckbox(String compName, //is called only by


other methods
int state,
GridBagLayout gridbag,
GridBagConstraints c){

//create new checkbox object in hash table with reference


compID+"_checkbox"
CompNamePool.baptize (new Checkbox("Enabled"),compName+"_checkbox");
Checkbox checkbox = (Checkbox) (CompNamePool.component
(compName+"_checkbox"));
if(state == 1) checkbox.setState(true);
else checkbox.setState(false);
gridbag.setConstraints(checkbox, c);
add(checkbox);
}

protected void makebutton(String compName,


GridBagLayout gridbag,
GridBagConstraints c){

c.gridwidth = 1; //spacer
c.gridheight = 1;
makelabel("", gridbag, c);

//create new button object in hash table with reference


reCalculate
CompNamePool.baptize (new Button("Refresh"),compName);
Button button = (Button) (CompNamePool.component (compName));
c.gridwidth = 2;
c.gridheight = 1;
gridbag.setConstraints(button, c);
add(button);

c.gridwidth = 1; //spacer
c.gridheight = 1;
makelabel("", gridbag, c);
}

//main applet initialization

public void init(){

//get filename parameters


imageFile = getParameter("DemoImage");
dataFile = getParameter("DemoData");
paramsFile = getParameter("DemoParams");

//instantiate gridbag layout and constraints


GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);

//applet default parameters


setBackground(Color.gray);
setFont(new Font("Helvetica", Font.PLAIN, 14));
c.fill = GridBagConstraints.BOTH;
//c.insets; //specifies the components external padding

//instantiate URL and open data stream for demoParams


//try opening file
try{
demoLocation = new URL(DEMO_WEB_LOC_PARAMS);
demoParams = new DataInputStream(

demoLocation.openConnection().getInputStream());
//ignore all lines that begin with '#'
do dataLine = demoParams.readLine();
while (dataLine.charAt(0) == '#');
}
//catch all expections that might be thrown as a result
catch(Exception e){
//do nothing test
}

//instantiate URL and open data stream for demoData


//try opening file
try{
demoLocation = new URL(DEMO_WEB_LOC_DATA);
demoData = new DataInputStream(

demoLocation.openConnection().getInputStream());
}
//catch all expections that might be thrown as a result
catch(Exception e){
//do nothing test
}

//tokenize first line of demoParams to extract the number of


components
dataLineTokValue = new StringTokenizer(dataLine,"|",false);
dataLineTokValue.nextToken(); //throw away preface
numComp = dataLineTokValue.nextToken();
numComponents = Integer.parseInt(numComp);

//instantiate data arrays


compValues = new String[numComponents];
compTokValues = new StringTokenizer[numComponents];

//instantiate empty vectors


drawinfo = new Vector();
drawables = new Vector();
//instantiate image and canvas for image
dispImage = getImage(getCodeBase(), "test.jpg");
imgcanvas = new ImageCanvas(dispImage, drawables, this);

//specify canvas parameters


imgcanvas.setBackground(Color.blue);

//get image and canvas size


imageWidth = imgcanvas.getFWidth();
imageHeight = imgcanvas.getFHeight();

//reset canvas size to match image size


imgcanvas.resize(imageWidth, imageHeight);

//define compTokValues array


try{
dynCompIndex = 0;
for(int i=0; i<numComponents; i++){
compValues[i] = demoParams.readLine();
//fill compTokValues array with tokenized
compValues
//ignore all lines that begin with '#'
if(compValues[i].charAt(0) != '#') compTokValues[i] =
new StringTokenizer(compValues[i],"|",false);
else if(compValues[i].charAt(0) == '#') i--;
}
}

catch(Exception e){
//do nothing test
}

//determine layout of components around image


//one row is approximately 24 pixels high
numRowsRHS = imageHeight/24;

//set gridbag constraints for canvas and display canvas with


image
c.gridwidth = 3;
c.gridheight = numRowsRHS; //specififies the number of rows on RHS of
image
gridbag.setConstraints(imgcanvas, c);
add(imgcanvas);

//parse compTokValues and dynamically create GUI


//position of components is determied by order in parameters
//since there are only numRowsRHS availible on rhs of image,
//each time a component is added, the appropriate numRows
//are incremented and compared to numRowsRHS for availible rhs
space
numRows = 0;
dynCompIndex = 0;
for(int i=0; i<numComponents; i++){
compType = compTokValues[i].nextToken();
if(compType.equals("Header")){
if(numRows == numRowsRHS) makespacer("Spacer"+i,
compTokValues[i], gridbag, c);
makeheader("Header"+i, compTokValues[i], gridbag, c);
numRows+=1;
}
else if(compType.equals("Spacer")){
makespacer("Spacer"+i, compTokValues[i], gridbag, c);
numRows+=1;
}
else if(compType.equals("Slider")){
if(numRows == numRowsRHS -1) makespacer("Spacer"+i,
compTokValues[i], gridbag, c);
makescrollbar("DynComp"+dynCompIndex,
compTokValues[i], gridbag, c);
dynCompIndex++;
numRows+=2;
}
numDynComponents = dynCompIndex;
}

//dynamically fill drawinfo vector with lines of demoData


//read from file until exception is thrown
try{
for(;;){
dataLine = demoData.readLine();
//ignore all lines that begin with '#'
if(dataLine.charAt(0) != '#')
drawinfo.addElement(dataLine);
}
}

catch(Exception e){
//do nothing test
}

//create button to refresh demo


makebutton("rfshButton", gridbag, c);

System.out.println(imageWidth); //test
System.out.println(imageHeight); //test

System.out.println(numRows); //test

displayWidth = imageWidth + 500;


displayHeight = imageHeight + 50;
if((numRows - numRowsRHS)>0) displayHeight += (numRows -
numRowsRHS)*24;

resize(displayWidth, displayHeight);
}

//Handles action events for the applet -- either events


//directed to the applet or events passed up to the
//applet from components inside it.
public boolean action(Event evt, Object what) {
int dataValue;
int compValue;
int xVal, yVal, wVal, hVal, sizeVal;
String stringVal;
int compColor;

//check all checkboxes to disable and enable their


respective components
for(int i=0;i<numComponents;i++){
if
(evt.target.equals(CompNamePool.component("DynComp"+i+"_checkbox"))){
if(!
((Checkbox)CompNamePool.component("DynComp"+i+"_checkbox")).getState())

((Scrollbar)CompNamePool.component("DynComp"+i)).disable();

else((Scrollbar)CompNamePool.component("DynComp"+i)).enable();
}
}

//check if button was pressed to initiate refresh of


image
if (evt.target.equals(CompNamePool.component("rfshButton"))){
//when user clicks refresh, the drawing vector
is deleted
drawables.removeAllElements();
//loop through vector and extract each line
into it's tokens
for(int i=0; i<drawinfo.size(); i++){
System.out.println("Element" +
drawinfo.elementAt(i));
compDataTokValues = new
StringTokenizer((String)drawinfo.elementAt(i),"|",false);
//get compID
dataTokValue = compDataTokValues.nextToken();
dataValue = Integer.parseInt(dataTokValue);
//check to see if refering component
is enabled

if(((Checkbox)CompNamePool.component("DynComp"+dataValue+"_checkbox")).getStat
e()){
//get component's current
value
compValue =
((Scrollbar)CompNamePool.component("DynComp"+dataValue)).getValue();
//get threshold
dataTokValue =
compDataTokValues.nextToken();
dataValue =
Integer.parseInt(dataTokValue);
//compare component value to
threshold
if(compValue < dataValue){
//get color (String)
dataTokValue =
compDataTokValues.nextToken();
compColor =
Integer.parseInt(dataTokValue);
//get drawing
instruction
dataTokValue =
compDataTokValues.nextToken();
dataValue =
Integer.parseInt(dataTokValue);

System.out.println("dataValue" + dataValue);
//create a rectangle
drawing
if(dataValue == 0){
//get drawing
coordinites
dataTokValue =
compDataTokValues.nextToken();
//re-
instantiate compDataTokValues to seperate commas
compDataTokValues =
new StringTokenizer(dataTokValue,",",false);
//define
coordinites
xVal =
Integer.parseInt(compDataTokValues.nextToken());
yVal =
Integer.parseInt(compDataTokValues.nextToken());
wVal =
Integer.parseInt(compDataTokValues.nextToken());
hVal =
Integer.parseInt(compDataTokValues.nextToken());
//instantiate
DrawRect object
DrawRect rectangle =
new DrawRect(xVal,yVal,wVal,hVal,colors[compColor]);
//add the
drawable object to the drawables vector

drawables.addElement(rectangle);
}

//create a point
drawing
else if(dataValue == 1){
//get drawing
coordinites
dataTokValue =
compDataTokValues.nextToken();
//re-
instantiate compDataTokValues to seperate commas
compDataTokValues =
new StringTokenizer(dataTokValue,",",false);
//define
coordinites
xVal =
Integer.parseInt(compDataTokValues.nextToken());
yVal =
Integer.parseInt(compDataTokValues.nextToken());
sizeVal =
Integer.parseInt(compDataTokValues.nextToken());
//instantiate
DrawPoint object
DrawPoint point = new
DrawPoint(xVal,yVal,sizeVal,colors[compColor]);
//add the
drawable object to the drawables vector

drawables.addElement(point);
}

//create a string
drawing
else if(dataValue == 2){
//get drawing
coordinites
dataTokValue =
compDataTokValues.nextToken();
//re-
instantiate compDataTokValues to seperate commas
compDataTokValues =
new StringTokenizer(dataTokValue,",",false);
//define
coordinites
xVal =
Integer.parseInt(compDataTokValues.nextToken());
yVal =
Integer.parseInt(compDataTokValues.nextToken());
sizeVal =
Integer.parseInt(compDataTokValues.nextToken());
stringVal =
compDataTokValues.nextToken();
//instantiate
DrawString object
DrawString string =
new DrawString(stringVal,xVal,yVal,sizeVal,colors[compColor]);
//add the
drawable object to the drawables vector

drawables.addElement(string);
}

else
System.out.println("Error: Unable to parse demodata");
}
}
}
imgcanvas.repaint();
}
return true;
}
}

abstract class Drawable{


int x,y,w,h,sz;
Color c;
String strn;
abstract public void draw(Graphics g);
}

class DrawRect extends Drawable{


DrawRect(int xR, int yR, int wR, int hR, Color color){
x=xR;
y=yR;
w=wR;
h=hR;
c = color;
}
public void draw(Graphics g){
g.setColor(c);
g.drawRect(x, y, w, h);
}
}

class DrawPoint extends Drawable{


DrawPoint(int xP, int yP, int sizeP, Color color){
x=xP;
y=yP;
sz = sizeP;
c = color;
}
public void draw(Graphics g){
g.setColor(c);
g.drawLine(x-sz,y,x+sz,y);
g.drawLine(x,y-sz,x,y+sz);
}
}

class DrawString extends Drawable{


DrawString(String stringS, int xS, int yS, int sizeS, Color color){
strn = stringS;
x=xS;
y=yS;
sz = sizeS;
c = color;
}
public void draw(Graphics g){
g.setFont(new Font("Helvetica", Font.PLAIN, sz));
g.setColor(c);
g.drawString(strn,x,y);
}
}

class CompNamePool{
static final Hashtable hash = new Hashtable ();
static final void baptize(Object o,String name) {hash.put (name,o);}
static final Object component(String name) {return hash.get (name);}
static final boolean includes(String name) {return hash.containsKey
(name);}
}
class ImageCanvas extends Canvas{
Container parentContainer;
public Image canvasImage;
public Image renderImage;
public Graphics renderImageGraphics;
MediaTracker tracker;
Vector drawVect;
int imageWidth = -1;
int imageHeight = -1;

public ImageCanvas(Image cImage, Vector dVect, Container container){


if (cImage == null) {
System.err.println("Canvas got invalid image object!");
return;
}

canvasImage = cImage;
drawVect = dVect;
parentContainer = container;

tracker = new MediaTracker(this);


tracker.addImage(canvasImage, 0);
}

public int getFWidth(){


while(imageWidth == -1){
imageWidth = canvasImage.getWidth(this);
}
return imageWidth;
}

public int getFHeight(){


while(imageHeight == -1){
imageHeight = canvasImage.getHeight(this);
}
return imageHeight;
}

public void paint (Graphics g) {


if (canvasImage != null) {
imageWidth = canvasImage.getWidth(this);
imageHeight = canvasImage.getHeight(this);

if (tracker.checkAll(true)) {
if (tracker.isErrorAny()) {
System.err.println("Error loading this canvasImage: "
+ canvasImage);
}
}

//Component-initiated resizing
resize(imageWidth, imageHeight);
parentContainer.validate();

renderImage = createImage(imageWidth, imageHeight);


renderImageGraphics = renderImage.getGraphics();
renderImageGraphics.setColor(Color.black);
renderImageGraphics.drawImage(canvasImage, 0, 0, this);

for(int i=0; i<drawVect.size(); i++){


Drawable d = (Drawable)drawVect.elementAt(i);
System.err.println("drawVect Element: " + i);
d.draw(renderImageGraphics);
}

renderImageGraphics.setColor(Color.black);
//draw border around image
renderImageGraphics.drawRect(0, 0, imageWidth - 1, imageHeight
- 1);
//draw buffered image
g.drawImage(renderImage, 0, 0, this);
}
}

Das könnte Ihnen auch gefallen