I want to update a record in the DB from my menu

Hi everybody,

I have an menu applet and I want to fill a DB record when i choose an item from my menu.

This is my code and I want a connection with the database to update the record word_path:

please help me !!

thanks in advance

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import java.net.*;

import java.util.*;

import netscape.javascript.*;

public class PopupMenuApplet extends Applet implements MouseListener, ActionListener {

String title, img, bgcolor, text, font, size, style, menufont, menustyle, menusize, data;

String actions[], targets[];

Menu menus[];

MenuItem menuItems[];

int fontsize, menufontsize;

CardLayout cardlayout;

PopupMenu mainMenu;

Image bgImage = null;

boolean parseError = false, imgError = false;

URL imgUrl;

Label label;

Font labelFont, menuFont;

//Construct the applet

public PopupMenuApplet() {

}

//Initialize the applet

public void init() {

cardlayout = new CardLayout();

title = getParameter("title");

if (title == null) title = "Menu";

// the colors for bgcolor and text are used only for the applet label

// Java 1.1 menus themselves don't support colors, although some Unix implementations

// allow a menu's background color to be inherited from the object it's attached to.

bgcolor = getParameter("bgcolor");

if (bgcolor == null) bgcolor = "white";

else bgcolor = bgcolor.toLowerCase();

text = getParameter("text");

if (text == null) text = "blue";

else text = text.toLowerCase();

// font, size and style are used for the applet's text label (if any)

font = getParameter("font");

if (font == null) font = "SansSerif";

size = getParameter("size");

if (size == null) fontsize = 11;

else

try {

fontsize = Integer.parseInt(size);

} catch(NumberFormatException f) {

fontsize = 11;

}

style = getParameter("style");

if (style == null) style = "plain";

labelFont = new Font(font, translateStyle(style), fontsize);

// menufont, menusize and menustyle default to font, size and style if undefined,

// but they can be also defined explicitely in case we want the popup menu to look different

// from the applet's text label (if any)

menufont = getParameter("menufont");

if (menufont == null) menufont = font;

menusize = getParameter("menusize");

if (menusize == null) menufontsize = fontsize;

else

try {

menufontsize = Integer.parseInt(menusize);

} catch(NumberFormatException f) {

menufontsize = 11;

}

menustyle = getParameter("menustyle");

if (menustyle == null) menustyle = style;

menuFont = new Font(menufont, translateStyle(menustyle), menufontsize);

data = getParameter("data");

parseData(data);

this.addMouseListener(this);

this.setBackground(translateColor(bgcolor));

this.setForeground(translateColor(text));

this.setFont(labelFont);

this.setLayout(cardlayout);

img = getParameter("img");

if (img != null) {

try { // absolute URL

imgUrl = new URL(img);

bgImage = this.getImage(imgUrl);

} catch(MalformedURLException a) {

try { // relative URL

imgUrl = new URL(this.getDocumentBase(), img);

bgImage = this.getImage(imgUrl);

} catch(MalformedURLException r) {

imgError = true;

}

}

bgImage = this.getImage(this.getDocumentBase(), img);

} else {

label = new Label(title);

label.setAlignment(1);

label.addMouseListener(this);

this.add(title, label);

}

}

//Start the applet

public void start() {

}

//Stop the applet

public void stop() {

}

//Destroy the applet

public void destroy() {

}

//Get Applet information

public String getAppletInfo() {

return(

"Title:\t\tPopupMenuApplet\n" +

"Version:\t1.1.1\n" +

"Date:\t\t11/15/2001\n" +

"Author:\t\tErwin (http://www.centric.nl/)\n" +

"Description:\tA configurable menu applet based on the\n" +

"\t\tJava (TM) 1.1 PopupMenu class."

);

}

//Get parameter info

public String[][] getParameterInfo() {

String pinfo[][] =

{

{"title", "String", "Menu title"},

{"img", "URL", "Background image"},

{"bgcolor", "Color or Hex RGB value", "Menu background color"},

{"text", "Color or Hex RGB value", "Menu foreground color"},

{"font", "Font name", "Menu font name"},

{"size", "Integer", "Menu font size"},

{"style", "Sum of BOLD,PLAIN,ITALIC", "Menu font style"},

{"menufont", "Font name", "Menu font name"},

{"menusize", "Integer", "Menu font size"},

{"menustyle", "Sum of BOLD,PLAIN,ITALIC", "Menu font style"},

{"data", "Menu item names, actions and targets", "Menu data"},

};

return pinfo;

}

public void paint(Graphics g) {

if (bgImage != null)

g.drawImage(bgImage,0,0,this);

if (imgError)

this.showStatus("PopupMenuApplet: invalid URL for img parameter " + img);

if (parseError)

this.showStatus("PopupMenuApplet Error: unbalanced braces in data parameter tag.");

}

public void mousePressed(MouseEvent e) {

}

public void mouseReleased(MouseEvent e) {

}

public void mouseClicked(MouseEvent e) {

popup();

}

public void mouseEntered(MouseEvent e) {

popup();

}

public void mouseExited(MouseEvent e) {

}

public void actionPerformed(ActionEvent e) {

int elt = Integer.parseInt(e.getActionCommand());

String cmd = actions[elt];

String target = targets[elt];

if (cmd.length() > 7 && cmd.substring(0,7).equalsIgnoreCase("script=")) {

// catch exception thrown by the appletviewer (but not a browser)

// just so we can test the menu appearance with the appletviewer.

try {

cmd = cmd.substring(7); // trim the "script=" identifier

if (target.equalsIgnoreCase("_self") || target.equalsIgnoreCase("_parent")

|| target.equalsIgnoreCase("_top"))

target = target.substring(1).toLowerCase(); // allow for leading underscore HTML syntax

cmd = target + "." + cmd;

JSObject win = JSObject.getWindow(this);

win.eval(cmd);

} catch(Exception n) {

this.showStatus("PopupMenuApplet: Error running script " + cmd);

}

} else {

try { // absolute URL

URL dest = new URL(cmd);

this.getAppletContext().showDocument(dest, target);

} catch(MalformedURLException a) {

try { // relative URL

URL dest = new URL(this.getDocumentBase(), cmd);

this.getAppletContext().showDocument(dest, target);

} catch(MalformedURLException r) {

this.showStatus("PopupMenuApplet: invalid URL " + cmd);

}

}

}

}

public void popup() {

if (!parseError)

mainMenu.show(this,this.getSize().width/2,this.getSize().height/2);

}

private Color translateColor(String c) {

if(c.equalsIgnoreCase("white"))

return(Color.white);

else if(c.equalsIgnoreCase("lightgray"))

return(Color.lightGray);

else if(c.equalsIgnoreCase("gray"))

return(Color.gray);

else if(c.equalsIgnoreCase("darkgray"))

return(Color.darkGray);

else if(c.equalsIgnoreCase("black"))

return(Color.black);

else if(c.equalsIgnoreCase("red"))

return(Color.red);

else if(c.equalsIgnoreCase("pink"))

return(Color.pink);

else if(c.equalsIgnoreCase("orange"))

return(Color.orange);

else if(c.equalsIgnoreCase("yellow"))

return(Color.yellow);

else if(c.equalsIgnoreCase("green"))

return(Color.green);

else if(c.equalsIgnoreCase("magenta"))

return(Color.magenta);

else if(c.equalsIgnoreCase("cyan"))

return(Color.cyan);

else if(c.equalsIgnoreCase("blue"))

return(Color.blue);

// allow for Hex RGB values (and an optional leading #, as in HTML syntax)

else if (c.length() == 6 || (c.length() == 7 && c.charAt(0) == '#')) {

if (c.length() == 7)

c = c.substring(1);

return(new Color(hexToInt(c.substring(0,2)),

hexToInt(c.substring(2,4)),hexToInt(c.substring(4,6))));

}

else

return(Color.white);

}

private int hexToInt(String c) {

try {

return(Integer.parseInt(c, 16));

} catch(NumberFormatException h) {

return 0;

}

}

private int translateStyle(String s) {

int style = 0;

String token = null;

StringTokenizer st = new StringTokenizer(s,",+ \t\n\r");

do {

try {

token = st.nextToken();

} catch(NoSuchElementException n) {}

if (token.equalsIgnoreCase("PLAIN"))

style += Font.PLAIN;

else if (token.equalsIgnoreCase("BOLD"))

style += Font.BOLD;

else if (token.equalsIgnoreCase("ITALIC"))

style += Font.ITALIC;

} while (st.hasMoreTokens());

return style;

}

private void parseData(String s) {

// menuItem counters start at -1 so that at first increment, they get set to

// the first array subscript value of 0

// menu counters start at 0 so that at first increment, they get set to

// the array subscript value of 1, the first value (0) being reserved for the main menu

int levelCtr = -1, menuCtr = 0, menuItemCtr = -1;

int levelCount = 0, menuCount = 0, menuItemCount = -1;

int parentMenuPtr[];

String itemToken = null, datatoken = null;

String title = "", action = "", target = "_self";

boolean newMenu = false;

if (s == null || s.indexOf("{") == -1) {

parseError = true;

return;

}

StringTokenizer braces = new StringTokenizer(s,"{}",true);

StringTokenizer braceCtr = new StringTokenizer(s,"{}",true);

StringTokenizer asterisks;

// Get the number of menus and menuItems for which to allocate array space

do {

try {

itemToken = braceCtr.nextToken();

} catch(NoSuchElementException i) {}

if (itemToken.charAt(0) == '{') {

if (newMenu)

menuCount++;

newMenu = true;

levelCtr++;

if (levelCount < levelCtr) levelCount = levelCtr;

} else if (itemToken.charAt(0) == '}') {

if (newMenu)

menuItemCount++;

newMenu = false;

levelCtr--;

}

} while (braceCtr.hasMoreTokens());

if (levelCtr != -1) {

parseError = true;

return;

}

// allocate one more element than the counter values , since the first subscript value is 0

actions = new String[menuItemCount+1];

targets = new String[menuItemCount+1];

menuItems = new MenuItem[menuItemCount+1];

menus = new Menu[menuCount+1];

parentMenuPtr = new int[levelCount+1];

mainMenu = new PopupMenu(title);

menus[0] = (Menu)(mainMenu);

this.add(mainMenu);

itemToken = null;

newMenu = false;

// Parse the data Param and build the menu and menu items

do {

try {

itemToken = braces.nextToken();

} catch(NoSuchElementException i) {}

if (itemToken.charAt(0) == '{') {

if (newMenu) {

menuCtr++;

menus[menuCtr] = new Menu(title);

menus[menuCtr].setFont(menuFont);

menus[parentMenuPtr[levelCtr]].add(menus[menuCtr]);

parentMenuPtr[levelCtr+1] = menuCtr;

}

newMenu = true;

levelCtr++;

} else if (itemToken.charAt(0) == '}') {

if (newMenu) {

menuItemCtr++;

actions[menuItemCtr] = action;

targets[menuItemCtr] = target;

menuItems[menuItemCtr] = new MenuItem(title);

menuItems[menuItemCtr].setFont(menuFont);

menuItems[menuItemCtr].addActionListener(this);

menuItems[menuItemCtr].setActionCommand(new Integer(menuItemCtr).toString());

menus[parentMenuPtr[levelCtr]].add(menuItems[menuItemCtr]);

}

newMenu = false;

levelCtr--;

} else if (!itemToken.trim().equals("")) {

asterisks = new StringTokenizer(itemToken,"*");

try {

title = asterisks.nextToken();

// a menu separator is a -, but allow for hr as well, as in HTML syntax

if (title.equals("-") || title.equalsIgnoreCase("HR"))

title = "-";

} catch(NoSuchElementException i) {

title = "-";

}

try {

action = asterisks.nextToken();

} catch(NoSuchElementException i) {

action = "";

}

try {

target = asterisks.nextToken();

} catch(NoSuchElementException i) {

target = "_self";

}

}

} while (braces.hasMoreTokens());

}

}

