Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How would I...

 
jen sol
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would I replace Java applet created dynamic hyperlinks with buttons that accomplish the same purpose?

The powers that be decided that click links are "too 90s" and would like to see buttons replace them.

As stated once before, I am familiar enough with Java to really cause problems :roll:

Thanks in advance,
Jen
 
Joe Ess
Bartender
Posts: 9339
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm confused by the wording "applet created dynamic hyperlinks"
Do you want an applet that loads a particular link depending on which button is pressed? Look at java.applet.AppletContext.showDocument()
Do you want hyperlinks that look like buttons?

Note that the "x" in the above code should be changed to a "k". JavaRanch is apparently succeptible to some sort of JavaScript vulnerability and won't let me spell it correctly. . .

[ September 07, 2004: Message edited by: Joe Ess ]
[ September 07, 2004: Message edited by: Joe Ess ]
 
jen sol
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the applet creates the hyperlink based on the real estate information found on a particular parcel of land.

So if I have parcel 110, then applet currently displays a root (the beginning parcel) then if it was sold, the code Trans on a child off the root with a hyperlink to the scanned public document. Its easier seen than explained. Here is the test page. As you can see, I am on #4 attempt (not counting the numerous: Well, hmmm. Let me try... ones) that I thought had promise, but it didnt.

http://www.geocities.com/jenharrymn/pidtree4.html

The testpage doesnt link back into the database. Its just there for me to play with

Jen

They want buttons (with the appropriate labels or picture icons) instead of hyperlinks.
[ September 07, 2004: Message edited by: jen sol ]
 
Joe Ess
Bartender
Posts: 9339
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, a Swing question. The display of tree elements is handled by something called a Renderer. What you are using is a DefaultTreeCellRenderer, which extends JLabel, so it appears as text. What you should probably do is create a new tree cell renderer which implements java.swing.tree.TreeCellRenderer and extends JButton. If it seems confusing, that's because it is. But Swing is also extremely flexible. You should take a look at The Java Tutorial: How To Use Trees. Unfortunately the trees tutorial does not cover using renderers, so take a look at How To Use Tables - Editors and Renderers. It covers creating Renderers for JTable, but the same concepts apply to JTree.
BTW, bookmark the Java Tutorial. Has examples for pretty much everything.
 
jen sol
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well after wrestling with my applet, I have managed to get myself backed into a corner with how I try to build a URL. I get a > where I shouldnt. I also will get an Out of Bounds Error if I try to reload the page. When I clear the cache and wait a little bit, then I get a URL error.

I think it is occuring in this par of my code:

private StringBuffer setHyperlinks(String p) {
StringBuffer hyperP = new StringBuffer(120);
int j = p.lastIndexOf(","); //start of form params
int i = p.indexOf("$"); //end of pid
if (i >= 0) {
String p1;
if (j >= 0) {
hyperP.append("<HTML><img src=url><A HREF=\"?");
hyperP.append(p.substring(j + 1));
hyperP.append("\">");
p1 = p.substring(0, j);
} else {
hyperP.append("<HTML><img src=url><A HREF=\"\">");
p1 = p;
}
hyperP.append(p1.substring(0, i));
hyperP.append("</A>");
//hyperP.append(p1.substring(i));
hyperP.append("</HTML>");
} else {
//no hyperlink needed; but ^ means make it bold
i = p.indexOf("^");
if (i >= 0) {
hyperP.append("<HTML><B>");
hyperP.append(p.substring(0, i));
hyperP.append("</B>");
hyperP.append(p.substring(i));
hyperP.append("</HTML>");
} else {
//no special format needed
hyperP.append(p);
}
}
return hyperP;
}

I added the img src=url part as I am trying to have a little picture be the link instead of a long line of mumbo jumbo (basically a concat of several identifiers for a piece of land).

Here is the test page: http://www.geocities.com/jenharrymn/javatester2.html

I am thinking that the img src= url part would be causing the part of the error at java.lang.String.substring(Unknown Source).

Any ideas or nudges in the right direction?

Thanks in advance,
Jen
[ September 14, 2004: Message edited by: jen sol ]
 
Joe Ess
Bartender
Posts: 9339
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get the following when I go to that link:


