Is it OK to remove this code?

Hi, I removed this line:    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
from the top of every web page I have since I thought it was just not needed and could slow down the web spyders when reading my page. Now my page starts with: <html>
Is that OK or the line I removed need to be there?
Was this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
Changed to this:
<html>
<head>

You say this is the simplest and cleanest doctype, so is it better to use this doctype: <!DOCTYPE HTML> or the doctype created by my web app: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
Use either one.  But bear in mind that your PRIMARY goal would be to produce pages that validate.  If you use the HTML 5 doctype, yet write your pages with HTML 4.01 Transitional usages, the page will not validate because of those and you will be faced with the prospect of visually eliminating them from the list when you are looking for potential layout anomaly-causing errors.
Which one IYO will be better for SEO, web spyders, web robots and will load faster?
1)     <!DOCTYPE HTML>
or
2)     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
It will make no difference whatsoever.

Similar Messages

  • Can I remove this code from header?

    function MM_findObj(n, d) { //v4.01
      var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
      if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
      for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
      if(!x && d.getElementById) x=d.getElementById(n); return x;
    I'm cleaning up an old website with much extraneous code in HEAD section.
    There are no rollovers or frames on the site. Can I lose this?
    The messy pages are on www.fearlessselling.net
    Many thanks for your kindness.

    I checked your entire site, I think.  The only place it is used, or found, fo rthat matter, is on the home page where you DO use it for the mouseover function on the
    "Listen to our BlogTalk Radio Program"
    link.
    So, if you want that mouseover to work, you need to leave all the head functions in place.
    E. Michael Brandt
    www.divahtml.com
    www.divahtml.com/products/scripts_dreamweaver_extensions.php
    Standards-compliant scripts and Dreamweaver Extensions
    www.valleywebdesigns.com/vwd_Vdw.asp
    JustSo PictureWindow
    JustSo PhotoAlbum, et alia

  • 6131 Remove Protection Code

    I have a phone 6131 and I want to know if I can remove Protection Code. How can I remove the Protection Code?
    Always the phone off, when I put on the phone ask me Protecion Code. It's possible to remove this Code?
    Hope in a reply.
    Tanks,
    Fabbris Pierluigi

    It'll be somewhere in your options, try reading the manual it should tell you in there how to turn it off.
    I have a 6131 too, but I cant seem to find a protection code option
    Nokia phones i have owned to date:
    5110,3210, 3310,3330,8210,6510,3220,n90,6131

  • //remove this line if you want to edit the code by hand? um which line?

    Several of my pages are locking up and I don't know why. As I work through the code, I remembered that I altered some text in a SendEmail by directly altering the page rather than using the Server Behavior. Don't understand why that would matter but whatever...
    Now as I ponder if that is causing the problem, I ran across this commented line in the code:
    //remove this line if you want to edit the code by hand
    But are they talking about the line just after that line of //remove or do they mean the actual comment line of
    //remove this line if you want to edit the code by hand?
    Thanks for your help

    Trigger and $tNG look suspiciously like ADDT code to me. Ask the guys in the ADDT forum (http://forums.adobe.com/community/dreamweaver/addt). There are a couple of them in there who know the code intimately. I haven't touched ADDT for ages.

  • I have just tried to sync my iphone. Error message saying it cannot be synced has popped up quoting error code (-50). I have just removed old iphone backups from itunes but was very careful to not delete the current one. What does this code mean?

    Hi there,
    I have just tried to sync my iphone.
    Worryingly an error message saying it cannot be synced has popped up quoting error code (-50)
    I have just removed old iphone backups from itunes but was very careful to not delete the current one
    What does this code mean?

    http://support.apple.com/kb/TS1583

  • Can anybody tell me the problem with this code when compiled in jdk1.4

    Can anybody help me find out the error in this code.
    Try to drag a file from your desktop and drop it on the first textpane on my GUI. Then try to drag another file. This time the dragdrop event handler throws a null pointer exception. This happened when I compiled the code with jdk1.4. With jdk1.3 it is working fine. Actually, I need jdk1.4 to get the systemicons for the files I drop on my desktop.
    /* Client.java*/
    import java.util.Vector;
    import java.util.Enumeration;
    import java.util.Arrays;
    import java.awt.*;
    import java.awt.event.*;
    import java.rmi.*;
    import java.rmi.server.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.filechooser.*;
    import java.io.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    import java.util.Iterator;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import java.util.Hashtable;
    import javax.swing.text.*;
    import javax.swing.event.*;
    public class Client extends JFrame{
    static String newline = System.getProperty("line.separator");
    static Client client;
         //ServerInterface server;
         //ClientProperties clp;
         Vector v1=new Vector();
         ByteArrayOutputStream out;
         Runtime r1;
         //file objects,together with array of bytes
         Hashtable files=new Hashtable(); //files sent
         Hashtable rfiles=new Hashtable(); //files received
         //file objects,together with button handlers
         Hashtable hfiles=new Hashtable(); //files sent,files received
         JButton button1=new JButton();
         JButton button2=new JButton();
         JButton button3=new JButton();
         JLabel label1=new JLabel();
         JLabel label2=new JLabel();
         JLabel label3=new JLabel();
         JLabel label4=new JLabel();
         JLabel label5=new JLabel();
         JLabel label6=new JLabel();
         JLabel label7=new JLabel();
         JLabel label8=new JLabel();
         JOptionPane dialog=new JOptionPane();
         JFileChooser chooser = new JFileChooser();
         JPanel panel1;
         JPanel panel2;
         DropTarget dtarget;
         DragSource dsource;
         JTextPane textArea1=new JTextPane();
         TextArea textArea2=new TextArea();
         JTextPane textpanel=new JTextPane();
         Style defstyle,style;
         StyledDocument doc,doc1;
         JPopupMenu popup;
         JTree tree;
         JScrollPane jsppane;
         JScrollPane jsp,jsp2;
         DefaultMutableTreeNode top;
         Container cp;
         private String toalias;
         private String togroup;
    private String fromalias;
         private String fromgroup;     
         private boolean CONNECT;
         public Client()
         cp=getContentPane();
         cp.setLayout(null);
              setForeground(java.awt.Color.red);
              setFont(new Font("Dialog", Font.PLAIN, 14));
              setVisible(false);
              label1.setText(" CHAT APPLICATION");
              cp.add(label1);
              label1.setFont(new Font("Dialog", Font.BOLD, 16));
              label1.setBounds(72,20,319,30);
              label2.setText("List of Users Connected.");
              cp.add(label2);
              label2.setForeground(java.awt.Color.blue);
              label2.setFont(new Font("Dialog", Font.BOLD, 12));
              label2.setBounds(24,60,192,26);
              label8.setBounds(280,60,100,26);
              cp.add(label8);
              cp.add(textArea2);
              textArea2.setBounds(204,120,268,90);
              jsppane=new JScrollPane(textArea1);
              doc1=textArea1.getStyledDocument();
              jsppane.setBounds(12,264,456,109);
              cp.add(jsppane);
              label3.setText("TO::");
              cp.add(label3);
              label3.setFont(new Font("Dialog", Font.BOLD, 12));
              label3.setBounds(12,228,36,20);
              cp.add(label4);
              label4.setBackground(java.awt.Color.lightGray);
              label4.setBounds(60,228,172,19);
              label5.setText("SERVER RESPONSE");
              cp.add(label5);
              label5.setFont(new Font("Dialog", Font.BOLD, 12));
              label5.setBounds(204,96,204,21);
              label7.setText("MESSAGE FOR YOU.");
              cp.add(label7);
              label7.setFont(new Font("Dialog", Font.BOLD, 14));
         label7.setBounds(12,371,288,25);
         jsp2=new JScrollPane(textpanel);
         setTextPaneStyle();
    jsp2.setBounds(12,401,456,109);
    cp.add(jsp2);
    button1.setLabel("Send");
              button1.setEnabled(false);
              cp.add(button1);
              button1.setBackground(java.awt.Color.lightGray);
              button1.setForeground(java.awt.Color.black);
              button1.setFont(new Font("Dialog", Font.BOLD|Font.ITALIC, 10));
              button1.setBounds(60,520,78,36);
              button2.setLabel("Attach");
              //button2.setEnabled(false);
              cp.add(button2);
              button2.setBackground(java.awt.Color.lightGray);
              button2.setForeground(java.awt.Color.black);
              button2.setFont(new Font("Dialog", Font.BOLD|Font.ITALIC, 10));
              button2.setBounds(180,520,72,36);
              button3.setLabel("Connect");
              cp.add(button3);
              button3.setBackground(java.awt.Color.lightGray);
              button3.setForeground(java.awt.Color.black);
              button3.setFont(new Font("Dialog", Font.BOLD|Font.ITALIC, 10));
              button3.setBounds(288,520,72,33);
              setSize(500,620);
         show();
         addWindowListener(new WindowEventHandler());
         button1.addActionListener(new ButtonHandler());     
         button2.addActionListener(new ButtonHandler());     
         button3.addActionListener(new ButtonHandler());
         textArea1.addContainerListener(new ComponentHandler());     
         dtarget=new DropTarget(textArea1,new DragDropHandler());
         textArea2.setEnabled(false);
         textpanel.setEnabled(false);
         r1=Runtime.getRuntime();
         r1.addShutdownHook(new onshutdown());
         addMenu();
         cp.repaint();
         //adds attachments to the textArea1     
         synchronized private void addAttach(java.util.List fileList)
         Iterator iterator=fileList.iterator();
         JButton bw;
         while(iterator.hasNext())
              File file=(File)iterator.next();
              Icon icon=chooser.getIcon(file);
              bw=new JButton(icon);
              bw.setBackground(java.awt.Color.gray);
              bw.setToolTipText(file.getAbsolutePath());
              bw.addMouseListener(new AttachmentHandler());
              Dimension d1=new Dimension(icon.getIconWidth(),icon.getIconHeight());
              bw.setMaximumSize(d1);
              hfiles.put(bw,file);          
              textArea1.insertComponent(bw);
              textArea1.setCaretPosition(doc1.getLength());
              bw.setSize(icon.getIconWidth(),icon.getIconHeight());
              //only one file at a time
              break;
         cp.repaint();
    public void setAudioStream(ByteArrayOutputStream out)
    this.out=out;               
    private void addMenu()
         JMenuBar mbar=new JMenuBar();
         mbar.setVisible(true);
         mbar.setBounds(0,0,500,20);
         mbar.setBackground(java.awt.Color.gray);
         //first menu
         JMenu m1=new JMenu("Connection");
         m1.setBounds(0,0,80,20);
         m1.setBackground(java.awt.Color.gray);
         JMenuItem mitem1=new JMenuItem("Connect");
         JMenuItem mitem2=new JMenuItem("Disconnect");
         m1.add(mitem1);
         m1.add(mitem2);
         mitem1.addActionListener(new ButtonHandler());
         mitem2.addActionListener(new ButtonHandler());
         mbar.add(m1);
         //second menu
         JMenu m2=new JMenu("Send...");
         m2.setBounds(90,0,80,20);
         m2.setBackground(java.awt.Color.gray);
         JMenuItem mitem3=new JMenuItem("Send");
         JMenuItem mitem4=new JMenuItem("Send with Audio...");
         mitem3.addActionListener(new ButtonHandler());
         mitem4.addActionListener(new ButtonHandler());
         m2.add(mitem3);
         m2.add(mitem4);
         mbar.add(m2);
         cp.add(mbar);
    private void setTextPaneStyle()
    StyleContext stylecontext =StyleContext.getDefaultStyleContext();
    defstyle=stylecontext.getStyle(StyleContext.DEFAULT_STYLE);
    doc= textpanel.getStyledDocument();
    //style 1
    style= textpanel.addStyle("bold",defstyle);
    StyleConstants.setBackground(style,Color.white);
    StyleConstants.setForeground(style,Color.blue);
    StyleConstants.setItalic(style, false);
    StyleConstants.setBold(style, true);
    StyleConstants.setFontSize(style,16);
    //style 2
    style= textpanel.addStyle("normal",defstyle);
    StyleConstants.setBackground(style,Color.white);
    StyleConstants.setForeground(style,Color.black);
    StyleConstants.setItalic(style, false);
    StyleConstants.setBold(style, false);
    StyleConstants.setFontSize(style,14);      
    //style3
    style= textpanel.addStyle("attach",defstyle);
    StyleConstants.setBackground(style,Color.white);
    StyleConstants.setForeground(style,Color.red);
    StyleConstants.setItalic(style, true);
    StyleConstants.setBold(style, false);
    StyleConstants.setFontSize(style,12);      
    //remote method called by server
    public void addClient(String alias,String group,JTree tree)
         //if old client remove old tree
         if(!alias.equals(""))
         cp.remove(this.jsp);
         //add new tree
         this.tree=tree;
         setTreeModel();
         getSound(2);
         if(!alias.equals(""))
         textArea2.append("\nNew Client:" + alias + "has joined");
         else
         textArea2.append("\nYou have been connected to the Server.");
         jsp=new JScrollPane(this.tree);
    jsp.setBounds(12,96,168,120);
         jsp.setBackground(java.awt.Color.lightGray);
    cp.add(jsp);
    this.tree.addMouseListener(new MouseHandler());
    //remote method called by server
    public void sendMessage(String str,Hashtable rfiles,String alias,String group) throws RemoteException
              receiveMessage(str,rfiles,alias,group);
    //remote method called by server
    public void removeClient(JTree tree,String alias,String group) throws RemoteException
    cp.remove(this.jsp);
    this.tree=tree;
    setTreeModel();
    getSound(3);
    jsp=new JScrollPane(this.tree);
    jsp.setBounds(12,96,168,120);
         jsp.setBackground(java.awt.Color.lightGray);
    cp.add(jsp);
    this.tree.addMouseListener(new MouseHandler());
    textArea2.append("\nClient:" + alias + "has disconnected");                          
    private void receiveMessage(String str,Hashtable rfiles,String alias,String group)
              boolean flag=true;
              UIManager.put("JFrame.activeTitleBackground", new Color(64,128,255));
    UIManager.put("JFrame.activeTitleForeground", Color.white);
    UIManager.put("JFrame.inactiveTitleBackground", new Color(128,128,128));
    UIManager.put("JFrame.inactiveTitleForeground", Color.black);
    SwingUtilities.updateComponentTreeUI(this);
              try{
              if(alias.equals(""))
         doc.insertString(doc.getLength(),"CHATMASTER>>",textpanel.getStyle("bold"));
              doc.insertString(doc.getLength(),str+ newline,textpanel.getStyle("normal"));
              else
              doc.insertString(doc.getLength(),alias + "@" + group + ">>",textpanel.getStyle("bold"));
              doc.insertString(doc.getLength(),str,textpanel.getStyle("normal"));
              //add files to textpanel
              if(rfiles!=null && rfiles.size()>0)
              doc.insertString(doc.getLength(),newline+"Attachments>>",textpanel.getStyle("attach"));
              showattach(rfiles);
              addtoList(rfiles);     
    doc.insertString(doc.getLength(),newline,textpanel.getStyle("normal"));
    catch(Exception e)
              e.printStackTrace();
              dialog.showMessageDialog(client,e.toString(),"Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
         cp.repaint();               
    protected boolean ContactServer(String alias,String servername,String group)
         try{
              //UnicastRemoteObject.exportObject(this);
              //server=(ServerInterface)Naming.lookup("//gpt02d05:5500/" + servername);
         //     server.notifyMe(this,alias,group);
              //change the settings of buttons
              button1.setEnabled(true);
              button2.setEnabled(true);
              button3.setLabel("Disconnect");
              label8.setVisible(true);
              label8.setText(" Welcome::" + alias);
              //putting values of alias and group for sending messages
              fromalias=alias;
              fromgroup=group;
              CONNECT=true;
              return true;
         catch(UnsupportedOperationException e)
         dialog.showMessageDialog(client,"Client with the Same Alias in " + group + " already exists","Error:ChatApplication",JOptionPane.ERROR_MESSAGE);                                   
         try{
              //     UnicastRemoteObject.unexportObject(client,true);
              catch(Exception ev){System.out.println(ev.toString());}     
         catch(Exception e)
              dialog.showMessageDialog(client,"Unable to connect to Server","Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
              try{
              //     UnicastRemoteObject.unexportObject(client,true);
              catch(Exception ev){System.out.println(ev.toString());}     
         return false;      
    public static void main(String args[]) throws RemoteException{
         client=new Client();          
    }//main ends
    public void getSound(int count)
         Toolkit t1=getToolkit();
              for(int i=0;i<count;i++)
              t1.beep();
              try{
                   Thread.sleep(500);
              catch(Exception e){}
    public void setTreeModel()
    ImageIcon i1=new ImageIcon("Lock.gif","No Users");
    ImageIcon i2=new ImageIcon("Connec.gif","Users in Group");
    ImageIcon i3=new ImageIcon("authorbn.gif","An User");
    DefaultTreeCellRenderer dr1= new DefaultTreeCellRenderer();
    dr1.setClosedIcon(i1);
    dr1.setOpenIcon(i2);
    dr1.setLeafIcon(i3);
    dr1.setTextSelectionColor(java.awt.Color.red);
    tree.setCellRenderer(dr1);
    //add received files to the list
    private void addtoList(Hashtable rfiles)
    Enumeration filelist=rfiles.keys();          
    while(filelist.hasMoreElements())          
    File file=(File)filelist.nextElement();
    this.rfiles.put(file,rfiles.get(file));               
    //show the attachments received               
    private void showattach(Hashtable rfiles)
    Enumeration filelist=rfiles.keys();
    dsource=DragSource.getDefaultDragSource();
    JButton b1=null;
    while(filelist.hasMoreElements())
         File file=(File)filelist.nextElement();
         Icon icon=chooser.getIcon(file);
         b1=new JButton(icon);
         b1.setBackground(java.awt.Color.gray);
    b1.setToolTipText(file.getName());
    b1.addMouseListener(new AttachmentHandler());
    Dimension d1=new Dimension(icon.getIconWidth(),icon.getIconHeight());
    b1.setMaximumSize(d1);
    hfiles.put(b1,file);
    textpanel.setCaretPosition(doc.getLength());
    textpanel.insertComponent(b1);
    b1.setSize(icon.getIconWidth(),icon.getIconHeight());
    dsource.createDefaultDragGestureRecognizer(b1, DnDConstants.ACTION_COPY_OR_MOVE,new DragGestureHandler());           
    cp.repaint();
    private void savefile(File file,Object parent)
    //ExtensionFileFilter filter = new ExtensionFileFilter(false);
    //filter.addExtension("txt",true);
    //chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(client);
    if(returnVal ==JFileChooser.APPROVE_OPTION)
         try{
         FileOutputStream fstream=new FileOutputStream(chooser.getSelectedFile());
         //decide whether the file received or sent is to be saved
         if(((Container)parent).equals(textArea1))
         fstream.write((byte[])files.get(file));
         else
         fstream.write((byte[])rfiles.get(file));
         fstream.close();
         System.out.println(file.getName());          
         catch(Exception e)
         {System.out.println(e.toString()); }
    private void openfile(File file,Object parent)
         File tempfile=null;
         try{
         String fname=file.getName();     
         tempfile=File.createTempFile("temp",fname.substring(fname.lastIndexOf(".")));     
         FileOutputStream fstream=new FileOutputStream(tempfile);
         System.out.println(tempfile.getAbsolutePath());
         //decide whether the file received or sent is to be saved
         if(((Container)parent).equals(textArea1))
         fstream.write((byte[])files.get(file));
         else
         fstream.write((byte[])rfiles.get(file));          
         fstream.close();
    catch(Exception e){System.out.println(e.toString());}
    try{
         Process p1=r1.exec("cmd /c start " + tempfile.getAbsolutePath());
         p1.waitFor();
    catch(Exception e){System.out.println(e.toString());}     
    //inner classes
    class ComponentHandler implements ContainerListener{
    public void componentRemoved(ContainerEvent ev)     
              Container cont=(Container)ev.getChild();
              if(cont.getComponentCount()>0)
              JButton but=(JButton)cont.getComponent(0);
              files.remove((File)hfiles.get(but));
              hfiles.remove(but);
    public void componentAdded(ContainerEvent ev){}
    class AttachmentHandler extends MouseAdapter{
         public void mouseClicked(MouseEvent ev){
         if(ev.getModifiers()==4)
         Component comp=(Component)ev.getSource();
         File file=(File)hfiles.get(comp);
         popup=new JPopupMenu();
         JMenuItem popopen=new JMenuItem("Open");
         JMenuItem popsave=new JMenuItem("Save As..");
         popup.add(popopen);
         System.out.println(comp.getParent().getParent().getClass().toString());
         popopen.addActionListener(new ButtonHandler(file,comp.getParent().getParent()));
         popup.add(popsave);
         popsave.addActionListener(new ButtonHandler(file,comp.getParent().getParent()));
         popup.show(comp,12,12);
    class DragGestureHandler extends Vector implements DragGestureListener,DragSourceListener,Transferable{
    final static int FILE = 0;
    final static int STRING = 1;
    final static int PLAIN = 2;
    DataFlavor flavors[] = {DataFlavor.javaFileListFlavor,DataFlavor.stringFlavor,DataFlavor.plainTextFlavor};
    public void dragDropEnd(DragSourceDropEvent ev){}
    public void dragEnter(DragSourceDragEvent ev){}
    public void dragExit(DragSourceEvent ev){}
    public void dragOver(DragSourceDragEvent ev){}
    public void dropActionChanged(DragSourceDragEvent ev){}
    public void dragGestureRecognized(DragGestureEvent ev)     
              System.out.println("recognized");
              File file=(File)hfiles.get(ev.getComponent());
    addElement(file);
    ev.startDrag(DragSource.DefaultCopyDrop,this,this);
    /* Returns the array of flavors in which it can provide the data. */
    public synchronized DataFlavor[] getTransferDataFlavors() {
         return flavors;
    /* Returns whether the requested flavor is supported by this object. */
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    boolean b = false;
    b |=flavor.equals(flavors[FILE]);
    b |= flavor.equals(flavors[STRING]);
    b |= flavor.equals(flavors[PLAIN]);
         return (b);
    public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException,IOException
    if(flavor.equals(flavors[FILE])){return this;}
    else if (flavor.equals(flavors[PLAIN])) {
         return new StringReader(((File)elementAt(0)).getAbsolutePath());
         } else if (flavor.equals(flavors[STRING])) {
         return((File)elementAt(0)).getAbsolutePath();
         } else {
         throw new UnsupportedFlavorException(flavor);
    //inner class for draging in the files on java frame     
    class DragDropHandler implements DropTargetListener{
    public void dragEnter(DropTargetDragEvent ev){     
    public void dragExit(DropTargetEvent ev){
    public void dragOver(DropTargetDragEvent ev){
    public void drop(DropTargetDropEvent ev){
         Transferable tf1=ev.getTransferable();
         DataFlavor fl[]=ev.getCurrentDataFlavors();
         if(ev.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
         ev.acceptDrop (DnDConstants.ACTION_COPY_OR_MOVE);
         try{
         java.util.List fileList = (java.util.List)tf1.getTransferData(DataFlavor.javaFileListFlavor);
    Iterator iterator = fileList.iterator();
    while (iterator.hasNext())
    File file = (File)iterator.next();
    if(file.isFile())
    Icon icon=chooser.getIcon(file);
    FileInputStream fstream=new FileInputStream(file);
    int filedata=(new Double(file.length())).intValue();
    byte bytes[]=new byte[filedata];
    fstream.read(bytes);
    files.put(file,bytes);
    ev.getDropTargetContext().dropComplete(true);
    addAttach(fileList);
    catch(Exception e)
    {System.out.println(e.toString() + "here");}
    public void dropActionChanged(DropTargetDragEvent ev){
    class MouseHandler extends MouseAdapter{
    public void mouseClicked(MouseEvent me)
    TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
    if(tp!=null)
         if(tp.getPathCount()==3)
              toalias=tp.getPathComponent(2).toString();
              togroup=tp.getPathComponent(1).toString();
              System.out.println(toalias);
              if (!(toalias.equals(fromalias) && togroup.equals(fromgroup)))
              System.out.println("hh " + toalias);
              label4.setText(tp.getPathComponent(2).toString() + "_@" + tp.getPathComponent(1).toString());           
    class ButtonHandler implements ActionListener{
         private File file;
         private Object parent;
         //constructors
         public ButtonHandler()
         public ButtonHandler(File file,Object parent)
              this.file=file;
              this.parent=parent;
         //other functions      
         public void actionPerformed(ActionEvent ev){
              String s=ev.getActionCommand();
         System.out.println(s);
              if(s.equals("Send with Audio..."))
              //Audio audio=new Audio(client,false,"CAPTURE");          
              if(s.equals("Disconnect"))
              try{
              // server.disconnect(client);
              client.getSound(3);
              cp.remove(jsp);
              label6.setVisible(false);
              //UnicastRemoteObject.unexportObject(client,true);
              button3.setLabel("Connect");
              textArea2.append("\nYou have been disconnected to Server");
              client.repaint();     
              catch(Exception e)
              System.out.println(e.toString());
              if(s.equals("Connect"))
         //     clp=new ClientProperties(client,false);
         if(s.equals("Save As.."))
         savefile(file,parent);     
         if(s.equals("Open"))
         openfile(file,parent);
              if(s.equals("Attach"))
              //ExtensionFileFilter filter = new ExtensionFileFilter(false);
              //filter.addExtension(".txt",true);
              //filter.setDescription("Text Files(.txt)");
              // chooser.setFileFilter(filter);
              chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
              //chooser.setMultiSelectionEnabled(true);
              int returnVal = chooser.showOpenDialog(client);
              if(returnVal ==JFileChooser.APPROVE_OPTION)
              //File fp[]=chooser.getSelectedFiles();
              File fp[]=new File[1];
              fp[0]=chooser.getSelectedFile();
              int i=0;
              while(i<fp.length)
              try{
              File file=fp;
              Icon icon=chooser.getIcon(file);
    FileInputStream fstream=new FileInputStream(file);
    int filedata=(new Double(file.length())).intValue();
    byte bytes[]=new byte[filedata];
    fstream.read(bytes);
    files.put(file,bytes);
    catch(Exception e){dialog.showMessageDialog(client,e.toString(),"Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
    return; }
    i++;
              java.util.List fileList=Arrays.asList(fp);
              addAttach(fileList);
              if(s.equals("Send"))
              try{
                   if(toalias==null)
                   dialog.showMessageDialog(client,"Select the Recepient First!!","Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
                   return;
                   if(toalias!=null && togroup!=null && (!toalias.equals(fromalias)))
                   // server.sendMessage(textArea1.getText(),files,toalias,togroup,fromalias,fromgroup);
                   textArea1.setText("");
              catch(Exception e)
         e.printStackTrace();
    }//if ends
    class WindowEventHandler extends WindowAdapter{
         public void windowClosing(WindowEvent ev){
              try{
              //server.disconnect(client);
              client.getSound(3);
         //     UnicastRemoteObject.unexportObject(client,true);
              catch(Exception e){System.out.println(e.toString());}
              dispose();
    private class onshutdown extends Thread{
    public void run(){
         try{
              //server.disconnect(client);
              //UnicastRemoteObject.unexportObject(client,true);
              catch(Exception e){}      
    }//run ends          

    Here is the working code :
    There was an error line 724
    File file=fp; -> File file=fp[0];
    Several method were deprecated and try to replace the deprecated static field : DataFlavor.plainTextFlavor which was deprecated since 1.4.
    /* Client.java*/
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.rmi.*;
    import java.rmi.server.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.filechooser.*;
    import java.io.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    public class Client extends JFrame{
    static String newline = System.getProperty("line.separator");
    static Client client;
    //ServerInterface server;
    //ClientProperties clp;
    Vector v1=new Vector();
    ByteArrayOutputStream out;
    Runtime r1;
    //file objects,together with array of bytes
    Hashtable files=new Hashtable(); //files sent
    Hashtable rfiles=new Hashtable(); //files received
    //file objects,together with button handlers
    Hashtable hfiles=new Hashtable(); //files sent,files received
    JButton button1=new JButton();
    JButton button2=new JButton();
    JButton button3=new JButton();
    JLabel label1=new JLabel();
    JLabel label2=new JLabel();
    JLabel label3=new JLabel();
    JLabel label4=new JLabel();
    JLabel label5=new JLabel();
    JLabel label6=new JLabel();
    JLabel label7=new JLabel();
    JLabel label8=new JLabel();
    JOptionPane dialog=new JOptionPane();
    JFileChooser chooser = new JFileChooser();
    JPanel panel1;
    JPanel panel2;
    DropTarget dtarget;
    DragSource dsource;
    JTextPane textArea1=new JTextPane();
    TextArea textArea2=new TextArea();
    JTextPane textpanel=new JTextPane();
    Style defstyle,style;
    StyledDocument doc,doc1;
    JPopupMenu popup;
    JTree tree;
    JScrollPane jsppane;
    JScrollPane jsp,jsp2;
    DefaultMutableTreeNode top;
    Container cp;
    private String toalias;
    private String togroup;
    private String fromalias;
    private String fromgroup;
    private boolean CONNECT;
    public Client()
    cp=getContentPane();
    cp.setLayout(null);
    setForeground(java.awt.Color.red);
    setFont(new Font("Dialog", Font.PLAIN, 14));
    setVisible(false);
    label1.setText(" CHAT APPLICATION");
    cp.add(label1);
    label1.setFont(new Font("Dialog", Font.BOLD, 16));
    label1.setBounds(72,20,319,30);
    label2.setText("List of Users Connected.");
    cp.add(label2);
    label2.setForeground(java.awt.Color.blue);
    label2.setFont(new Font("Dialog", Font.BOLD, 12));
    label2.setBounds(24,60,192,26);
    label8.setBounds(280,60,100,26);
    cp.add(label8);
    cp.add(textArea2);
    textArea2.setBounds(204,120,268,90);
    jsppane=new JScrollPane(textArea1);
    doc1=textArea1.getStyledDocument();
    jsppane.setBounds(12,264,456,109);
    cp.add(jsppane);
    label3.setText("TO::");
    cp.add(label3);
    label3.setFont(new Font("Dialog", Font.BOLD, 12));
    label3.setBounds(12,228,36,20);
    cp.add(label4);
    label4.setBackground(java.awt.Color.lightGray);
    label4.setBounds(60,228,172,19);
    label5.setText("SERVER RESPONSE");
    cp.add(label5);
    label5.setFont(new Font("Dialog", Font.BOLD, 12));
    label5.setBounds(204,96,204,21);
    label7.setText("MESSAGE FOR YOU.");
    cp.add(label7);
    label7.setFont(new Font("Dialog", Font.BOLD, 14));
    label7.setBounds(12,371,288,25);
    jsp2=new JScrollPane(textpanel);
    setTextPaneStyle();
    jsp2.setBounds(12,401,456,109);
    cp.add(jsp2);
    button1.setText("Send");
    button1.setEnabled(false);
    cp.add(button1);
    button1.setBackground(java.awt.Color.lightGray);
    button1.setForeground(java.awt.Color.black);
    button1.setFont(new Font("Dialog", Font.BOLD|Font.ITALIC, 10));
    button1.setBounds(60,520,78,36);
    button2.setText("Attach");
    //button2.setEnabled(false);
    cp.add(button2);
    button2.setBackground(java.awt.Color.lightGray);
    button2.setForeground(java.awt.Color.black);
    button2.setFont(new Font("Dialog", Font.BOLD|Font.ITALIC, 10));
    button2.setBounds(180,520,72,36);
    button3.setText("Connect");
    cp.add(button3);
    button3.setBackground(java.awt.Color.lightGray);
    button3.setForeground(java.awt.Color.black);
    button3.setFont(new Font("Dialog", Font.BOLD|Font.ITALIC, 10));
    button3.setBounds(288,520,72,33);
    setSize(500,620);
    show();
    addWindowListener(new WindowEventHandler());
    button1.addActionListener(new ButtonHandler());
    button2.addActionListener(new ButtonHandler());
    button3.addActionListener(new ButtonHandler());
    textArea1.addContainerListener(new ComponentHandler());
    dtarget=new DropTarget(textArea1,new DragDropHandler());
    textArea2.setEnabled(false);
    textpanel.setEnabled(false);
    r1=Runtime.getRuntime();
    r1.addShutdownHook(new onshutdown());
    addMenu();
    cp.repaint();
    //adds attachments to the textArea1
    synchronized private void addAttach(java.util.List fileList)
    Iterator iterator=fileList.iterator();
    JButton bw;
    while(iterator.hasNext())
    File file=(File)iterator.next();
    Icon icon=chooser.getIcon(file);
    bw=new JButton(icon);
    bw.setBackground(java.awt.Color.gray);
    bw.setToolTipText(file.getAbsolutePath());
    bw.addMouseListener(new AttachmentHandler());
    Dimension d1=new Dimension(icon.getIconWidth(),icon.getIconHeight());
    bw.setMaximumSize(d1);
    hfiles.put(bw,file);
    textArea1.insertComponent(bw);
    textArea1.setCaretPosition(doc1.getLength());
    bw.setSize(icon.getIconWidth(),icon.getIconHeight());
    //only one file at a time
    break;
    cp.repaint();
    public void setAudioStream(ByteArrayOutputStream out)
    this.out=out;
    private void addMenu()
    JMenuBar mbar=new JMenuBar();
    mbar.setVisible(true);
    mbar.setBounds(0,0,500,20);
    mbar.setBackground(java.awt.Color.gray);
    //first menu
    JMenu m1=new JMenu("Connection");
    m1.setBounds(0,0,80,20);
    m1.setBackground(java.awt.Color.gray);
    JMenuItem mitem1=new JMenuItem("Connect");
    JMenuItem mitem2=new JMenuItem("Disconnect");
    m1.add(mitem1);
    m1.add(mitem2);
    mitem1.addActionListener(new ButtonHandler());
    mitem2.addActionListener(new ButtonHandler());
    mbar.add(m1);
    //second menu
    JMenu m2=new JMenu("Send...");
    m2.setBounds(90,0,80,20);
    m2.setBackground(java.awt.Color.gray);
    JMenuItem mitem3=new JMenuItem("Send");
    JMenuItem mitem4=new JMenuItem("Send with Audio...");
    mitem3.addActionListener(new ButtonHandler());
    mitem4.addActionListener(new ButtonHandler());
    m2.add(mitem3);
    m2.add(mitem4);
    mbar.add(m2);
    cp.add(mbar);
    private void setTextPaneStyle()
    StyleContext stylecontext =StyleContext.getDefaultStyleContext();
    defstyle=stylecontext.getStyle(StyleContext.DEFAULT_STYLE);
    doc= textpanel.getStyledDocument();
    //style 1
    style= textpanel.addStyle("bold",defstyle);
    StyleConstants.setBackground(style,Color.white);
    StyleConstants.setForeground(style,Color.blue);
    StyleConstants.setItalic(style, false);
    StyleConstants.setBold(style, true);
    StyleConstants.setFontSize(style,16);
    //style 2
    style= textpanel.addStyle("normal",defstyle);
    StyleConstants.setBackground(style,Color.white);
    StyleConstants.setForeground(style,Color.black);
    StyleConstants.setItalic(style, false);
    StyleConstants.setBold(style, false);
    StyleConstants.setFontSize(style,14);
    //style3
    style= textpanel.addStyle("attach",defstyle);
    StyleConstants.setBackground(style,Color.white);
    StyleConstants.setForeground(style,Color.red);
    StyleConstants.setItalic(style, true);
    StyleConstants.setBold(style, false);
    StyleConstants.setFontSize(style,12);
    //remote method called by server
    public void addClient(String alias,String group,JTree tree)
    //if old client remove old tree
    if(!alias.equals(""))
    cp.remove(this.jsp);
    //add new tree
    this.tree=tree;
    setTreeModel();
    getSound(2);
    if(!alias.equals(""))
    textArea2.append("\nNew Client:" + alias + "has joined");
    else
    textArea2.append("\nYou have been connected to the Server.");
    jsp=new JScrollPane(this.tree);
    jsp.setBounds(12,96,168,120);
    jsp.setBackground(java.awt.Color.lightGray);
    cp.add(jsp);
    this.tree.addMouseListener(new MouseHandler());
    //remote method called by server
    public void sendMessage(String str,Hashtable rfiles,String alias,String group) throws RemoteException
    receiveMessage(str,rfiles,alias,group);
    //remote method called by server
    public void removeClient(JTree tree,String alias,String group) throws RemoteException
    cp.remove(this.jsp);
    this.tree=tree;
    setTreeModel();
    getSound(3);
    jsp=new JScrollPane(this.tree);
    jsp.setBounds(12,96,168,120);
    jsp.setBackground(java.awt.Color.lightGray);
    cp.add(jsp);
    this.tree.addMouseListener(new MouseHandler());
    textArea2.append("\nClient:" + alias + "has disconnected");
    private void receiveMessage(String str,Hashtable rfiles,String alias,String group)
    boolean flag=true;
    UIManager.put("JFrame.activeTitleBackground", new Color(64,128,255));
    UIManager.put("JFrame.activeTitleForeground", Color.white);
    UIManager.put("JFrame.inactiveTitleBackground", new Color(128,128,128));
    UIManager.put("JFrame.inactiveTitleForeground", Color.black);
    SwingUtilities.updateComponentTreeUI(this);
    try{
    if(alias.equals(""))
    doc.insertString(doc.getLength(),"CHATMASTER>>",textpanel.getStyle("bold"));
    doc.insertString(doc.getLength(),str+ newline,textpanel.getStyle("normal"));
    else
    doc.insertString(doc.getLength(),alias + "@" + group + ">>",textpanel.getStyle("bold"));
    doc.insertString(doc.getLength(),str,textpanel.getStyle("normal"));
    //add files to textpanel
    if(rfiles!=null && rfiles.size()>0)
    doc.insertString(doc.getLength(),newline+"Attachments>>",textpanel.getStyle("attach"));
    showattach(rfiles);
    addtoList(rfiles);
    doc.insertString(doc.getLength(),newline,textpanel.getStyle("normal"));
    catch(Exception e)
    e.printStackTrace();
    dialog.showMessageDialog(client,e.toString(),"Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
    cp.repaint();
    protected boolean ContactServer(String alias,String servername,String group)
    try{
    //UnicastRemoteObject.exportObject(this);
    //server=(ServerInterface)Naming.lookup("//gpt02d05:5500/" + servername);
    // server.notifyMe(this,alias,group);
    //change the settings of buttons
    button1.setEnabled(true);
    button2.setEnabled(true);
    button3.setText("Disconnect");
    label8.setVisible(true);
    label8.setText(" Welcome::" + alias);
    //putting values of alias and group for sending messages
    fromalias=alias;
    fromgroup=group;
    CONNECT=true;
    return true;
    catch(UnsupportedOperationException e)
    dialog.showMessageDialog(client,"Client with the Same Alias in " + group + " already exists","Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
    try{
    // UnicastRemoteObject.unexportObject(client,true);
    catch(Exception ev){System.out.println(ev.toString());}
    catch(Exception e)
    dialog.showMessageDialog(client,"Unable to connect to Server","Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
    try{
    // UnicastRemoteObject.unexportObject(client,true);
    catch(Exception ev){System.out.println(ev.toString());}
    return false;
    public static void main(String args[]) throws RemoteException{
    client=new Client();
    }//main ends
    public void getSound(int count)
    Toolkit t1=getToolkit();
    for(int i=0;i<count;i++)
    t1.beep();
    try{
    Thread.sleep(500);
    catch(Exception e){}
    public void setTreeModel()
    ImageIcon i1=new ImageIcon("Lock.gif","No Users");
    ImageIcon i2=new ImageIcon("Connec.gif","Users in Group");
    ImageIcon i3=new ImageIcon("authorbn.gif","An User");
    DefaultTreeCellRenderer dr1= new DefaultTreeCellRenderer();
    dr1.setClosedIcon(i1);
    dr1.setOpenIcon(i2);
    dr1.setLeafIcon(i3);
    dr1.setTextSelectionColor(java.awt.Color.red);
    tree.setCellRenderer(dr1);
    //add received files to the list
    private void addtoList(Hashtable rfiles)
    Enumeration filelist=rfiles.keys();
    while(filelist.hasMoreElements())
    File file=(File)filelist.nextElement();
    this.rfiles.put(file,rfiles.get(file));
    //show the attachments received
    private void showattach(Hashtable rfiles)
    Enumeration filelist=rfiles.keys();
    dsource=DragSource.getDefaultDragSource();
    JButton b1=null;
    while(filelist.hasMoreElements())
    File file=(File)filelist.nextElement();
    Icon icon=chooser.getIcon(file);
    b1=new JButton(icon);
    b1.setBackground(java.awt.Color.gray);
    b1.setToolTipText(file.getName());
    b1.addMouseListener(new AttachmentHandler());
    Dimension d1=new Dimension(icon.getIconWidth(),icon.getIconHeight());
    b1.setMaximumSize(d1);
    hfiles.put(b1,file);
    textpanel.setCaretPosition(doc.getLength());
    textpanel.insertComponent(b1);
    b1.setSize(icon.getIconWidth(),icon.getIconHeight());
    dsource.createDefaultDragGestureRecognizer(b1, DnDConstants.ACTION_COPY_OR_MOVE,new DragGestureHandler());
    cp.repaint();
    private void savefile(File file,Object parent)
    //ExtensionFileFilter filter = new ExtensionFileFilter(false);
    //filter.addExtension("txt",true);
    //chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(client);
    if(returnVal ==JFileChooser.APPROVE_OPTION)
    try{
    FileOutputStream fstream=new FileOutputStream(chooser.getSelectedFile());
    //decide whether the file received or sent is to be saved
    if(((Container)parent).equals(textArea1))
    fstream.write((byte[])files.get(file));
    else
    fstream.write((byte[])rfiles.get(file));
    fstream.close();
    System.out.println(file.getName());
    catch(Exception e)
    {System.out.println(e.toString()); }
    private void openfile(File file,Object parent)
    File tempfile=null;
    try{
    String fname=file.getName();
    tempfile=File.createTempFile("temp",fname.substring(fname.lastIndexOf(".")));
    FileOutputStream fstream=new FileOutputStream(tempfile);
    System.out.println(tempfile.getAbsolutePath());
    //decide whether the file received or sent is to be saved
    if(((Container)parent).equals(textArea1))
    fstream.write((byte[])files.get(file));
    else
    fstream.write((byte[])rfiles.get(file));
    fstream.close();
    catch(Exception e){System.out.println(e.toString());}
    try{
    Process p1=r1.exec("cmd /c start " + tempfile.getAbsolutePath());
    p1.waitFor();
    catch(Exception e){System.out.println(e.toString());}
    //inner classes
    class ComponentHandler implements ContainerListener{
    public void componentRemoved(ContainerEvent ev)
    Container cont=(Container)ev.getChild();
    if(cont.getComponentCount()>0)
    JButton but=(JButton)cont.getComponent(0);
    files.remove((File)hfiles.get(but));
    hfiles.remove(but);
    public void componentAdded(ContainerEvent ev){}
    class AttachmentHandler extends MouseAdapter{
    public void mouseClicked(MouseEvent ev){
    if(ev.getModifiers()==4)
    Component comp=(Component)ev.getSource();
    File file=(File)hfiles.get(comp);
    popup=new JPopupMenu();
    JMenuItem popopen=new JMenuItem("Open");
    JMenuItem popsave=new JMenuItem("Save As..");
    popup.add(popopen);
    System.out.println(comp.getParent().getParent().getClass().toString());
    popopen.addActionListener(new ButtonHandler(file,comp.getParent().getParent()));
    popup.add(popsave);
    popsave.addActionListener(new ButtonHandler(file,comp.getParent().getParent()));
    popup.show(comp,12,12);
    class DragGestureHandler extends Vector implements DragGestureListener,DragSourceListener,Transferable{
    final static int FILE = 0;
    final static int STRING = 1;
    final static int PLAIN = 2;
    DataFlavor flavors[] = {DataFlavor.javaFileListFlavor,DataFlavor.stringFlavor,DataFlavor.plainTextFlavor};
    public void dragDropEnd(DragSourceDropEvent ev){}
    public void dragEnter(DragSourceDragEvent ev){}
    public void dragExit(DragSourceEvent ev){}
    public void dragOver(DragSourceDragEvent ev){}
    public void dropActionChanged(DragSourceDragEvent ev){}
    public void dragGestureRecognized(DragGestureEvent ev)
    System.out.println("recognized");
    File file=(File)hfiles.get(ev.getComponent());
    addElement(file);
    ev.startDrag(DragSource.DefaultCopyDrop,this,this);
    /* Returns the array of flavors in which it can provide the data. */
    public synchronized DataFlavor[] getTransferDataFlavors() {
    return flavors;
    /* Returns whether the requested flavor is supported by this object. */
    public boolean isDataFlavorSupported(DataFlavor flavor) {
    boolean b = false;
    b |=flavor.equals(flavors[FILE]);
    b |= flavor.equals(flavors[STRING]);
    b |= flavor.equals(flavors[PLAIN]);
    return (b);
    public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException,IOException
    if(flavor.equals(flavors[FILE])){return this;}
    else if (flavor.equals(flavors[PLAIN])) {
    return new StringReader(((File)elementAt(0)).getAbsolutePath());
    } else if (flavor.equals(flavors[STRING])) {
    return((File)elementAt(0)).getAbsolutePath();
    } else {
    throw new UnsupportedFlavorException(flavor);
    //inner class for draging in the files on java frame
    class DragDropHandler implements DropTargetListener{
    public void dragEnter(DropTargetDragEvent ev){
    public void dragExit(DropTargetEvent ev){
    public void dragOver(DropTargetDragEvent ev){
    public void drop(DropTargetDropEvent ev){
    Transferable tf1=ev.getTransferable();
    DataFlavor fl[]=ev.getCurrentDataFlavors();
    if(ev.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
    ev.acceptDrop (DnDConstants.ACTION_COPY_OR_MOVE);
    try{
    java.util.List fileList = (java.util.List)tf1.getTransferData(DataFlavor.javaFileListFlavor);
    Iterator iterator = fileList.iterator();
    while (iterator.hasNext())
    File file = (File)iterator.next();
    if(file.isFile())
    Icon icon=chooser.getIcon(file);
    FileInputStream fstream=new FileInputStream(file);
    int filedata=(new Double(file.length())).intValue();
    byte bytes[]=new byte[filedata];
    fstream.read(bytes);
    files.put(file,bytes);
    ev.getDropTargetContext().dropComplete(true);
    addAttach(fileList);
    catch(Exception e)
    {System.out.println(e.toString() + "here");}
    public void dropActionChanged(DropTargetDragEvent ev){
    class MouseHandler extends MouseAdapter{
    public void mouseClicked(MouseEvent me)
    TreePath tp=tree.getPathForLocation(me.getX(),me.getY());
    if(tp!=null)
    if(tp.getPathCount()==3)
    toalias=tp.getPathComponent(2).toString();
    togroup=tp.getPathComponent(1).toString();
    System.out.println(toalias);
    if (!(toalias.equals(fromalias) && togroup.equals(fromgroup)))
    System.out.println("hh " + toalias);
    label4.setText(tp.getPathComponent(2).toString() + "_@" + tp.getPathComponent(1).toString());
    class ButtonHandler implements ActionListener{
    private File file;
    private Object parent;
    //constructors
    public ButtonHandler()
    public ButtonHandler(File file,Object parent)
    this.file=file;
    this.parent=parent;
    //other functions
    public void actionPerformed(ActionEvent ev){
    String s=ev.getActionCommand();
    System.out.println(s);
    if(s.equals("Send with Audio..."))
    //Audio audio=new Audio(client,false,"CAPTURE");
    if(s.equals("Disconnect"))
    try{
    // server.disconnect(client);
    client.getSound(3);
    cp.remove(jsp);
    label6.setVisible(false);
    //UnicastRemoteObject.unexportObject(client,true);
    button3.setText("Connect");
    textArea2.append("\nYou have been disconnected to Server");
    client.repaint();
    catch(Exception e)
    System.out.println(e.toString());
    if(s.equals("Connect"))
    // clp=new ClientProperties(client,false);
    if(s.equals("Save As.."))
    savefile(file,parent);
    if(s.equals("Open"))
    openfile(file,parent);
    if(s.equals("Attach"))
    //ExtensionFileFilter filter = new ExtensionFileFilter(false);
    //filter.addExtension(".txt",true);
    //filter.setDescription("Text Files(.txt)");
    // chooser.setFileFilter(filter);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    //chooser.setMultiSelectionEnabled(true);
    int returnVal = chooser.showOpenDialog(client);
    if(returnVal ==JFileChooser.APPROVE_OPTION)
    //File fp[]=chooser.getSelectedFiles();
    File fp[]=new File[1];
    fp[0]=chooser.getSelectedFile();
    int i=0;
    while(i<fp.length)
    try{
    File file=fp[0];
    Icon icon=chooser.getIcon(file);
    FileInputStream fstream=new FileInputStream(file);
    int filedata=(new Double(file.length())).intValue();
    byte bytes[]=new byte[filedata];
    fstream.read(bytes);
    files.put(file,bytes);
    catch(Exception e){dialog.showMessageDialog(client,e.toString(),"Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
    return; }
    i++;
    java.util.List fileList=Arrays.asList(fp);
    addAttach(fileList);
    if(s.equals("Send"))
    try{
    if(toalias==null)
    dialog.showMessageDialog(client,"Select the Recepient First!!","Error:ChatApplication",JOptionPane.ERROR_MESSAGE);
    return;
    if(toalias!=null && togroup!=null && (!toalias.equals(fromalias)))
    // server.sendMessage(textArea1.getText(),files,toalias,togroup,fromalias,fromgroup);
    textArea1.setText("");
    catch(Exception e)
    e.printStackTrace();
    }//if ends
    class WindowEventHandler extends WindowAdapter{
    public void windowClosing(WindowEvent ev){
    try{
    //server.disconnect(client);
    client.getSound(3);
    // UnicastRemoteObject.unexportObject(client,true);
    catch(Exception e){System.out.println(e.toString());}
    dispose();
    private class onshutdown extends Thread{
    public void run(){
    try{
    //server.disconnect(client);
    //UnicastRemoteObject.unexportObject(client,true);
    catch(Exception e){}
    }//run ends
    I hope this helps,
    Denis

  • I am stuck with this code- I definitely need a bail out

    I would appreciate if a good samaritan could add this code for me. I am at my wits end.
    The program I am trying to write is supposed to add students with their personal information and then display them in a GUI.
    I should be able to select a student and add a grade for that student.
    Finally I should be able to get the average for all the grades added for this student and display the average grade.
    My challenge is how to obtain all the added scores and show the students average .
    I understand my best shot is to use VECTOR API.
    I tried to write someething but it did not work at , obviously due to inexperience.
    I just can't figure how to link this average display window to the Get Average button.
    A student can have any number of grades.
    I need someone to show me the way, may be little "code guide" I am waaaay lost
    Thanks in advance
    Little Delmarie.
    THIS IS WHAT I HAVE DONE SO FAR . IT COMPILES nicely in DOS and Visual age
    // CODE GradeSystem
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    * UsingJLists.java
    * This is a sample program for the use of JLists. You can add a student by entering their
    * information a clicking on add. You can remove a student by entering their information and
    * clicking on remove. They must be in the list to be removed. You can modify a student by
    * entering their information and clicking add. You will be asked for the new student
    * information when using modify. The add and remove buttons will disappear when modifying
    * is underway and the new information is being collected for updating.
    * @author Delmarie
    public class GradeSystem extends JDialog {
    Vector studentGrades = new Vector();
    JButton add, modify, remove;
    JList theJList;
    JPanel buttonPanel, textPanel, labelPanel, masterPanel, jlistPanel, infoPanel;
    JTextField score, possibleScore, gradeType;
    JLabel label1, label2, label3;
    public class ModifyHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the student info from the text boxes
    double dScore = 0;
    double dPossibleScore = 0;
    try {
    String str1 = score.getText();
    if (str1 != null) dScore = Double.parseDouble(str1);
    String str2 = possibleScore.getText();
    if (str2 != null) dPossibleScore = Double.parseDouble(str2);
    catch(NumberFormatException e) {}
    String sGradeType = gradeType.getText();
    Grade grade = (Grade)theJList.getSelectedValue();
    if (grade == null) {
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    return;
    grade.setScore(dScore);
    grade.setPossibleScore(dPossibleScore);
    grade.setGradeType(sGradeType);
    theJList.repaint();
    public class RemoveHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    int removeIndex = theJList.getSelectedIndex();
    if (removeIndex == -1) {
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    return;
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.removeElementAt(removeIndex);
    studentGrades.removeElementAt(removeIndex);
    // clear the textboxes
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    public class AddHandler implements ActionListener {
    public void actionPerformed(ActionEvent actionEvent) {
    // get the student info from the text boxes
    double dScore = 0;
    double dPossibleScore = 0;
    try {
    String str1 = score.getText();
    if (str1 != null) dScore = Double.parseDouble(str1);
    String str2 = possibleScore.getText();
    if (str2 != null) dPossibleScore = Double.parseDouble(str2);
    catch(NumberFormatException e) {}
    String sGradeType = gradeType.getText();
    // get the model and add the student to the model
    Grade g = new Grade();
    g.setScore(dScore);
    g.setPossibleScore(dPossibleScore);
    g.setGradeType(sGradeType);
    studentGrades.add(g);
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.addElement(g);
    // display the added element
    theJList.setSelectedValue(g, true);
    public class WindowHandler extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    setVisible(false);
    /** Creates a new instance of UsingJLists */
    public GradeSystem(JFrame owner, boolean modal) {
    super(owner, modal);
    // create all of the components, put them in panels, and put the panels in JFrame
    add = new JButton("Add");
    modify = new JButton("Modify");
    remove = new JButton("Remove");
    score = new JTextField("");
    score.setColumns(10);
    possibleScore = new JTextField("");
    gradeType = new JTextField("");
    label1 = new JLabel("score");
    label2 = new JLabel("possibleScore");
    label3 = new JLabel("gradeType");
    FlowLayout flow = new FlowLayout();
    FlowLayout flow1 = new FlowLayout();
    FlowLayout flow2 = new FlowLayout();
    GridLayout grid1 = new GridLayout(7,1);
    GridLayout grid2 = new GridLayout(7,1);
    BorderLayout border3 = new BorderLayout();
    buttonPanel = new JPanel(flow);
    buttonPanel.add(add);
    buttonPanel.add(modify);
    buttonPanel.add(remove);
    labelPanel = new JPanel(grid1);
    //labelPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label1);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label2);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label3);
    labelPanel.add(Box.createVerticalStrut(20));
    textPanel = new JPanel(grid2);
    //textPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(score);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(possibleScore);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(gradeType);
    textPanel.add(Box.createVerticalStrut(20));
    infoPanel = new JPanel(new FlowLayout());
    infoPanel.setBorder(BorderFactory.createTitledBorder("Grade Information"));
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(textPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(labelPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    theJList = new JList(new DefaultListModel());
    theJList.addListSelectionListener(new javax.swing.event.ListSelectionListener(){
    public void valueChanged(ListSelectionEvent evt) {
    Grade grade = (Grade)theJList.getSelectedValue();
    if (grade == null) {
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    return;
    score.setText(Double.toString(grade.getScore()));
    possibleScore.setText(Double.toString(grade.getPossibleScore()));
    gradeType.setText(grade.getGradeType());
    //JLabel theLabel = new JLabel("Students");
    jlistPanel = new JPanel(border3);
    jlistPanel.setBorder(BorderFactory.createTitledBorder("List of Scores"));
    jlistPanel.add(new JScrollPane(theJList));//, BorderLayout.SOUTH);
    masterPanel = new JPanel(new GridLayout(1, 2));
    masterPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    // masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(infoPanel);
    // masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(jlistPanel);
    // masterPanel.add(Box.createHorizontalStrut(10));
    BorderLayout border = new BorderLayout();
    this.getContentPane().setLayout(border);
    Container theContainer = this.getContentPane();
    theContainer.add(buttonPanel,BorderLayout.SOUTH);
    theContainer.add(masterPanel, BorderLayout.CENTER);
    // now add the event handlers for the buttons
    AddHandler handleAdd = new AddHandler();
    ModifyHandler handleModify = new ModifyHandler();
    RemoveHandler handleRemove = new RemoveHandler();
    add.addActionListener(handleAdd);
    modify.addActionListener(handleModify);
    remove.addActionListener(handleRemove);
    // add the event handler for the window events
    WindowHandler handleWindow = new WindowHandler();
    this.addWindowListener(handleWindow);
    setSize(600,300);
    * Insert the method's description here.
    * Creation date: (2/24/03 4:20:07 PM)
    * @param v com.sun.java.util.collections.Vector
    public void setStudentGrades(Vector v) {
    studentGrades = v;
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.removeAllElements();
    int size = v.size();
    for (int i = 0; i < size; i++) {
    model.addElement(v.get(i));
    score.setText("");
    possibleScore.setText("");
    gradeType.setText("");
    setVisible(true);
    // CODE2 StudentSystem
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    * UsingJLists.java
    * This is a sample program for the use of JLists. You can add a student by entering their
    * information a clicking on add. You can remove a student by entering their information and
    * clicking on remove. They must be in the list to be removed. You can modify a student by
    * entering their information and clicking add. You will be asked for the new student
    * information when using modify. The add and remove buttons will disappear when modifying
    * is underway and the new information is being collected for updating.
    * @author Delmarie
    public class StudentSystem extends JFrame {
    StudentGradeBook studentGradeBook = new StudentGradeBook();
    GradeSystem gradeSystem = new GradeSystem(this, true);
    JButton add, modify, remove, bGrade;
    JList theJList;
    JPanel buttonPanel, textPanel, labelPanel, masterPanel, jlistPanel, infoPanel;
    JTextField name, address, email, phone, courseName, courseDescription;
    JLabel label1, label2, label3;
    StudentSystem tempObjectRef; // used to hold a class level reference to object for dispose
    boolean getStudentInfo = false;
    int saveIndexInObject;
    public class ModifyHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the information for the student to modify
    String studentName = name.getText();
    String studentAddress = address.getText();
    String studentEmail = email.getText();
    if (!getStudentInfo) { // set up to get student info
    // find the correct element of the model to remove and save in class variable
    int removeIndex = -1;
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    for (int i = 0; i < model.size(); i++) {
    String temp = (String) model.elementAt(i);
    if (temp.equals(name.getText())) {
    removeIndex = i;
    break;
    saveIndexInObject = removeIndex;
    if (removeIndex == -1) return;
    // change the text on the border of the info box
    infoPanel.setBorder(BorderFactory.createTitledBorder("Enter new Student Info"));
    // set up to get the modified info and remove some of the buttons
    getStudentInfo = true;
    buttonPanel.removeAll();
    buttonPanel.add(modify);
    buttonPanel.add(bGrade);
    buttonPanel.repaint();
    else {
    // reset the border and change the element at the provided index (from if above)
    getStudentInfo = false;
    infoPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.setElementAt(name.getText(), saveIndexInObject);
    Student student = studentGradeBook.findStudent(saveIndexInObject);
    student.setName(name.getText());
    student.setAddress(address.getText());
    student.setEmail(email.getText());
    student.setPhone(phone.getText());
    student.setCourseName(courseName.getText());
    student.setCourseDescription(courseDescription.getText());
    // clear the textboxes
    name.setText("");
    address.setText("");
    email.setText("");
    phone.setText("");
    courseName.setText("");
    courseDescription.setText("");
    // restore all of the buttons
    buttonPanel.removeAll();
    buttonPanel.add(add);
    buttonPanel.add(modify);
    buttonPanel.add(remove);
    buttonPanel.add(bGrade);
    buttonPanel.repaint();
    public class RemoveHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the student info from the text boxes
    String studentName = name.getText();
    String studentAddress = address.getText();
    String studentEmail = email.getText();
    // find the element to remove by name (you could use email address etc also)
    int removeIndex = -1; // = theJList.getSelectedIndex();
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    for (int i = 0; i < model.size(); i++) {
    String temp = (String) model.elementAt(i);
    if (temp.equals(name.getText())) {
    removeIndex = i;
    break;
    if (removeIndex == -1) return;
    // remove the element at the index from the for loop
    model.removeElementAt(removeIndex);
    Student student = studentGradeBook.findStudent(removeIndex);
    studentGradeBook.removeStudent(student);
    // clear the textboxes
    name.setText("");
    address.setText("");
    email.setText("");
    phone.setText("");
    courseName.setText("");
    courseDescription.setText("");
    public class AddHandler implements ActionListener {
    public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
    // get the student info from the text boxes
    String studentName = name.getText();
    String studentAddress = address.getText();
    String studentEmail = email.getText();
    String studentPhone = phone.getText();
    String studentCourseName = courseName.getText();
    String studentCourseDescription = courseDescription.getText();
    // get the model and add the student to the model
    studentGradeBook.addStudent(studentName, studentAddress, studentEmail, studentPhone,
    studentCourseName, studentCourseDescription);
    DefaultListModel model = (DefaultListModel) theJList.getModel();
    model.addElement(studentName);
    // reset the text boxes
    name.setText("");
    address.setText("");
    email.setText("");
    phone.setText("");
    courseName.setText("");
    courseDescription.setText("");
    public class WindowHandler extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    gradeSystem.dispose();
    tempObjectRef.dispose();
    System.exit(0);
    /** Creates a new instance of UsingJLists */
    public StudentSystem() {
    // create all of the components, put them in panels, and put the panels in JFrame
    add = new JButton("Add");
    modify = new JButton("Modify");
    remove = new JButton("Remove");
    bGrade = new JButton("Grades");
    name = new JTextField("");
    name.setColumns(10);
    address = new JTextField("");
    email = new JTextField("");
    phone = new JTextField("");
    courseName = new JTextField("");
    courseDescription = new JTextField("");
    label1 = new JLabel("name");
    label2 = new JLabel("address");
    label3 = new JLabel("email");
    JLabel label4 = new JLabel("phone");
    JLabel label5 = new JLabel("courseName");
    JLabel label6 = new JLabel("courseDescription");
    FlowLayout flow = new FlowLayout();
    FlowLayout flow1 = new FlowLayout();
    FlowLayout flow2 = new FlowLayout();
    GridLayout grid1 = new GridLayout(13,1);
    GridLayout grid2 = new GridLayout(13,1);
    BorderLayout border3 = new BorderLayout();
    buttonPanel = new JPanel(flow);
    buttonPanel.add(add);
    buttonPanel.add(modify);
    buttonPanel.add(remove);
    buttonPanel.add(bGrade);
    bGrade.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    int index = theJList.getSelectedIndex();
    if (index == -1) return;
    Student student = studentGradeBook.findStudent(index);
    gradeSystem.setStudentGrades(student.getStudentGrades());
    labelPanel = new JPanel(grid1);
    //labelPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label1);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label2);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label3);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label4);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label5);
    labelPanel.add(Box.createVerticalStrut(20));
    labelPanel.add(label6);
    labelPanel.add(Box.createVerticalStrut(20));
    textPanel = new JPanel(grid2);
    //textPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(name);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(address);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(email);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(phone);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(courseName);
    textPanel.add(Box.createVerticalStrut(20));
    textPanel.add(courseDescription);
    textPanel.add(Box.createVerticalStrut(20));
    infoPanel = new JPanel(new FlowLayout());
    infoPanel.setBorder(BorderFactory.createTitledBorder("Student Information"));
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(textPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    infoPanel.add(labelPanel);
    infoPanel.add(Box.createHorizontalStrut(10));
    theJList = new JList(new DefaultListModel());
    theJList.addListSelectionListener(new javax.swing.event.ListSelectionListener(){
    public void valueChanged(ListSelectionEvent evt) {
    int index = theJList.getSelectedIndex();
    if (index == -1) return;
    Student student = studentGradeBook.findStudent(index);
    name.setText(student.getName());
    address.setText(student.getAddress());
    email.setText(student.getEmail());
    phone.setText(student.getPhone());
    courseName.setText(student.getCourseName());
    courseDescription.setText(student.getCourseDescription());
    //JLabel theLabel = new JLabel("Students");
    jlistPanel = new JPanel(border3);
    jlistPanel.setBorder(BorderFactory.createTitledBorder("List of Students"));
    jlistPanel.add(new JScrollPane(theJList), BorderLayout.SOUTH);
    masterPanel = new JPanel(flow1);
    masterPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(infoPanel);
    masterPanel.add(Box.createHorizontalStrut(10));
    masterPanel.add(jlistPanel);
    masterPanel.add(Box.createHorizontalStrut(10));
    BorderLayout border = new BorderLayout();
    this.getContentPane().setLayout(border);
    Container theContainer = this.getContentPane();
    theContainer.add(buttonPanel,BorderLayout.SOUTH);
    theContainer.add(masterPanel, BorderLayout.NORTH);
    // now add the event handlers for the buttons
    AddHandler handleAdd = new AddHandler();
    ModifyHandler handleModify = new ModifyHandler();
    RemoveHandler handleRemove = new RemoveHandler();
    add.addActionListener(handleAdd);
    modify.addActionListener(handleModify);
    remove.addActionListener(handleRemove);
    // add the event handler for the window events
    WindowHandler handleWindow = new WindowHandler();
    this.addWindowListener(handleWindow);
    // make the frame visible and set its size and show it.
    this.setVisible(true);
    this.pack();//setSize(600,300);
    this.show();
    public static void main (String [] args) {
    StudentSystem mainObject = new StudentSystem();
    mainObject.setTempObjectRef(mainObject);
    public void setTempObjectRef(StudentSystem obj) {
    // set up a reference to this object for use in closing the window method dispose
    tempObjectRef = obj;
    // CODE 3 Student
    import java.util.*;
    * Insert the type's description here.
    * Creation date: (2/24/03 11:23:58 AM)
    * @author: Delmarie
    public class Student {
    private String name, address, phone, email, courseName, courseDescription;
    private Vector studentGrades;
    * Student constructor comment.
    public Student() {
    studentGrades = new Vector();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:39:56 AM)
    * @param score double
    * @param possibleScore double
    * @param gradeType java.lang.String
    public void addGrade(double score, double possibleScore, String gradeType) {
    Grade g = new Grade();
    g.setScore(score);
    g.setPossibleScore(possibleScore);
    g.setGradeType(gradeType);
    studentGrades.add(g);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:47:01 AM)
    * @return Grade
    * @param index int
    public Grade findGrade(int index) {
    return (Grade)studentGrades.get(index);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getAddress() {
    return address;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getCourseDescription() {
    return courseDescription;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getCourseName() {
    return courseName;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getEmail() {
    return email;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:48:03 AM)
    * @return java.util.Iterator
    public Iterator getGradeIterator() {
    return studentGrades.iterator();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getName() {
    return name;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @return java.lang.String
    public java.lang.String getPhone() {
    return phone;
    * Insert the method's description here.
    * Creation date: (2/25/03 10:56:13 AM)
    * @return java.util.Vector
    public java.util.Vector getStudentGrades() {
    return studentGrades;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:41:52 AM)
    * @param grade Grade
    public void removeGrade(Grade grade) {
    studentGrades.remove(grade);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newAddress java.lang.String
    public void setAddress(java.lang.String newAddress) {
    address = newAddress;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newCourseDescription java.lang.String
    public void setCourseDescription(java.lang.String newCourseDescription) {
    courseDescription = newCourseDescription;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newCourseName java.lang.String
    public void setCourseName(java.lang.String newCourseName) {
    courseName = newCourseName;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newEmail java.lang.String
    public void setEmail(java.lang.String newEmail) {
    email = newEmail;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newName java.lang.String
    public void setName(java.lang.String newName) {
    name = newName;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:28:57 AM)
    * @param newPhone java.lang.String
    public void setPhone(java.lang.String newPhone) {
    phone = newPhone;
    * Insert the method's description here.
    * Creation date: (2/25/03 10:56:13 AM)
    * @param newStudentGrades java.util.Vector
    public void setStudentGrades(Vector newStudentGrades) {
    studentGrades = newStudentGrades;
    //CODE 4 StudentGradeBook
    import java.util.*;
    * Insert the type's description here.
    * Creation date: (2/24/03 11:50:35 AM)
    * @author: delmarie
    public class StudentGradeBook {
    private Vector allStudents;
    * StudentGradeBook constructor comment.
    public StudentGradeBook() {
    allStudents = new Vector();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:54:01 AM)
    * @param name java.lang.String
    * @param address java.lang.String
    * @param email java.lang.String
    * @param phone java.lang.String
    public void addStudent(String name, String address, String email, String phone) {
    Student student = new Student();
    student.setName(name);
    student.setAddress(address);
    student.setEmail(email);
    student.setPhone(phone);
    allStudents.add(student);
    * Insert the method's description here.
    * Creation date: (2/24/03 11:54:01 AM)
    * @param name java.lang.String
    * @param address java.lang.String
    * @param email java.lang.String
    * @param phone java.lang.String
    public void addStudent(String name, String address, String email, String phone,
    String courseName, String courseDescription) {
    Student student = new Student();
    student.setName(name);
    student.setAddress(address);
    student.setEmail(email);
    student.setPhone(phone);
    student.setCourseName(courseName);
    student.setCourseDescription(courseDescription);
    allStudents.add(student);
    * Insert the method's description here.
    * Creation date: (2/24/03 12:00:53 PM)
    * @param index Student
    public Student findStudent(int index) {
    return (Student)allStudents.get(index);
    * Insert the method's description here.
    * Creation date: (2/24/03 12:02:43 PM)
    * @return java.util.Iterator
    public Iterator getStudentIterator() {
    return allStudents.iterator();
    * Insert the method's description here.
    * Creation date: (2/24/03 11:59:41 AM)
    * @param student Student
    public void removeStudent(Student student) {
    allStudents.remove(student);
    // CODE 5 Grade
    * Insert the type's description here.
    * Creation date: (2/24/03 11:29:38 AM)
    * @author: Delmarie
    public class Grade {
    private double score, possibleScore;
    private String gradeType;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:46:07 AM)
    public Grade() {}
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @return java.lang.String
    public java.lang.String getGradeType() {
    return gradeType;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @return double
    public double getPossibleScore() {
    return possibleScore;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @return double
    public double getScore() {
    return score;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @param newGradeType java.lang.String
    public void setGradeType(java.lang.String newGradeType) {
    gradeType = newGradeType;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @param newPossibleScore double
    public void setPossibleScore(double newPossibleScore) {
    possibleScore = newPossibleScore;
    * Insert the method's description here.
    * Creation date: (2/24/03 11:31:13 AM)
    * @param newScore double
    public void setScore(double newScore) {
    score = newScore;
    * Insert the method's description here.
    * Creation date: (2/24/03 4:03:57 PM)
    * @return java.lang.String
    public String toString() {
    return Double.toString(score);

    Ok.
    I had a look at your code and decided against showing you how to
    modify it to do what you want....
    Reason being that it's something of a mess. I guess the reason for that
    mess is a combination of the fact that you're new to Java (new to
    software in general?) and you're using Visual Age.
    So, below is a very quick (far from perfect, I just knocked it up in my
    lunch hour) example of the kind of approach I would take to the problem.
    Feel free to take ideas from it and build them in to your code.
    Whatever you do, don't hand it in as you own work. By all means, hand
    it in in addition to your own work and maybe even get your
    teacher to comment on it.
    Oh yes, if you use it, chuck me some dukes form this and your earlier
    post on the same subject. Too many folks these days are neglecting to
    allocate dukes - don't be one of them!
    Oh, one thing about using the app, double clicking on table entries
    for students and grades brings up the appropriate dialog. To create
    a new grade or delete the selected ones, use the "right mouse" context
    menu.
    Enjoy.
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.text.*;
    public class Rosemary2
         static class GradeDialog
              extends JDialog
              private JTextField mScore= new JTextField();
              private JTextField mPossibleScore= new JTextField();
              private JTextField mGradeType= new JTextField();
              private Grade mGrade;
              public GradeDialog(JDialog owner) { this(owner, null); }
              public GradeDialog(JDialog owner, Grade grade)
                   super(owner, true);
                   mGrade= grade;
                   if (mGrade == null)
                        setTitle("New Grade");
                   else {
                        setTitle("Edit Grade");
                        setGrade();
                   JPanel panel= new JPanel();
                   panel.setBorder(new EmptyBorder(4,4,4,4));
                   panel.setLayout(new GridLayout(0,2,4,4));
                   panel.add(new JLabel("Score:"));
                   panel.add(mScore);
                   panel.add(new JLabel("Possible Score:"));
                   panel.add(mPossibleScore);
                   panel.add(new JLabel("Grade Type:"));
                   panel.add(mGradeType);
                   getContentPane().add(panel, BorderLayout.CENTER);
                   panel= new JPanel();
                   panel.setLayout(new GridLayout(1,0));
                   JButton ok= new JButton("OK");
                   panel.add(ok);
                   ok.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (scrapeGrade())
                                  dispose();
                   JButton cancel= new JButton("Cancel");
                   panel.add(cancel);
                   cancel.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             mGrade= null;
                             dispose();
                   JPanel wrapper= new JPanel();
                   wrapper.setBorder(new EmptyBorder(0,4,4,4));
                   wrapper.setLayout(new BorderLayout());
                   wrapper.add(panel, BorderLayout.EAST);
                   getContentPane().add(wrapper, BorderLayout.SOUTH);
                   setResizable(false);
                   pack();
                   setLocation(
                        owner.getLocation().x +
                             (owner.getSize().width/2) -
                                  (getSize().width/2),
                        owner.getLocation().y +
                             (owner.getSize().height/2) -
                                  (getSize().height/2));
              private void setGrade()
                   mScore.setText(String.valueOf(mGrade.getScore()));
                   mPossibleScore.setText(String.valueOf(mGrade.getPossibleScore()));
                   mGradeType.setText(mGrade.getGradeType());
                   mScore.selectAll();
              private boolean scrapeGrade()
                   try {
                        if (mGrade == null) {
                             mGrade= new Grade(
                                  Double.parseDouble(mScore.getText()),
                                  Double.parseDouble(mPossibleScore.getText()),
                                  mGradeType.getText());
                        else {
                             mGrade.setScore(Double.parseDouble(mScore.getText()));
                             mGrade.setPossibleScore(Double.parseDouble(mPossibleScore.getText()));
                             mGrade.setGradeType(mGradeType.getText());
                        return true;
                   catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(this, "Scores must be numbers, you Muppet!");
                   return false;
              public Grade getGrade() { return mGrade; }
         static class GradesPanel
              extends JPanel
              private Vector mGrades= new Vector();
              private JTable mTable;
              private NumberFormat mFormat= NumberFormat.getInstance();
              private JDialog mParent;
              public GradesPanel(JDialog parent, Iterator grades)
                   mParent= parent;
                   mFormat.setMaximumFractionDigits(2);
                   while (grades != null && grades.hasNext())
                        mGrades.add(grades.next());
                   setLayout(new BorderLayout());
                   setBorder(new EmptyBorder(4,4,4,4));
                   createTable();
                   JScrollPane sp= new JScrollPane(mTable);
                   add(sp, BorderLayout.CENTER);
                   MouseListener listener= new MouseAdapter() {
                        public void mousePressed(MouseEvent e) {
                             if (e.getButton() == e.BUTTON2 || e.getButton() == e.BUTTON3)     
                                  menu(e.getPoint());
                   mTable.addMouseListener(listener);
                   sp.addMouseListener(listener);
                   mTable.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                             if (e.getClickCount() >= 2)
                                  editGrade();
              public Iterator getGrades() { return mGrades.iterator(); }
              private void createTable()
                   mTable= new JTable(new AbstractTableModel() {
                        public int getColumnCount() {
                             return 4;
                        public int getRowCount() {
                             return mGrades.size();
                        public String getColumnName(int column) {
                             switch (column) {
                                  case 0: return "Score";
                                  case 1: return "Possible";
                                  case 2: return "Type";
                                  case 3: return "Grade";
                                  default: return "###";
                        public Object getValueAt(int row, int column) {
                             Grade grade= (Grade) mGrades.elementAt(row);
                             switch (column) {
                                  case 0: return mFormat.format(grade.getScore());
                                  case 1: return mFormat.format(grade.getPossibleScore());
                                  case 2: return grade.getGradeType();
                                  case 3: return String.valueOf(grade.getGrade()) +"%";
                                  default: return "###";
                   mTable.setPreferredScrollableViewportSize(new Dimension(10,10));
              private void menu(Point point)
                   JPopupMenu popup= new JPopupMenu();
                   JMenuItem add= new JMenuItem("Add");
                   popup.add(add);
                   add.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { addGrade(); } });
                   if (mTable.rowAtPoint(point) >= 0 && mTable.rowAtPoint(point) == mTable.getSelectedRow()) {
                        JMenuItem edit= new JMenuItem("Edit");
                        popup.add(edit);
                        edit.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) { editGrade(); } });
                        if (mTable.getSelectedRowCount() > 1)
                             edit.setEnabled(false);
                        JMenuItem delete= new JMenuItem("Delete");
                        popup.add(delete);
                        delete.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) { deleteGrade(); } });
                   popup.show(this, point.x, point.y);
              private void addGrade()
                   GradeDialog dialog= new GradeDialog(mParent);
                   dialog.setVisible(true);
                   Grade grade= dialog.getGrade();
                   if (grade != null) {
                        mGrades.add(grade);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsInserted(
                             mGrades.size()-1, mGrades.size()-1);
              private void editGrade()
                   GradeDialog dialog= new GradeDialog(
                        mParent, (Grade) mGrades.get(mTable.getSelectedRow()));
                   dialog.setVisible(true);
                   if (dialog.getGrade() != null) {
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsUpdated(
                             mTable.getSelectedRow(), mTable.getSelectedRow());
              private void deleteGrade()
                   while (true) {
                        int row= mTable.getSelectedRow();
                        if (row < 0)
                             break;
                        mGrades.removeElementAt(row);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsDeleted(row, row);
         static class StudentDialog
              extends JDialog
              private JTextField mName= new JTextField(12);
              private JTextField mAddress= new JTextField();
              private JTextField mPhone= new JTextField();
              private JTextField mEmail= new JTextField();
              private JTextField mCourseName= new JTextField();
              private JTextField mCourseDescription= new JTextField();
              private GradesPanel mGradesPanel;
              private Student mStudent;
              public StudentDialog(JFrame owner) { this(owner, null); }
              public StudentDialog(JFrame owner, Student student)
                   super(owner, true);
                   mStudent= student;
                   if (mStudent == null) {
                        setTitle("New Student");
                        mGradesPanel= new GradesPanel(this, null);
                   else {
                        setTitle("Edit Student: " +mStudent.getName());
                        mGradesPanel= new GradesPanel(this, mStudent.getGrades());
                   JTabbedPane tab= new JTabbedPane();
                   tab.setBorder(new EmptyBorder(4,4,4,4));
                   getContentPane().add(tab, BorderLayout.CENTER);
                   tab.add("Details", getDetailsPanel());
                   tab.add("Grades", mGradesPanel);
                   JPanel panel= new JPanel();
                   panel.setLayout(new GridLayout(1,0));
                   JButton ok= new JButton("OK");
                   panel.add(ok);
                   ok.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             scrapeStudent();
                             dispose();
                   JButton cancel= new JButton("Cancel");
                   panel.add(cancel);
                   cancel.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             mStudent= null;
                             dispose();
                   JPanel wrapper= new JPanel();
                   wrapper.setBorder(new EmptyBorder(0,4,4,4));
                   wrapper.setLayout(new BorderLayout());
                   wrapper.add(panel, BorderLayout.EAST);
                   getContentPane().add(wrapper, BorderLayout.SOUTH);
                   setResizable(false);
                   pack();
                   if (mStudent != null)
                        setStudent();
                   setLocation(
                        owner.getLocation().x +
                             (owner.getSize().width/2) -
                                  (getSize().width/2),
                        owner.getLocation().y +
                             (owner.getSize().height/2) -
                                  (getSize().height/2));
              private JPanel getDetailsPanel()
                   JPanel panel= new JPanel();
                   panel.setBorder(new EmptyBorder(4,4,4,4));
                   panel.setLayout(new GridLayout(0,2,4,4));
                   panel.add(new JLabel("Name:"));
                   panel.add(mName);
                   panel.add(new JLabel("Address:"));
                   panel.add(mAddress);
                   panel.add(new JLabel("Phone:"));
                   panel.add(mPhone);
                   panel.add(new JLabel("E-Mail:"));
                   panel.add(mEmail);
                   panel.add(new JLabel("Course Name:"));
                   panel.add(mCourseName);
                   panel.add(new JLabel("Course Description:"));
                   panel.add(mCourseDescription);
                   return panel;
              private void setStudent()
                   mName.setEnabled(false);
                   mName.setText(mStudent.getName());
                   mAddress.setText(mStudent.getAddress());
                   mPhone.setText(mStudent.getPhone());
                   mEmail.setText(mStudent.getEmail());
                   mCourseName.setText(mStudent.getCourseName());
                   mCourseDescription.setText(mStudent.getCourseDescription());
              private void scrapeStudent()
                   if (mStudent == null) {
                        mStudent= new Student(
                             mName.getText(),
                             mAddress.getText(),
                             mPhone.getText(),
                             mEmail.getText(),
                             mCourseName.getText(),
                             mCourseDescription.getText());
                   else {
                        mStudent.setName(mName.getText());
                        mStudent.setAddress(mAddress.getText());
                        mStudent.setPhone(mPhone.getText());
                        mStudent.setEmail(mEmail.getText());
                        mStudent.setCourseName(mCourseName.getText());
                        mStudent.setCourseDescription(mCourseDescription.getText());
                   mStudent.clearGrades();
                   Iterator grades= mGradesPanel.getGrades();
                   while (grades.hasNext())
                        mStudent.addGrade((Grade) grades.next());
              public Student getStudent() { return mStudent; }
         static class StudentFrame
              extends JFrame
              private Vector mStudents;
              private JTable mTable;
              private JButton mBtnEdit;
              private JButton mBtnDelete;
              public StudentFrame(Vector students)
                   super("Students");
                   mStudents= students;
                   createTable();
                   getContentPane().add(new JScrollPane(mTable), BorderLayout.CENTER);
                   JPanel panel= new JPanel();
                   panel.setLayout(new GridLayout(1,0));
                   JButton btn= new JButton("Add");
                   panel.add(btn);
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { addStudent(); } });
                   mBtnEdit= new JButton("Edit");
                   panel.add(mBtnEdit);
                   mBtnEdit.setEnabled(false);
                   mBtnEdit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { editStudent(); } });
                   mBtnDelete= new JButton("Delete");
                   panel.add(mBtnDelete);
                   mBtnDelete.setEnabled(false);
                   mBtnDelete.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { deleteStudent(); } });
                   JPanel wrapper= new JPanel();
                   wrapper.setLayout(new BorderLayout());
                   wrapper.add(panel, BorderLayout.WEST);
                   getContentPane().add(wrapper, BorderLayout.SOUTH);
                   btn= new JButton("Exit");
                   wrapper.add(btn, BorderLayout.EAST);
                   btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) { System.exit(0); } });
                   pack();
              private void createTable()
                   mTable= new JTable(new AbstractTableModel() {
                        public int getColumnCount() {
                             return 7;
                        public int getRowCount() {
                             return mStudents.size();
                        public String getColumnName(int column) {
                             switch (column) {
                                  case 0: return "Name";
                                  case 1: return "Address";
                                  case 2: return "Phone";
                                  case 3: return "Email";
                                  case 4: return "Course";
                                  case 5: return "Description";
                                  case 6: return "Grade Average";
                                  default: return "###";
                        public Object getValueAt(int row, int column) {
                             Student student= (Student) mStudents.elementAt(row);
                             switch (column) {
                                  case 0: return student.getName();
                                  case 1: return student.getAddress();
                                  case 2: return student.getPhone();
                                  case 3: return student.getEmail();
                                  case 4: return student.getCourseName();
                                  case 5: return student.getCourseDescription();
                                  case 6: return student.getGrade() >= 0 ? String.valueOf(student.getGrade()) +"%": "n/a";
                                  default: return "###";
                   mTable.getSelectionModel().addListSelectionListener(
                        new ListSelectionListener() {
                             public void valueChanged(ListSelectionEvent e) {
                                  if (e.getValueIsAdjusting())
                                       return;
                                  switch (mTable.getSelectedRowCount()) {
                                       case 0:
                                            mBtnEdit.setEnabled(false);
                                            mBtnDelete.setEnabled(false);
                                            break;
                                       case 1:
                                            mBtnEdit.setEnabled(true);
                                            mBtnDelete.setEnabled(true);
                                            break;
                                       default:
                                            mBtnEdit.setEnabled(false);
                                            mBtnDelete.setEnabled(true);
                                            break;
                   mTable.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                             if (e.getClickCount() >= 2)
                                  editStudent();
              private void addStudent()
                   StudentDialog dialog= new StudentDialog(this);
                   dialog.setVisible(true);
                   Student student= dialog.getStudent();
                   if (student != null) {
                        mStudents.add(student);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsInserted(
                             mStudents.size()-1, mStudents.size()-1);
              private void editStudent()
                   StudentDialog dialog= new StudentDialog(
                        this, (Student) mStudents.get(mTable.getSelectedRow()));
                   dialog.setVisible(true);
                   if (dialog.getStudent() != null) {
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsUpdated(
                             mTable.getSelectedRow(), mTable.getSelectedRow());
              private void deleteStudent()
                   while (true) {
                        int row= mTable.getSelectedRow();
                        if (row < 0)
                             break;
                        mStudents.removeElementAt(row);
                        ((AbstractTableModel) mTable.getModel()).fireTableRowsDeleted(row, row);
         static class Student
              private String name;
              private String address;
              private String phone ;
              private String email;
              private String courseName;
              private String courseDescription;
              private Vector grades= new Vector();
              public Student(
                   String name,
                   String address,
                   String phone,
                   String email,
                   String courseName,
                   String courseDescription)
                   setName(name);
                   setAddress(address);
                   setPhone(phone);
                   setEmail(email);
                   setCourseName(courseName);
                   setCourseDescription(courseDescription);
              public Iterator getGrades() { return grades.iterator(); }
              public void addGrade(Grade grade) { grades.add(grade); }
              public void removeGrade(Grade grade) { grades.remove(grade); }
              public void clearGrades() { grades.clear(); }
              public int getGrade()
                   if (grades.size() == 0)
                        return -1;
                   int total= 0;
                   for (int i= 0; i< grades.size(); i++)
                        total += ((Grade) grades.get(i)).getGrade();
                   return (int) (total/grades.size());
              public String getAddress() { return address; }
              public void setAddress(String newAddress) { address = newAddress; }
              public String getCourseDescription() { return courseDescription; }
              public void setCourseDescription(String newCourseDescription) { courseDescription = newCourseDescription; }
              public String getCourseName() { return courseName; }
              public void setCourseName(String newCourseName) { courseName = newCourseName; }
              public String getEmail() { return email; }
              public void setEmail(String newEmail) { email = newEmail; }
              public String getName() { return name; }
              public void setName(String newName) { name = newName; }
              public String getPhone() { return phone; }
              public void setPhone(String newPhone) { phone = newPhone; }
         static class Grade
              private double score;
              private double possibleScore;
              private String gradeType;
              public Grade(
                   double score,
                   double possibleScore,
                   String gradeType)
                   setScore(score);
                   setPossibleScore(possibleScore);
                   setGradeType(gradeType);
              public int getGrade() { return (int) ((100/possibleScore)*score); }
              public String getGradeType() { return gradeType; }
              public void setGradeType(String newGradeType) { gradeType = newGradeType; }
              public double getPossibleScore() { return possibleScore; }
              public void setPossibleScore(double newPossibleScore) { possibleScore = newPossibleScore; }
              public double getScore() { return score; }
              public void setScore(double newScore) { score = newScore; }
              public String toString() { return Double.toString(score); }
         public static void main (String [] args)
              Vector students= new Vector();
              students.add(new Student(
                   "Fred Flitstone",
                   "6 Boulder Close, Bedrock",
                   "555 1234",
                   "[email protected]",
                   "Masonary 101",
                   "Elementary chipping bits off rocks"));
              students.add(new Student(
                   "Barney Rubble",
                   "7 Boulder Close, Bedrock",
                   "555 6789",
                   "[email protected]",
                   "Masonary 101",
                   "Elementary chipping bits off rocks"));
              for (int i= 0; i< 10; i++) {
                   Student student= new Student(
                        "Student " +i,
                        i +" Dorm St, Campus",
                        "555 1234",
                        "student" +i +"@college.edu",
                        "CS 101",
                        "CS for dummies");
                   student.addGrade(new Grade(Math.random()*100, 100.0, "Passing?"));
                   student.addGrade(new Grade(Math.random()*100, 100.0, "Failing?"));
                   students.add(student);
              StudentFrame frame= new StudentFrame(students);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setBounds(32,32,640,480);
              frame.setVisible(true);
    }

  • Help needed in this code

    Hi guys, I need help in debugging this code I made, which is a GUI minesweeper. Its extremely buggy...I particularly need help fixing the actionListener part of the code as everytime I press a button on the GUI, an exception occurs.
    help please!
    package minesweeperGUI;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MinesweeperGUI implements ActionListener
         //Declaration of attributes
         static int length = 0;
         JMenuItem menuItemNew = new JMenuItem();
         JRadioButtonMenuItem rbEasy = new JRadioButtonMenuItem();
         JRadioButtonMenuItem rbHard = new JRadioButtonMenuItem();
         JMenuItem menuItemExit = new JMenuItem();
         JButton buttonReset = new JButton();
         JButton buttonGrid[][] = null;
         JFrame frame = new JFrame();
         int getBombsTotal = 0;
         JLabel setBombsLabel = new JLabel();
         int a = 0;
         int b = 0;     
         //No constructor created. Uses default constructor
         //Create the menu bar
         public JMenuBar newMenuBar()
              //Sets up the menubar
              JMenuBar menuBar = new JMenuBar();
              //Sets up the Game menu with choice of new, grid size, and exit
              JMenu menu = new JMenu ("Game");
              menuBar.add (menu);
              menuItemNew = new JMenuItem ("New");
              menuItemNew.addActionListener (this);
              menu.add (menuItemNew);
              menu.addSeparator();
              //Sets up sub-menu for grid size with choice of easy and hard radio buttons
              JMenu subMenu = new JMenu ("Grid Size");
              rbEasy = new JRadioButtonMenuItem ("Easy: 5x5 grid");
              rbEasy.addActionListener (this);
              subMenu.add (rbEasy);
              rbHard = new JRadioButtonMenuItem ("Hard: 10x10 grid");
              rbHard.addActionListener (this);
              subMenu.add (rbHard);
              menu.add (subMenu);
              menu.addSeparator();
              menuItemExit = new JMenuItem ("Exit");
              menuItemExit.addActionListener (this);
              menu.add (menuItemExit);
              return menuBar;
         //Setting up of Bomb Grid
         public int [][] setGrid (int length)
              int grid[][] = null;
              grid = new int[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        grid[i][j] = ((int)Math.round(Math.random() * 10))% 2;
              return grid;     
         //Setting up of the of the graphical bomb grid
         public JButton[][] setButtonGrid (int length)
              JButton buttonGrid[][] = null;
              buttonGrid = new JButton[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        buttonGrid[i][j] = new JButton();
              return buttonGrid;
         //Setting up of a way to count the total number of bombs in the bomb grid
         public int getBombsTotal (int length, int setGrid[][])
              int bombsTotal = 0;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (setGrid[i][j] == 1)
                             bombsTotal += 1;
              return bombsTotal;
         //Create a label for number of bombs left
         public JLabel setBombsLabel (int getBombsTotal)
              JLabel bombsLabel = new JLabel(String.valueOf (getBombsTotal) + " Bombs Left");
              return bombsLabel;
         //Setting up a way to count the number of bombs around a button
         public String setBombs (int length, int setGrid[][], int x, int y)
              int bombs[][] = new int[length][length];
              String bombsString = null;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (i == 0 && j == 0)
                             bombs[i][j] = setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i ==0 && j == (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else if (i == (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1];
                        else if (i == (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1];
                        else if (i == 0 && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i][j+1] +
                                  setGrid[i+1][j-1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i == (length - 1) && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1];
                        else if (i != 0 && i != (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i != 0 && i != (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j] + setGrid[i+1][j+1];
              bombsString = String.valueOf (bombs[x][y]);
              return bombsString;
         //create the panel for the bombs label and reset button
         public JPanel newTopPanel(int length)
              int setGridNew [][] = null;
              setGridNew = new int[length][length];
              int getBombsTotalNew = 0;
              JLabel setBombsLabelNew = new JLabel();
              setGridNew = setGrid (length);
              getBombsTotalNew = getBombsTotal (length, setGridNew);
              setBombsLabelNew = setBombsLabel (getBombsTotalNew);
              JPanel topPanel = new JPanel ();
              topPanel.setLayout (new BorderLayout (50,50));
              JLabel bombsLabel = new JLabel ();
              bombsLabel = setBombsLabelNew;     
              topPanel.add (bombsLabel, BorderLayout.WEST);
              buttonReset = new JButton("Reset");
              buttonReset.addActionListener (this);
              topPanel.add (buttonReset, BorderLayout.CENTER);
              return topPanel;
         //create the panel for the play grids
         public JPanel newBottomPanel(int length)
              JButton setButtonGridNew[][] = null;
              setButtonGridNew = new JButton [length][length];
              setButtonGridNew = setButtonGrid (length);
              JPanel bottomPanel = new JPanel ();
              bottomPanel.setLayout (new GridLayout (length, length));
              buttonGrid = new JButton[length][length];          
              for (a = 0; a < length; a++)
                   for (b = 0; b < length; b++)
                        buttonGrid[a] = setButtonGridNew[a][b];
                        buttonGrid[a][b].addActionListener (this);
                        bottomPanel.add (buttonGrid[a][b]);
              return bottomPanel;
         //Overiding of abstract method actionPerformed
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == menuItemNew)
                   launchFrame(length);
              else if (e.getSource() == menuItemExit)
                   frame.setVisible (false);
                   System.exit(0);
              else if (e.getSource() == rbEasy)
                   length = 5;
                   launchFrame(length);
              else if (e.getSource() == rbHard)
                   length = 10;
                   launchFrame(length);     
              else if (e.getSource() == buttonReset)
                   launchFrame(length);
              else if (e.getSource() == buttonGrid[a][b])
                   int setGridNew [][] = null;
                   setGridNew = new int[length][length];               
                   JButton bombButton [][] = null;
                   bombButton = new JButton [length][length];
                   String bombString [][] = null;
                   bombString = new String[length][length];
                   setGridNew = setGrid (length);               
                   bombString[a][b] = setBombs (length, setGridNew, a, b);
                   bombButton[a][b] = new JButton (bombString[a][b]);
                   if (setGridNew[a][b] == 0)
                        buttonGrid[a][b] = bombButton[a][b];
                        getBombsTotal--;
                        JLabel setBombsLabelNew = new JLabel();
                        setBombsLabelNew = setBombsLabel (getBombsTotal);
                   else if (setGridNew[a][b] == 1 )
                        buttonGrid[a][b] = new JButton("x");
                        JOptionPane.showMessageDialog (null, "Game Over. You hit a Bomb!");
                        System.exit(0);     
         //create the content pane
         public Container newContentPane(int length)
              JPanel topPanel = new JPanel();
              JPanel bottomPanel = new JPanel();          
              topPanel = newTopPanel(length);
              bottomPanel = newBottomPanel (length);
              JPanel contentPane = new JPanel();
              contentPane.setOpaque (true);
              contentPane.setLayout (new BorderLayout(50,50));
              contentPane.add (topPanel, BorderLayout.NORTH);
              contentPane.add (bottomPanel, BorderLayout.CENTER);
              return contentPane;
         public void launchFrame (int length)
              //Makes sure we have nice window decorations
              JFrame.setDefaultLookAndFeelDecorated(true);          
              //Sets up the top-level window     
              frame = new JFrame ("Minesweeper");
              //Exits program when the closed button is clicked
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar menuBar = new JMenuBar();
              Container contentPane = new Container();
              menuBar = newMenuBar();
              contentPane = newContentPane (length);
              //Sets up the menu bar and content pane
              frame.setJMenuBar (menuBar);
              frame.setContentPane (contentPane);
              //Displays the window
              frame.pack();
              frame.setVisible (true);
         public static void main (String args[])
              //Default length is 5
              length = 5;
              MinesweeperGUI minesweeper = new MinesweeperGUI();
              minesweeper.launchFrame(length);

    hi, thanks. that removed the exception; although now the buttons action listener won't work :(
    here is the revised code:
    To anyone out there, can you guys run this code and help me debug it?
    I'm really desperate as this is a school project of mine and the deadline is 7 hours away. I have already been working on it for 3 days, but the program is still very buggy.
    thanks!
    /* Oliver Ian C. Wee 04-80112
    * CS12 MHRU
    * Machine Problem 2
    package minesweeperGUI;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MinesweeperGUI implements ActionListener
         //Declaration of attributes
         static int length = 0;
         JMenuItem menuItemNew = new JMenuItem();
         JRadioButtonMenuItem rbEasy = new JRadioButtonMenuItem();
         JRadioButtonMenuItem rbHard = new JRadioButtonMenuItem();
         JMenuItem menuItemExit = new JMenuItem();
         JButton buttonReset = new JButton();
         JButton buttonGrid[][] = null;
         JFrame frame = new JFrame();
         int getBombsTotal = 0;
         JLabel setBombsLabel = new JLabel();
         int a = 0;
         int b = 0;
         //No constructor created. Uses default constructor
         //Create the menu bar
         public JMenuBar newMenuBar()
              //Sets up the menubar
              JMenuBar menuBar = new JMenuBar();
              //Sets up the Game menu with choice of new, grid size, and exit
              JMenu menu = new JMenu ("Game");
              menuBar.add (menu);
              menuItemNew = new JMenuItem ("New");
              menuItemNew.addActionListener (this);
              menu.add (menuItemNew);
              menu.addSeparator();
              //Sets up sub-menu for grid size with choice of easy and hard radio buttons
              JMenu subMenu = new JMenu ("Grid Size");
              ButtonGroup bg = new ButtonGroup();
              rbEasy = new JRadioButtonMenuItem ("Easy: 5x5 grid");
              bg.add (rbEasy);
              rbEasy.addActionListener (this);
              subMenu.add (rbEasy);
              rbHard = new JRadioButtonMenuItem ("Hard: 10x10 grid");
              bg.add (rbHard);
              rbHard.addActionListener (this);
              subMenu.add (rbHard);
              menu.add (subMenu);
              menu.addSeparator();
              menuItemExit = new JMenuItem ("Exit");
              menuItemExit.addActionListener (this);
              menu.add (menuItemExit);
              return menuBar;
         //Setting up of Bomb Grid
         public int [][] setGrid (int length)
              int grid[][] = null;
              grid = new int[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        grid[i][j] = ((int)Math.round(Math.random() * 10))% 2;
              return grid;     
         //Setting up of the of the graphical bomb grid
         public JButton[][] setButtonGrid (int length)
              JButton buttonGrid[][] = null;
              buttonGrid = new JButton[length][length];
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        buttonGrid[i][j] = new JButton();
              return buttonGrid;
         //Setting up of a way to count the total number of bombs in the bomb grid
         public int getBombsTotal (int length, int setGrid[][])
              int bombsTotal = 0;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (setGrid[i][j] == 1)
                             bombsTotal += 1;
              return bombsTotal;
         //Create a label for number of bombs left
         public JLabel setBombsLabel (int getBombsTotal)
              JLabel bombsLabel = new JLabel("  " +String.valueOf (getBombsTotal) + " Bombs Left");
              return bombsLabel;
         //Setting up a way to count the number of bombs around a button
         public String setBombs (int length, int setGrid[][], int x, int y)
              int bombs[][] = new int[length][length];
              String bombsString = null;
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        if (i == 0 && j == 0)
                             bombs[i][j] = setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i ==0 && j == (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else if (i == (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1];
                        else if (i == (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1];
                        else if (i == 0 && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i][j-1] + setGrid[i][j+1] +
                                  setGrid[i+1][j-1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i == (length - 1) && j != 0 && j != (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1];
                        else if (i != 0 && i != (length - 1) && j == 0)
                             bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
                                  setGrid[i][j+1] + setGrid[i+1][j] +
                                  setGrid[i+1][j+1];
                        else if (i != 0 && i != (length - 1) && j == (length - 1))
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i][j-1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j];
                        else
                             bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
                                  setGrid[i-1][j+1] + setGrid[i][j-1] +
                                  setGrid[i][j+1] + setGrid[i+1][j-1] +
                                  setGrid[i+1][j] + setGrid[i+1][j+1];
              bombsString = String.valueOf (bombs[x][y]);
              return bombsString;
         //create the panel for the bombs label and reset button
         public JPanel newTopPanel(int length)
              int setGridNew [][] = null;
              setGridNew = new int[length][length];
              int getBombsTotalNew = 0;
              JLabel setBombsLabelNew = new JLabel();
              setGridNew = setGrid (length);
              getBombsTotalNew = getBombsTotal (length, setGridNew);
              setBombsLabelNew = setBombsLabel (getBombsTotalNew);
              JPanel topPanel = new JPanel ();
              topPanel.setLayout (new BorderLayout (20,20));
              JLabel bombsLabel = new JLabel ();
              bombsLabel = setBombsLabelNew;     
              topPanel.add (bombsLabel, BorderLayout.WEST);
              buttonReset = new JButton("Reset");
              buttonReset.addActionListener (this);
              topPanel.add (buttonReset, BorderLayout.CENTER);
              return topPanel;
         //create the panel for the play grids
         public JPanel newBottomPanel(int length)
              JButton setButtonGridNew[][] = null;
              setButtonGridNew = new JButton [length][length];
              setButtonGridNew = setButtonGrid (length);
              JPanel bottomPanel = new JPanel ();
              bottomPanel.setLayout (new GridLayout (length, length));
              buttonGrid = new JButton[length][length];          
              for (int i = 0; i < length; i++)
                   for (int j = 0; j < length; j++)
                        buttonGrid[i][j] = setButtonGridNew[i][j];
                        buttonGrid[i][j].addActionListener (this);
                        bottomPanel.add (buttonGrid[i][j]);
              return bottomPanel;
         //Overiding of abstract method actionPerformed
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == menuItemNew)
                   closeFrame();
                   launchFrame(length);
              else if (e.getSource() == menuItemExit)
                   frame.setVisible (false);
                   System.exit(0);
              else if (e.getSource() == rbEasy)
                   closeFrame();
                   length = 5;
                   launchFrame(length);
              else if (e.getSource() == rbHard)
                   closeFrame();
                   length = 10;
                   launchFrame(length);     
              else if (e.getSource() == buttonReset)
                   closeFrame();
                   launchFrame(length);
              else if (e.getSource() == buttonGrid[a])
                   int setGridNew [][] = null;
                   setGridNew = new int[length][length];               
                   JButton bombButton [][] = null;
                   bombButton = new JButton [length][length];
                   String bombString [][] = null;
                   bombString = new String[length][length];
                   setGridNew = setGrid (length);               
                   for (int i = 0; i < length; i++)
                        for (int j = 0; j < length; j++)
                             bombString[i][j] = setBombs (length, setGridNew, i, j);
                             bombButton[i][j] = new JButton (bombString[i][j]);
                   if (setGridNew[a][b] == 0)
                        buttonGrid[a][b] = bombButton[a][b];
                        getBombsTotal--;
                        JLabel setBombsLabelNew = new JLabel();
                        setBombsLabelNew = setBombsLabel (" " String.valueOf (getBombsTotal) " Bombs Left");
                   else if (setGridNew[a][b] == 1 )
                        buttonGrid[a][b] = new JButton("x");
                        JOptionPane.showMessageDialog (null, "Game Over. You hit a Bomb!");
                        System.exit(0);     
         //create the content pane
         public Container newContentPane(int length)
              JPanel topPanel = new JPanel();
              JPanel bottomPanel = new JPanel();          
              topPanel = newTopPanel(length);
              bottomPanel = newBottomPanel (length);
              JPanel contentPane = new JPanel();
              contentPane.setOpaque (true);
              contentPane.setLayout (new BorderLayout(5,5));
              contentPane.add (topPanel, BorderLayout.NORTH);
              contentPane.add (bottomPanel, BorderLayout.CENTER);
              return contentPane;
         public void closeFrame ()
              frame = new JFrame ("Minesweeper");
              frame.dispose();
         public void launchFrame (int length)
              //Makes sure we have nice window decorations
              JFrame.setDefaultLookAndFeelDecorated(true);          
              //Sets up the top-level window     
              frame = new JFrame ("Minesweeper");
              //Exits program when the closed button is clicked
              frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JMenuBar menuBar = new JMenuBar();
              Container contentPane = new Container();
              menuBar = newMenuBar();
              contentPane = newContentPane (length);
              //Sets up the menu bar and content pane
              frame.setJMenuBar (menuBar);
              frame.setContentPane (contentPane);
              //Displays the window
              frame.pack();
              frame.setVisible (true);
         public static void main (String args[])
              //Default length is 5
              length = 5;
              MinesweeperGUI minesweeper = new MinesweeperGUI();
              minesweeper.launchFrame(length);

  • Please give me flowchart for this code...

    Writing a Java applet to communicate with a serial device attached to the Device
    Server is very straightforward. However, familiarity with Java programming and a
    Java compiler are required.
    As with any network application, open a communication channel to the remote
    device. In our example, a socket is opened and and two data streams are created to
    perform the actual sending and receiving of data.
    The following example uses a new Java Class called tcpip. Copy the following code
    into a file called tcpip.java.
    import java.*;
    import java.lang.*;
    import java.net.*;
    import java.util.*;
    import java.io.*;
    * This class opens a TCP connection, and allows reading and writing of byte
    arrays.
    public class tcpip
    protected Socket s = null;
    public DataInputStream dis = null;
    protected DataOutputStream dos = null;
    public tcpip(InetAddress ipa, int port)
    Socket s1 = null;
    try { // Open the socket
    s1 = new Socket(ipa.getHostAddress(), port);
    catch (IOException e) {
    System.out.println("Error opening socket");
    return;
    s = s1;
    try { // Create an input stream
    dis = new DataInputStream(new
    BufferedInputStream(s.getInputStream()));
    catch(Exception ex) {
    System.out.println("Error creating input stream");
    try { // Create an output stream
    dos = new DataOutputStream(new
    BufferedOutputStream(s.getOutputStream()));
    catch(Exception ex) {
    System.out.println("Error creating output stream");
    public synchronized void disconnect()
    if (s != null) {
    try {
    s.close();
    catch (IOException e){}
    public synchronized void send(byte[] temp)
    try {
    dos.write(temp, 0, temp.length);
    dos.flush();
    catch(Exception ex) {
    System.out.println("Error sending data : " + ex.toString());
    public synchronized void send(byte[] temp, int len)
    try {
    dos.write(temp, 0, len);
    dos.flush();
    catch(Exception ex) {
    System.out.println("Error sending data : " + ex.toString());
    public synchronized void send(String given)
    // WARNING: this routine may not properly convert Strings to bytes
    int length = given.length();
    byte[] retvalue = new byte[length];
    char[] c = new char[length];
    given.getChars(0, length, c, 0);
    for (int i = 0; i < length; i++) {
    retvalue[i] = (byte)c;
    send(retvalue);
    public synchronized byte[] receive()
    byte[] retval = new byte[0];
    try {
    while(dis.available() == 0); /* Wait for data */
    catch (IOException e){}
    try {
    retval = new byte[dis.available()];
    catch (IOException e){}
    try {
    dis.read(retval);
    catch (IOException e){}
    return(retval);
    public int available()
    int avail;
    avail = 0;
    try {
    avail = dis.available();
    catch (IOException e) {}
    return(avail);
    Next, create the Text_io class as the application. Copy the following code
    into a file called �Text_io.java�.
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    public class Text_io extends Panel implements Runnable,
    TextListener {
    private tcpip gtp;
    String oldmessage = new String("");
    TextArea input_box = new TextArea("", 10, 60, 3);
    TextArea output_box = new TextArea("", 10, 60, 3);
    Thread timer;
    public Text_io(tcpip tp) {
    gtp = tp;
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(5,5,5,5);
    setBackground(java.awt.Color.lightGray);
    setSize(561,380);
    c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.gridheight =
    1;
    c.weightx = 0.0; c.weighty = 0.0; c.anchor =
    GridBagConstraints.WEST;
    c.fill = GridBagConstraints.NONE;
    add((new Label("To Device Server: (Type Here--->)")), c);
    //input_box
    input_box.addTextListener(this);
    c.gridx = 1; c.gridy = 2; c.gridwidth = 3; c.gridheight =
    1;
    c.weightx = 0.5; c.weighty = 0.0; c.anchor =
    GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    add(input_box,c);
    c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.gridheight =
    1;
    c.weightx = 0.0; c.weighty = 0.0; c.anchor =
    GridBagConstraints.WEST;
    c.fill = GridBagConstraints.NONE;
    add((new Label("From Device Server:")), c);
    c.gridx = 1; c.gridy = 4; c.gridwidth = 3; c.gridheight =
    1;
    c.weightx = 0.5; c.weighty = 0.0; c.anchor =
    GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    add(output_box,c);
    output_box.setEditable(false);
    timer = new Thread(this);
    timer.start();
    public void run() {
    int i;
    byte[] in;
    Thread me = Thread.currentThread();
    while (timer == me) {
    try {
    Thread.currentThread().sleep(200);
    catch (InterruptedException e) { }
    if ( (gtp != null) && ((i = gtp.available()) > 0) ) {
    in = gtp.receive();
    /* remove non-printing bytes */
    for (i = 0; i < in.length; i++) {
    if (in[i] < 0x20)
    in[i] = 0x20;
    output_box.append((new String(in)));
    public void textValueChanged(TextEvent e) {
    int len, i;
    String str = new String("");
    String message = input_box.getText();
    len = message.length() - oldmessage.length();
    if (len < 0) {
    for (i = 0; i < -len; i++)
    str += "\b";
    //System.out.println("Backspace");
    else if (len > 0) {
    str = message.substring(oldmessage.length());
    //System.out.println("len = "+str.length()+" str =
    "+str);
    oldmessage = message;
    if ( (len != 0) && (gtp != null) )
    gtp.send(str);
    Next, create the actual applet that uses the tcpip and Text_io classes. Copy
    the following code into a file called �Test.java�.
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.net.*;
    import java.io.*;
    import java.lang.*;
    import java.text.*;
    import java.util.*;
    public class Test extends Applet {
    static private boolean isapplet = true;
    static private InetAddress arg_ip = null;
    static private int arg_port = 0;
    public tcpip gtp = null;;
    InetAddress reader_ip = null;
    int port = 10001;
    public void init()
    gtp = null;
    reader_ip = null;
    port = 10001;
    public void start()
    String st = new String("TCP/IP connection status: ");
    setFont(new Font("Dialog",Font.BOLD,16));
    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight
    = 1;
    c.anchor = GridBagConstraints.CENTER;
    c.fill = GridBagConstraints.BOTH;
    c.insets = new Insets(5,5,5,5);
    setBackground(Color.yellow);
    setSize(600,500);
    /* Either get the IP address from the HTTP server if
    we're an applet, or from the commandline (if passed).
    if (isapplet) {
    try{
    reader_ip = InetAddress.getByName(getCodeBase().getHost());
    catch (UnknownHostException e){}
    else {
    reader_ip = arg_ip;
    if (arg_port != 0) {
    port = arg_port;
    /* Open a socket to the Device Server's serial port
    if (reader_ip != null) {
    if (gtp == null) {
    gtp = new tcpip(reader_ip, port);
    if (gtp.s == null) {
    st += "Connection FAILED! ";
    gtp = null;
    if (gtp == null) {
    st += "Not Connected";
    add((new Label(st)), c);
    return;
    st += "Connected";
    add((new Label(st)), c);
    /* You may now perform IO with the Device Server via
    * gtp.send(byte[] data_out);
    * byte[] data_in = gtp.receive();
    * functions.
    * In our example we'll use two TextBoxes which have
    * been extended to handle IO to the Device Server.
    *Data typed in the upper text box will be sent to
    * the Device Server, and data received will be
    *displayed in the lower text box.
    /* Start of custom application code */
    /* ADD YOUR CODE HERE */
    c.gridx = 0; c.gridy = 2; c.gridwidth = 3; c.gridheight =
    1;
    c.anchor = GridBagConstraints.WEST;
    add((new Text_io(gtp)), c);
    /* End of custom application code */
    public void destroy()
    if (gtp != null)
    gtp.disconnect();
    gtp = null;
    public void stop() {
    public static void main(String[] args) {
    Frame frame = new Frame("TCP/IP Test");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    if (args.length > 0) {
    try{
    arg_ip = InetAddress.getByName(args[0]);
    catch (UnknownHostException e){}
    if (args.length > 1) {
    try {
    arg_port = Integer.valueOf(args[1]).intValue();
    catch (NumberFormatException e) {}
    Test ap = new Test();
    frame.add(ap);
    ap.init();
    isapplet = false;
    ap.start();
    frame.pack();
    frame.show();

    Let's see a decent try by you towards a solution first. I've found that usually the more thought and effort posters put into creating and solving their questions, the better their chances are of a volunteer here taking the time and effort to consider it and give a helpful answer. In other words, show that you are putting effort into doing your own homework first.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]or
    {&#99;ode}
      // your code block goes here.
      // note here that the tags are the same.
    {&#99;ode}good luck

  • Why does this code fail in command line?

    I am using the "ListDemo" from the java swing tutorial. If I compile it on the command line
    javac ListDemo.java
    It compiles fine. Then when I run it, it says:
    C:\Development\Java\Projects\Projects>java ListDemo
    Exception occurred during event dispatching:
    java.lang.NoSuchMethodError
    at ListDemo.createAndShowGUI(ListDemo.java:196)
    at ListDemo.access$400(ListDemo.java:7)
    at ListDemo$1.run(ListDemo.java:217)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Yet when I load up the same file into Netbeans, it compiles and runs fine! Here is the file:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    /* ListDemo.java is a 1.4 application that requires no other files. */
    public class ListDemo extends JPanel
                          implements ListSelectionListener {
        private JList list;
        private DefaultListModel listModel;
        private static final String hireString = "Hire";
        private static final String fireString = "Fire";
        private JButton fireButton;
        private JTextField employeeName;
        public ListDemo() {
            super(new BorderLayout());
            listModel = new DefaultListModel();
            listModel.addElement("Alan Sommerer");
            listModel.addElement("Alison Huml");
            listModel.addElement("Kathy Walrath");
            listModel.addElement("Lisa Friendly");
            listModel.addElement("Mary Campione");
            listModel.addElement("Sharon Zakhour");
            //Create the list and put it in a scroll pane.
            list = new JList(listModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.addListSelectionListener(this);
            list.setVisibleRowCount(5);
            JScrollPane listScrollPane = new JScrollPane(list);
            JButton hireButton = new JButton(hireString);
            HireListener hireListener = new HireListener(hireButton);
            hireButton.setActionCommand(hireString);
            hireButton.addActionListener(hireListener);
            hireButton.setEnabled(false);
            fireButton = new JButton(fireString);
            fireButton.setActionCommand(fireString);
            fireButton.addActionListener(new FireListener());
            employeeName = new JTextField(10);
            employeeName.addActionListener(hireListener);
            employeeName.getDocument().addDocumentListener(hireListener);
            String name = listModel.getElementAt(
                                  list.getSelectedIndex()).toString();
            //Create a panel that uses BoxLayout.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane,
                                               BoxLayout.LINE_AXIS));
            buttonPane.add(fireButton);
            buttonPane.add(Box.createHorizontalStrut(5));
            buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
            buttonPane.add(Box.createHorizontalStrut(5));
            buttonPane.add(employeeName);
            buttonPane.add(hireButton);
            buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            add(listScrollPane, BorderLayout.CENTER);
            add(buttonPane, BorderLayout.PAGE_END);
        class FireListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //This method can be called only if
                //there's a valid selection
                //so go ahead and remove whatever's selected.
                int index = list.getSelectedIndex();
                listModel.remove(index);
                int size = listModel.getSize();
                if (size == 0) { //Nobody's left, disable firing.
                    fireButton.setEnabled(false);
                } else { //Select an index.
                    if (index == listModel.getSize()) {
                        //removed item in last position
                        index--;
                    list.setSelectedIndex(index);
                    list.ensureIndexIsVisible(index);
        //This listener is shared by the text field and the hire button.
        class HireListener implements ActionListener, DocumentListener {
            private boolean alreadyEnabled = false;
            private JButton button;
            public HireListener(JButton button) {
                this.button = button;
            //Required by ActionListener.
            public void actionPerformed(ActionEvent e) {
                String name = employeeName.getText();
                //User didn't type in a unique name...
                if (name.equals("") || alreadyInList(name)) {
                    Toolkit.getDefaultToolkit().beep();
                    employeeName.requestFocusInWindow();
                    employeeName.selectAll();
                    return;
                int index = list.getSelectedIndex(); //get selected index
                if (index == -1) { //no selection, so insert at beginning
                    index = 0;
                } else {           //add after the selected item
                    index++;
                listModel.insertElementAt(employeeName.getText(), index);
                //If we just wanted to add to the end, we'd do this:
                //listModel.addElement(employeeName.getText());
                //Reset the text field.
                employeeName.requestFocusInWindow();
                employeeName.setText("");
                //Select the new item and make it visible.
                list.setSelectedIndex(index);
                list.ensureIndexIsVisible(index);
            //This method tests for string equality. You could certainly
            //get more sophisticated about the algorithm.  For example,
            //you might want to ignore white space and capitalization.
            protected boolean alreadyInList(String name) {
                return listModel.contains(name);
            //Required by DocumentListener.
            public void insertUpdate(DocumentEvent e) {
                enableButton();
            //Required by DocumentListener.
            public void removeUpdate(DocumentEvent e) {
                handleEmptyTextField(e);
            //Required by DocumentListener.
            public void changedUpdate(DocumentEvent e) {
                if (!handleEmptyTextField(e)) {
                    enableButton();
            private void enableButton() {
                if (!alreadyEnabled) {
                    button.setEnabled(true);
            private boolean handleEmptyTextField(DocumentEvent e) {
                if (e.getDocument().getLength() <= 0) {
                    button.setEnabled(false);
                    alreadyEnabled = false;
                    return true;
                return false;
        //This method is required by ListSelectionListener.
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (list.getSelectedIndex() == -1) {
                //No selection, disable fire button.
                    fireButton.setEnabled(false);
                } else {
                //Selection, enable the fire button.
                    fireButton.setEnabled(true);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("ListDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ListDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();

    You are not running this code under JDK 1.4
    The setDefaultLookAndFeelDecorated method requires JDK 1.4 version.

  • MC container causes this code to fail...why ?

    Hi
    Flash CS5 as3
    We have settlements named with suffix _Level2 such as e.g. Mitre'sGate_Level2 as well as _Level3 as MovieClips that are in a container MovieClip called Map_Collection.
    The code below fails with the error shown if the code line shown in bold is used, it works with:-
    var clipName :String = String(e.item[s]).replace(r,"")+currentLevel;             if the settlements are placed directly on stage.
    The code identifies _Level2 or Level3 at end of button name e.g. DistrictA_Level2 and appends it to the dataGrid output on the MouseHover.
    What should the code read to resolve this problem that we have poured heart and soul into for 2 hours ?
    Error is:-
    Map_Collection.Mitre'sGate_Level2
    TypeError: Error #1010: A term is undefined and has no properties.
    at BusMap_fla::MainTimeline/ShowSymbols()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at fl.controls::SelectableList/handleCellRendererMouseEvent()
    at fl.controls::DataGrid/handleCellRendererMouseEvent()
    Code is:-
    dg.addEventListener(ListEvent.ITEM_ROLL_OVER,ShowSymbols);
    function ShowSymbols(e:ListEvent):void{
    makeAllVisibleF(false);
    var r:RegExp = /\W/g;
    for(var s:String in e.item){
    //trace(currentLevel)
    if(e.item[s]){
    var clipName :String = String(e.item[s]).replace(r,"")+currentLevel;
    trace(clipName)
    this[clipName].visible=true;
    trace(s,e.item[s])
    function makeAllVisibleF(b:Boolean):void{
    Mitre'sGate_Level2.visible=b;
    UpperDowning_Level2.visible=b
    //Map_Collection.Tamar Brook_Level3.visible=b;
    Map_Collection.Mitre'sGate_Level2.visible=b;
    This code works on sttmnts directly on stage.
    I show here an extract of the code visible=b; that follows it. we have such for every sttmnt. The first two lines are for those not in the MC container.
    if we use:-
    var clipName :String = "Map_Collection."+String(e.item[s]).replace(r,"")+currentLevel;
    which is our best stab after trying various options, it fails with error above.
    My compatriot says, in code !!!  
    // This is what we want
    Map_Collection.Mitre'sGate_Level2.visible=true
    //This doesn’t work
    Map_Collection.this[clipName].visible=true
    //This works, when Mitre'sGate_Level2 is placed on the stage
    Mitre'sGate_Level2.visible=true
    //Placing Mitre'sGate_Level2 in movie clip Map_Collection How do we get it to work
    We tried a variety of  options, even replacing 'this' with Map_Collection.., my best stab,  just what should the code be ?
    Envirographics

    Hi,
    Not sure of that, (also now have edited csv to no gaps or apostrphes, still it fails) ...because the code I posted is the code we are successfully running in a test file where there is a dataGrid fed a csv with such as Mitre's Gate Collet's Reach etc.  This code removes the  apostrophes and gaps when user hovers datagrid, MC's spelt MitresGate etc are identified and appear, then hide again when another row is hovered. Note also as said, Mitre's Gate outside of MC Map_Collection is found and shows.
    The code in this test file (which is 3 columns) is:-
    import flash.net.URLLoader;
    import flash.events.Event;
    import flash.net.URLRequest;
    import fl.data.DataProvider;
    import fl.controls.DataGrid;
    import fl.events.ListEvent
    makeAllVisibleF(false);
    var urlLoader:URLLoader = new URLLoader();
    urlLoader.addEventListener(Event.COMPLETE,completeF);
    urlLoader.load(new URLRequest("NamesWithNullCellsGapsApostrophes.csv"));
    var dg:DataGrid
    function completeF(e:Event):void{
        var dataS:String = e.target.data;
        var dataA:Array = dataS.split("\n").join("").split("\r");
        var dpA:Array = [];
        var itemA:Array;
    var r:RegExp = /\W/g;
        for(var i:int=0;i<dataA.length;i++){
            itemA = dataA[i].split(",");
             dpA.push({"col1":itemA[0],"col2":itemA[1],"col3":itemA[2]});
    var dp:DataProvider = new DataProvider(dpA);
        dg.columns = ["col1","col2","col3"]
        dg.dataProvider = dp;
    dg.addEventListener(ListEvent.ITEM_ROLL_OVER,ShowSymbols);
    function ShowSymbols(e:ListEvent):void{
    makeAllVisibleF(false);
    var r:RegExp = /\W/g;
    for(var s:String in e.item){
    if(e.item[s]){
    var clipName :String = String(e.item[s]).replace(r,"");
    this[clipName].visible=true;
    trace(s,e.item[s])
    function makeAllVisibleF(b:Boolean):void{
    We have introduced to that the code by Kglad, or so we hope, that appends to the output from OnHover  _Level2 or _Level3 depending on which District button is clicked on, DistrictA_Level2 or DistrictA_Level3.
    Just to recap/describe what we are aiming at, a map has 6 districts, user clicks District A button named in instance DistrictA_Level 2and is taken to that District, a dataGrid appears and when user hovers a row, the settlements for that layer of the map, e.g. Mitre's Gate_Layer2  appear. csv just has Mitre's Gate. user clicks on DistrictA_Level3 button and hover will show Mitre's Gate_L
     evel3 symbol. 
    Kglad code:-
    var currentLevel:String="_Level2";
    dg.addEventListener(ListEvent.ITEM_ROLL_OVER,ShowSymbols);
    function ShowSymbols(e:ListEvent):void{
    makeAllVisibleF(false);
    var r:RegExp = /\W/g;
    for(var s:String in e.item){
    if(e.item[s]){
    var clipName :String = String(e.item[s]).replace(r,"")+currentLevel;
    this[clipName].visible=true;
    trace(s,e.item[s])
    and when asked how one gets the Level2 into that var when user clicks on e.g. DistrictA_Level2
    we now have, for the 12 buttons we have named, reply from Kglad
     :-• DistrictA_Level2.addEventListener(MouseEvent.CLICK, clickF);
    DistrictB_Level2.addEventListener(MouseEvent.CLICK, clickF);
    DistrictF_Level2.addEventListener(MouseEvent.CLICK, clickF);
    DistrictA_Level3.addEventListener(MouseEvent.CLICK, clickF);
    DistrictB_Level3.addEventListener(MouseEvent.CLICK, clickF);
    DistrictF_Level3.addEventListener(MouseEvent.CLICK, clickF);
    var currentLevel:String;
    function clickF(e:MouseEvent):void{
    currentLevel="_"+e.currentTarnget.name.split("_")[1];
    for the moment we are focusing on getting it operational on just button DistrictA_Level2
    As said works fine if MC Mitre's Gate sits on stage, so the apostrophy and gap stripping is working as is the appending of the wording after and including the _ from the District button !  Place the settlement MC into Map_Collection MC and it fails.
    Envirographics

  • Remove tax code in billing document

    Hi
       In sales billing, accounting entries for  account key ERL is as below
    PK Account    Account short text   Tx
    01 10000001   Customer                  A0
    50 40001001   Gross Sales - Trade  A0
    The requirement is to remove tax code (A0) from posting in customer account (10000001 ) i.e. it should look like below
    PK Account    Account short text   Tx
    01 10000001   Customer                 
    50 40001001   Gross Sales - Trade  A0
    I could not find any standard solution to this. Can you please suggest what will be best way to achieve this without impacting other processes.
    Thanks in advance.

    Hi,
    1. Kindly make the tax code field 'Suppressed' at the customer's account group level to avoid having tax code getting filled in customer line items.
    2. Using &sap_edit at table level, kindly remove the value of tax code from the customer line item. This will not have any impact as the tax amount are relevant for GL line items and it is more important to populate this information for GL line items.
    3. You can also opt for a substitution rule based on the business requirement.
    BR, D'nesh

  • Whath is wrong with this code???

    Whath is wrong with this code:
    import java.sql.*;
    class DataBaseConnexion
    Connection connexion;
    String url;
    DataBaseConnexion()
    {// 1-charger le driver JDBC-ODBC
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("chargement du driver r�ussi");
    catch(ClassNotFoundException exc) {
    System.out.println("Erreur de chargement du pilote !");
    }// d�finir le pseudo URL pour joindre la BD
    url = "jdbc:odbc:cdi";//2- se connecter � la base de donn�es
    try {
    connexion = DriverManager.getConnection(url, "user_name", "pass_word");
    System.out.println("connexion r�ussie");
    catch(SQLException exc){
    System.out.println("Erreur 1 ! - " + exc.toString());
    public static void main(String Arg[])
    DataBaseConnexion db = new DataBaseConnexion();
    }//this errors occure
    File "C:\Documents and Settings\Administrateur\Bureau\DataBaseConnexion.java" Line 40: Syntax Error
    ---------------- JDK Release Build ------------------
    Compiling C:\Documents and Settings\Administrateur\Bureau\DataBaseConnexion.java
    C:\Documents and Settings\Administrateur\Bureau\DataBaseConnexion.java:40: 'class' or 'interface' expected
    public static void main(String Arg[])
    ^
    C:\Documents and Settings\Administrateur\Bureau\DataBaseConnexion.java:45: 'class' or 'interface' expected
    ^
    C:\Documents and Settings\Administrateur\Bureau\DataBaseConnexion.java:47: 'class' or 'interface' expected
    ^
    3 errors
    Finished

    I think you should remove the last closing curly brackets two lines above the main method.
    Regards

  • How to optimize the performance of this code ?

    I've two Movie clips on a flash project. One of them is fixed and the other can be moved by arrow buttons on the keyboard. The two Movie clips have irregular shapes, so HitTestObject and HitTestPoint doesn't work very well. I've a function that detects collision of two movie clips using bitmap. I wanted to update the position of the movable Movie clip so I put the collision detection function under the code of ENTER_FRAME event listener. It works very well, but when I add many fixed movie clips  ( about 10 fixed movie clips in one frame ), the game (.swf file) becomes slower and the performance of the PC becomes slower. I thought that my collision detection function has a negative effect on PC performance so I used the class on this page : https://forums.adobe.com/thread/873737
    but the same thing happens.
    Would you tell me how to speed up the execution of my codes ?
    Here is part of my code :
    stage.addEventListener(Event.ENTER_FRAME, myOnEnterFrame);
    function myOnEnterFrame(event:Event):void
      if (doThisFn) // doThisFn is a variable to allow or prevent the movable movie clip form being moved with keyboard arrows
      if ( left && !right ) {
      player.x -= speed;
      player.rotation = player.rotation - speed ;
      if( right && !left ) {
      player.x += speed;
      player.rotation = player.rotation + speed ;
    if( up && !down ) {
      player.y -= speed;
    if( down && !up ) {
      player.y += speed;
    // The fixed movie clips are wall1 ,wall2 , wall3 , wall4 , ... and so on
    // the following code checks how many walls exists on each frame and pushes them into the wallA  array
      for(var i:int=0;i<1000;i++) // We can put up to 1000 wall object into the wallA array
      if(this['wall'+i]) // If the object wall exists, push it into the wallA array
      wallA.push(this['wall'+i]);
      for(i=0;i<wallA.length;i++)
      if( h.hitF (player , wallA[i] ) || gameOverTest ) // This code checks if the player ( the movable movie clip ) hits the walls or not
      trace ( "second try" ) ;
      gameOver.visible = true ;
      doThisFn = false ;
    //I think the following codes are easy to excite and run. I think the performance issue is due to previous codes.
      if (player.hitTestObject(door))
      win.visible = true ;
      doThisFn = false ;
      if (key) // if there is a key on frame
      if (player.hitTestObject(key))
      key.visible = false ;
      switch( currentFrame )
      case 4:
      wallA[0].visible = false ;
      wallA[0].x = 50000;
      break;
      case 5:
      wall14.play();
      wall8.x = 430 ;
      break;

    it's a simple question that usually has no simple answer.
    here's an excerpt from a book (Flash Game Development: In a Social, Mobile and 3D World)  i wrote.
    Optimization Techniques
    Unfortunately, I know of no completely satisfactory way to organize this information. In what follows, I discuss memory management first with sub-topics listed in alphabetical order. Then I discuss CPU/GPU management with sub-topics listed in alphabetical order.
    That may seem logical but there are, at least, two problems with that organization.
    1. I do not believe it is the most helpful way to organize this information.
    2. Memory management affects CPU/GPU usage, so everything in the Memory Management section could also be listed in the CPU/GPU section.
    Anyway, I am going to also list the information two other ways, from easiest to hardest to implement and from greatest to least benefit.
    Both of those later listings are subjective and are dependent on developer experience and capabilities, as well as, the test situation and test environment. I very much doubt there would be a consensus on ordering of these lists.  Nevertheless, I think they still are worthwhile.
    Easiest to Hardest to Implement
    1.  Do not use Filters.
    2.  Always use reverse for-loops and avoid do-loops and avoid while-loops.
    3.  Explicitly stop Timers to ready them for gc (garbage collection).
    4.  Use weak event listeners and remove listeners.
    5.  Strictly type variables whenever possible.
    6.  Explicitly disable mouse interactivity when mouse interactivity not needed.
    7.  Replace dispatchEvents with callback functions whenever possible.
    8.  Stop Sounds to enable Sounds and SoundChannels to be gc'd.
    9.  Use the most basic DisplayObject needed.
    10. Always use cacheAsBitmap and cacheAsBitmapMatrix with air apps (i.e., mobile devices).
    11. Reuse Objects whenever possible.
    12. Event.ENTER_FRAME loops: Use different listeners and different listener functions applied to as few DisplayObjects as possible.
    13. Pool Objects instead of creating and gc'ing Objects.
    14. Use partial blitting.
    15. Use stage blitting.
    16. Use Stage3D
    Greatest to Least Benefit
    Use stage blitting (if there is enough system memory).
    Use Stage3D.
    Use partial blitting.
    Use cacheAsBitmap and cacheAsBitmapMatrix with mobile devices.
    Explicitly disable mouse interactivity when mouse interactivity not needed.
    Do not use Filters.
    Use the most basic DisplayObject needed.
    Reuse Objects whenever possible.
    Event.ENTER_FRAME loops: Use different listeners and different listener functions applied to as few DisplayObjects as possible.
    Use reverse for-loops and avoid do-loops and while-loops.
    Pool Objects instead of creating and gc'ing Objects.
    Strictly type variables whenever possible.
    Use weak event listeners and remove listeners.
    Replace dispatchEvents with callback functions whenever possible.
    Explicitly stop Timers to ready for gc.
      16. Stop Sounds to enable Sounds and SoundChannels to be gc'd.

  • How to optimize this code + is design proper

    Well I have to implement tree programming here , what i mean by tree
    programming is i have data stored in tree format i,e I have parent
    object which will have child objects of same type the level of depth can
    go any long:
    I am able to store objects in tree format and also able to display properly Here
    is code but I am facing problems when i have to filter some child nodes based on some conditions:
    I have two question is this code fine is there anything wrong with desin Plus how to handle removing child node in tree scenation where child can be in any place.Below is code
    package menu;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import com.chartis.gp.support.util.BrokerSupportUtil;
    import com.chartis.gp.support.vo.Links;
    import com.chartis.kernel.user.UserVO;
    import com.chartis.kernel.utils.Utils;
    public class Utility{
         /* IN this class NavModel,CModel,CNode are some dummy classes
          * which help us read contents form some resources which are stored in dummy format
          * as Example of tree format stored data below is the example
          *    tree
          *       child1
          *       child2
          *       child3
          *              child3-1
          *                       child:q
          *                       child:r
          *                               child:a
          *              child3-2
          *       child4
         private static void populateChildLinks(NavModel navModel, Object objectNode, Links parent ){
              try{
                   List<Links> childLinks = new ArrayList<Links>();
                   Iterator it = navModel.getChildren( objectNode );
                   while( it.hasNext() ){
                        NavNode node = (NavNode) it.next();
                        CNode contentNode = node.getContentNode();
                        Links links = new Links();
                        links.setNodeName( contentNode.getNodeName() );
                        childLinks.add( links );
                        if( navModel.hasChildren( node ) ){
                             populateChildLinks( node, links );
                   parent.setChildren( childLinks );
              catch( Exception e ){
         private static Links createCategoryLinks(String categoryLinkName){
              Links categoryLinks = new Links();
              categoryLinks.setNodeName( categoryLinkName );
              return categoryLinks;
         public static Links setupLinks(String categoryLinkName,String name) {
              Links categoryLinks=null;
              CModel contentModel = new CModel();
              NavModel navModel = new NavModel();
              categoryLinks = Utility.createCategoryLinks( categoryLinkName);
              Object objectNode = contentModel.getLocator().findByUniqueName(name);
              if( objectNode != null ){
                   if( navModel.hasChildren( objectNode ) ){
                        populateChildLinks( navModel,objectNode, categoryLinks );
                  // This is where i am facing issue once i get list of links of childs
              // i have to delete how can i find that particular child in the list
              // do i have to iterate through all the links and delete or  which
              // way is better
         private static void filterLinks( Links parentNode,
                   List<Links> childNodeList ){
              List<Links> filteredResourceList = new ArrayList<Links>();
              if(  childNodeList!=null ){
                   Iterator<Links> childNodeIt = childNodeList.iterator();
                   while( childNodeIt.hasNext() ){
                        Links childNode = (Links) childNodeIt.next();
                        if(childNode.getChildren().size() >0 ){
                           filterLinks( childNode, childNode.getChildren() );
                        boolean removeNode = filterContents( childNode);
                        if(! removeNode ){
                             filteredResourceList.add( childNode );
              Iterator<Links> filteredResourceIt = filteredResourceList.iterator();
              while( filteredResourceIt.hasNext() ){
                   Links childNode = (Links) filteredResourceIt.next();
                   parentNode.getChildren().remove( childNode );
         // Let us consider this as some dummy method which returns true or false based on some conditions
         private static boolean filterContents( menu.Links childNode ){
              return false;
      package menu;
    import java.util.List;
    public class Links{
          private String nodeName;
         private List<Links> children;
         public List<Links> getChildren(){
              return children;
         public void setChildren( List<Links> children ){
              this.children = children;
         public String getNodeName(){
              return nodeName;
         public void setNodeName( String nodeName ){
              this.nodeName = nodeName;
    package menu;
    public class TreeDisplay{
         public static void main( String[] args ){
          Links link = Utility.setupLinks( "SomeName", "ResiyrbceBane");
           Utility.filterLinks( link, link.getChildren() );
    }Is the utility class with so many static class is ok?

    Vicky wrote:
    Thanks TPD
    If you could write more on it , it will be great i rarely find ocasations of using interfaces , however i don't think creating a new tree with valid node could be better solution as you have to create a new tree keeping the same hierarchy .The advantage is that all other components do not need to know that they work with a filtered tree.
    Certainly you can do it the other way around bye passing the tree and the filter to eg. the <tt>NotePrinter</tt> Object, but than all components working with the tree meight neet to know that ther are Node filters.
    I just came up with the Idea to give the nodes themselfes knowlege of the Filter via <tt>setFilter(Filter<Links> myFilter)</tt>. You would call this on the root node and in the <tt>getChildren()</tt> method you would check if the child apllies to the filter and pass that filter to the eliable childs before putting them into a new collection which is returned to the caller. Ofcause you should initialise the <tt>this.filter</tt> property in <tt>Links</tt> with a <tt>ALL_NODES</tt> constant.
    Also you should resist the tamptation to make the <tt>this.filter</tt> property in <tt>Links</tt> static. This would save you one line of code in the <tt>getCildren()</tt> method by the cost that you cannot have different trees with different filters in the same JVM.
    This kind of interference between threads is pretty hard to find later in production environments...
    bye
    TPD

Maybe you are looking for

  • How to setup the local testing server ??

    hello, what do I need to install first before I can setup the testing server in dreamweaver 8? I have download apache2 triad, mySQL, IIS 6... Where should I download the correct version of mySQL because I need to test my php scripts locally which has

  • Error in message mapping

    I used MT_PerformRate for both sender side and receiver side in message mapping When I goto interface mapping and click on the mapping program it gives following error. The source or target structure has been changed or could not be found in the Inte

  • Pass parameter with apostrophe

    Hi, How I can pass parameter with apostrophe to a store procedure.Whats the change i need to make to ' when i am passing. Thanks in advance. Pramod

  • Basic interview questions in abap ddic

    can any one pls give me the link for basic ddic interview questions

  • Read Image XMP Metadata

    Hi All, Hope I'm not spamming  this thread to your mailbox as I felt this question asked in unrelated  forum. Question: Can we read image meta data from Flex ? I tried it with xmp core library and passed a jpeg file to xmpMeta object : private functi