[13069 byte] By [Erwin8] at [2007-9-26 12:47:45]
# 1

I don't think I understand where your problem is, you want to add database access to this Applet right? Well you already have an actionListener() which handles the actions on your Menu's and does some kind of URL post.Is this where you want to replace with Database commands? This is where I'm confused. Or are you trying to add databae commands in conjunction with the URL actions, or do you want the page that the Applet lives on to do the database commands?

bryanwclark at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
Yes, I want the actionListener part, where an URL is called, out and replaced with database commands to update a record.
Erwin8 at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3
Ok, so do you know how you want to access your Database, are you going to use EJB's or try direct access to the Database from the Applet?
bryanwclark at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4
I prefer direct access to the DB
Erwin8 at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

Ok, well you'll need to do something like this. Now this part is a little dependent on your database server:

try {

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

Connection c = DriverManager.getConnection(

"jdbc:mysql://{database-server}/{database-name}:3306?user={username}&password={password}");

Statement Stmt = c.createStatement();

int count = Stmt.executeUpdate(cmd);

if(count>0) {

System.out.println("count: " + count);

}

} catch (Exception e) {

e.printStackTrace();

}

}

That was some sample code for a MySQL database.

Note that the applet can only contact the server that is was loaded from, so you might want to do a getCodeBase() or something like that to get the server address.

Hope this is helpful.

bryanwclark at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6
It's all greek to me, really.There are so many errors, and illegal caracters.He even doesn't recognize the symbol "
Erwin8 at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7

OK, I've got the following error messages:

- class JSObject is not found in class

He doesn't recognize hte JSObject, should I set my classpath to be able to compile my code? He doesn't recognize hte JSObject

- incompatible types

what's supposed to be:if(count>0)

Erwin8 at 2007-7-2 12:19:18 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...