Note that the stack trace tells you the line number where the exception occurs. Knowing is half the battle.
Don't be afraid to pepper your code with System.out.println statements to make sure you are getting the arguments in the right format, getting the indexes you think you are getting and so on.
 
jen sol
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks again, Joe.

Have I mentioned before I really dislike working on someone else's code?

Back to the deciphering...
Jen
 
jen sol
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Joe. Me again. I have tried educating myself on the web and in the java tutorials, but I am stymied. The "web guy" wants images-as-buttons(ala href type thing) instead of the current clicky links. What am I mis-reading in the tutorials that I cant seem to get just one image (other than the infamous "Gray Box with Red X" to even appear?

Below, please find my mediocre attempt at accomplishing this. Last time I uploaded an applet, I was getting an exception error (which makes me think I forgot to put something in that the program is looking for).

This program was written by someone no longer employed here (having moved onto other pastures) and I am the only person that can read Java and get a rough idea what the program is trying to do.
(I hope this holds some of its formatting or at the very least will left adjust...)

public class PIDTree extends JApplet {
/** Contains the dataxxx parameter values */
private Vector params = new Vector(50);

/** Maximum display len of PID. Max len is 25 char */
private double dsplyWidth = 0;

/** Font is monospaced */
private Font myFont = new Font("Monospaced", Font.PLAIN, 12);

/** Patterns used in regular expressions to parse
* dataxxx parameter values */
private Pattern[] pat = {Pattern.compile("[S]"),
Pattern.compile("[T]"),
Pattern.compile("[E]"),
Pattern.compile("[X]"),
Pattern.compile("[x]"),
Pattern.compile("[Y]"),
Pattern.compile("[y]"),
Pattern.compile("[$^]")};

/** Pattern Matcher values for pat[0] thru pat[max] */
private static int maxTranTypes = 8;
private Matcher[] m = new Matcher[maxTranTypes];

/** Boolean array used in pattern matching */
private boolean[] b = new boolean[maxTranTypes];

/** Root node of the tree. It is parameter data0 */
DefaultMutableTreeNode rootPID = null;

/** Swing frame for GUI representation of the tree */
private JFrame frame = new JFrame("SOLUTIONS, INC: Splits, Consolidations and Transactions Viewer");

/**
* Initialization the PIDTree applet includes using the
* current L&F, building the GUI, setting up a listener
* for changing the tree node selection and setting up
* a listener for a double click on a PID (which
* then calls a program to display the tree using the
* selected PID as the root.
*/
public void init() {
//change to current system look & feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
//ignore
}
frame.setFont(myFont);

params = getPIDInfo();
rootPID = createNodes();

final JTree tree = new JTree(rootPID);
tree.setRowHeight(-1); //set ht to -1 pix--self adjusting; bug #4232709
tree.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);

//Set icon & row height
tree.setCellRenderer(new MyRenderer());

//Create the scroll pane and add the editor pane to it
JScrollPane treeView = new JScrollPane(tree);
treeView.setPreferredSize(new Dimension(650,400));

getContentPane().add(treeView, BorderLayout.CENTER);

//Listen for when the selection changes.
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
}
});

//Listen for double click
final JSObject win = JSObject.getWindow(this);
tree.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
//be sure dbl click was on highlighted node
if (!tree.getPathBounds(tree.getSelectionPath()).contains(e.getX(), e.getY()))
{return;}
//find <a> tag and execute it
Object nodeInfo = node.getUserObject();

//get PID to pass to javascript function
String line = nodeInfo.toString();
int i = line.indexOf("?");
int j = line.indexOf("\"",i+1);
if (i>=0) {
Object[] tStamp = {(Object)line.substring(i+1,j)};
//call javascript function frm
win.call("frm", tStamp);
} //end if hot linked
} //end if
} //end mouseClicked
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});

//listen for mouse over hyperlink
tree.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
tree.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (selRow > 0) {
Rectangle selRect = tree.getRowBounds(selRow);
if (e.getX() <= dsplyWidth + selRect.x) {
tree.setCursor(new Cursor(Cursor.HAND_CURSOR));}
}
}
public void mouseDragged(MouseEvent e) {}
});
}

/**
* Read the applet parameters
*/
private Vector getPIDInfo() {
int j,tmp;
StringBuffer hyperP = new StringBuffer(100);
String p;
String[] desc = {"Split ", "Trans ", " ", "XConsol",
"I-XCnsl", "Consol", "I-Cnsl"};
int i = 0;
Vector params = new Vector(50);

p = getParameter("data"+i);
while (p != null) {
//expand S,T,E,X,x,Y,y to words
for (j=0;j<=maxTranTypes-2;j++) {b[j]=false;}
for (j=0;j<=maxTranTypes-2;j++) {
m[j] = pat[j].matcher(p);
b[j] = m[j].find();
if (b[j]) {
p = m[j].replaceAll(desc[j]);
break;
} //end if (b[j])
} //end for
tmp = p.indexOf(",");
//add hyperlinks
hyperP=setHyperlinks(p);
params.insertElementAt(hyperP.toString(),i);
i++;
p = getParameter("data"+i);
} //end while (p!=null)
return params;
}
/**
* add Html tags to make the (non-root) PIDs hot
*/
private StringBuffer setHyperlinks(String p) {
StringBuffer hyperP = new StringBuffer(100);
String p1; //Is the numeral 1

int j = p.lastIndexOf(","); //start of form params

int i = p.indexOf("$"); //end of pid

if (i >= 0) {
hyperP.insert(0,"<HTML><A HREF=\">");
hyperP.append(p.substring(j + 1));
hyperP.append("\">");
p1 = p.substring(0, j);
} else {
hyperP.insert(0,"<HTML><A HREF=\">");
p1 = p + 1;
hyperP.append(p1.substring(i)); //~~~~~~~~~~~~~~~~~~~~~~~~~~~
hyperP.append("<img src=\"leaf.gif\"></A>");
hyperP.append(p1.substring(i));
hyperP.append("</HTML>");
}
//no hyperlink needed; but ^ means make it bold
i = p.indexOf("^");
if (i >= 0) {
hyperP.append("<HTML><B>");
hyperP.append(p.substring(0, i));
hyperP.append("</B>");
hyperP.append(p.substring(i));
hyperP.append("<HTML>");
} else {
//no special format needed
hyperP.append(p);
}
return hyperP;
} //end setHyperlinks

/**
* Create the tree
*/
private DefaultMutableTreeNode createNodes() {
int tmp, tmp1, levelNum;
String data, ln, p;
StringBuffer sb = new StringBuffer(256);
DefaultMutableTreeNode rootPID = null;
DefaultMutableTreeNode childPID = null;
DefaultMutableTreeNode nextPID = null;
int treeDepth = 0;
int crntLevel = 0;
int lastOne = pat.length-1;

for (int j = 0; j <= params.size() - 1; j++) {
ln = (String)params.elementAt(j);
//add spacing so it appears in columns
p = "      "; // 6 spaces
tmp = ln.indexOf(","); //searching for a comma
tmp1 = ln.indexOf("</HTML>"); //searching for </HTML>
if (tmp1 < tmp) {tmp1=ln.length();} //in case no <HTML> code on this line
levelNum = Integer.valueOf(ln.substring(tmp + 1)).intValue();
data = ln.substring(0,tmp) + ln.substring(tmp1); //pid,etc
sb.setLength(0);
m[lastOne] = pat[lastOne].matcher(data); //replace $ w/ appropriate # of spaces
b[lastOne] = m[lastOne].find();
if (b[lastOne]) {
m[lastOne].appendReplacement(sb,p); //first one get calc # of spaces
b[lastOne] = m[lastOne].find();
m[lastOne].appendReplacement(sb,p); //2nd gets fixed # of spaces
b[lastOne] = m[lastOne].find();
m[lastOne].appendTail(sb);
data=sb.toString();
}

if (levelNum <= 0) { //this is the root; add it
levelNum = 0;
rootPID = new DefaultMutableTreeNode(data);
nextPID = (DefaultMutableTreeNode) rootPID.getRoot();
//calc max display len of PID
Graphics2D g = (Graphics2D)this.getGraphics();
TextLayout tl = new TextLayout(rootPID.toString().substring(0,24),myFont,
g.getFontRenderContext());
dsplyWidth = tl.getBounds().getWidth();
} else {
//this is a child node which belongs to the last
//node with the level number minus one
childPID = new DefaultMutableTreeNode(data);
treeDepth = rootPID.getDepth();
if (treeDepth + 1 < levelNum) {
System.out.println("Data file has error in level #" +
levelNum + " record is " + data);
} else {
//valid level insert node after finding parent
crntLevel = nextPID.getLevel();
while (crntLevel + 1 > levelNum) {
nextPID = (DefaultMutableTreeNode) nextPID.getPreviousNode();
crntLevel = nextPID.getLevel();
} //end while (!done)
if (!nextPID.isRoot())
while (nextPID.getNextSibling() != null)
{nextPID = (DefaultMutableTreeNode) nextPID.getNextSibling();}
nextPID.add(childPID); //insert into tree
nextPID = childPID;
} //end if (rootPID.getDepth()+1<leveNum)
} //end if (levelNum == 0)
} //end for
return rootPID;
}

/**
* MyRenderer is a DefaultTreeCellRenderer which displays
* custom icons for the tree.
*/
class MyRenderer extends DefaultTreeCellRenderer {
//Change icons to custom gifs
ImageIcon iconSplit, iconPID, iconTrans, iconXConsol, iconLeaf;
ImageIcon iconConsol, iconConsolGray, iconXConsolGray;
/**
* There are max gif files that contain 16x16 pixel
* images. These files are expected to be on the same
* drive as the java class file but in the
* <b>com/gmdsolutions/applets/realestate/icons</b>
* directory. The files are:
* <ul>
* <li>split.gif       Split</li>
* <li>consol.gif      Consolidation</li>
* <li>congray.gif     Inactive Consolidation</li>
* <li>pid.gif         Property ID</li>
* <li>trns.gif        Transaction</li>
* <li>xconsol.gif    Complex Consolidation</li>
* <li>xcongray.gif  Inactive Complex Consolidation</li>
* <li>leaf.gif    Current State</li>
* </ul>
**/
public MyRenderer() {
URL url = PIDTree.class.getResource("split.gif");
iconSplit = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("consol.gif");
iconConsol = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("congray.gif");
iconConsolGray = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("pid.gif");
iconPID = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("trns.gif");
iconTrans = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("xconsol.gif");
iconXConsol = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("xcongray.gif");
iconXConsolGray = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
url = PIDTree.class.getResource("leaf.gif");
iconLeaf = new ImageIcon(Toolkit.getDefaultToolkit().getImage(url));
setFont(myFont);


} //end MyRenderer

/**
* see bug #4743195; warning this implementation is said to
* significantly slow the execution of this applet. However,
* it is necessary to use this method with Windows L&F.
*/
protected void firePropertyChange(String propertyName, Object oldVal, Object newVal) {
if (propertyName=="foreground") {propertyName="text";}
super.firePropertyChange(propertyName, oldVal, newVal);
} //end firePropertyChange

/**
* Determines which icon should be used for each node in the tree
* @return DefaultTreeCellRenderer with the appropriate icon set
*/
public Component getTreeCellRendererComponent (JTree tree, Object val,
boolean sel, boolean expd,
boolean leaf, int rw,
boolean hasFocus) {
super.getTreeCellRendererComponent(tree, val, sel, expd, leaf, rw, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)val;
if (node.isRoot()) {
setIcon(iconPID);
} else {
String nodeType = node.toString();
if (nodeType.indexOf("XConsol") >= 0) {setIcon(iconXConsol);}
else {
if (nodeType.indexOf("Trans") >= 0) {setIcon(iconTrans);}
else {
if (nodeType.indexOf("Split") >= 0) {setIcon(iconSplit);}
else {
if (nodeType.indexOf("Consol") >= 0) {setIcon(iconConsol);}
else {
if (nodeType.indexOf("I-XCnsl") >= 0) {setIcon(iconXConsolGray);}
else {
if (nodeType.indexOf("I-Cnsl") >= 0) {setIcon(iconConsolGray);}
else {setIcon(iconLeaf);}
} //inactive consolidation
} // inactive complex consolidation
} //end consolidation
} // end transaction chk
} //end complex consolidation chk
} //end all ifs
return this;
} //end getTreeCellRendererComponent
} //end of class MyRenderer

} //ends PIDTree

Thanks in advance for any help. I really appreciate the punts in the right direction.

Jen
[ September 27, 2004: Message edited by: jen sol ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic