Display tree in applet

i have a program to convert Xml to tree structure. But i am not able to call it in JSP. So i want to convert to applet. how to convert it.
package TreeGen;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
// Basic GUI components
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
// GUI components for right-hand side
import javax.swing.JSplitPane;
import javax.swing.JEditorPane;
// GUI support classes
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
// For creating borders
import javax.swing.border.EmptyBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
// For creating a TreeModel
import javax.swing.tree.*;
import javax.swing.event.*;
import java.util.*;
import java.applet.*;
public class TreeGen extends JPanel
     static Document document;
     boolean compress = false;
     static final int windowHeight = 660;
     static final int leftWidth = 300;
     static final int rightWidth = 640;
     static final int windowWidth = leftWidth + rightWidth;
     public TreeGen()
     EmptyBorder eb = new EmptyBorder(5,5,5,5);
     BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
     CompoundBorder cb = new CompoundBorder(eb,bb);
     this.setBorder(new CompoundBorder(cb,eb));
     JTree tree = new JTree(new DomToTreeModelAdapter());
     JScrollPane treeView = new JScrollPane(tree);
     treeView.setPreferredSize(
          new Dimension( leftWidth, windowHeight ));
     final
     JEditorPane htmlPane = new JEditorPane("text/html","");
     htmlPane.setEditable(true);
     JScrollPane htmlView = new JScrollPane(htmlPane);
     htmlView.setPreferredSize(
          new Dimension( rightWidth, windowHeight ));
     tree.addTreeSelectionListener(
          new TreeSelectionListener()
          public void valueChanged(TreeSelectionEvent e)
               TreePath p = e.getNewLeadSelectionPath();
               if (p != null)
               AdapterNode adpNode =
                    (AdapterNode) p.getLastPathComponent();
               htmlPane.setText(adpNode.content());
     JSplitPane splitPane =
          new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                              treeView,
                              htmlView );
     splitPane.setContinuousLayout( false );
     splitPane.setDividerLocation( leftWidth );
     splitPane.setDividerSize(1);
     splitPane.setPreferredSize(
               new Dimension( windowWidth + 10, windowHeight+10 ));
     this.setLayout(new BorderLayout());
     this.add("Center", splitPane );
     //return menuBar;
     } // constructor
     public static void main(String argv[])
          DocumentBuilderFactory factory =
               DocumentBuilderFactory.newInstance();
          try {
          DocumentBuilder builder = factory.newDocumentBuilder();
          document = builder.parse("C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/parser1/sample.xml");
               makeFrame();
          } catch (SAXException sxe){
               System.out.println("ERROR");
          Exception x = sxe;
          if (sxe.getException() != null)
               x = sxe.getException();
          x.printStackTrace();
          } catch (ParserConfigurationException pce) {
               pce.printStackTrace();
          } catch (IOException ioe) {
          ioe.printStackTrace();
     } // main
     public static void makeFrame()
          //JApplet app = new JApplet();
          //app.add
          JFrame frame = new JFrame("DOM Echo");
          frame.addWindowListener(
          new WindowAdapter() {
               public void windowClosing(WindowEvent e) {System.exit(0);}
          final TreeGen echoPanel =
          new TreeGen();
          frame.getContentPane().add("Center", echoPanel );
          frame.pack();
          Dimension screenSize =
          Toolkit.getDefaultToolkit().getScreenSize();
          int w = windowWidth + 10;
          int h = windowHeight + 10;
          //TreeGen tg = new TreeGen();
          //MenuDemo demo = new MenuDemo();
          //frame.setJMenuBar(demo.createMenuBar());
          //frame.setContentPane(demo.createContentPane());
          //Display the window.
          frame.setSize(w, h);
          frame.setVisible(true);
     } // makeFrame
     static final String[] typeName = {
          "none",
          "Element",
          "Attr",
          "Text",
          "CDATA",
          "EntityRef",
          "Entity",
          "ProcInstr",
          "Comment",
          "Document",
          "DocType",
          "DocFragment",
          "Notation",
     static final int ELEMENT_TYPE = 1;
     static final int ATTR_TYPE = 2;
     static final int TEXT_TYPE = 3;
     static final int CDATA_TYPE = 4;
     static final int ENTITYREF_TYPE = 5;
     static final int ENTITY_TYPE = 6;
     static final int PROCINSTR_TYPE = 7;
     static final int COMMENT_TYPE = 8;
     static final int DOCUMENT_TYPE = 9;
     static final int DOCTYPE_TYPE = 10;
     static final int DOCFRAG_TYPE = 11;
     static final int NOTATION_TYPE = 12;
static String[] treeElementNames = {
          "slideshow",
          "slide",
          "title", // For slideshow #1
          "slide-title", // For slideshow #10
          "item",
     boolean treeElement(String elementName) {
     for (int i=0; i<treeElementNames.length; i++) {
          //System.out.println(treeElementNames);
          if ( elementName.equals(treeElementNames[i]) )
          return true;
     return false;
     public class AdapterNode
     org.w3c.dom.Node domNode;
     public AdapterNode(org.w3c.dom.Node node)
          domNode = node;
     public String toString()
          String s = typeName[domNode.getNodeType()];
          String nodeName = domNode.getNodeName();
          if (! nodeName.startsWith("#"))
          s += ": " + nodeName;
          if (compress)
          String t = content().trim();
          int x = t.indexOf("\n");
          if (x >= 0) t = t.substring(0, x);
          s += " " + t;
          return s;
          if (domNode.getNodeValue() != null)
          if (s.startsWith("ProcInstr"))
               s += ", ";
          else
               s += ": ";
          // Trim the value to get rid of NL's at the front
          String t = domNode.getNodeValue().trim();
          int x = t.indexOf("\n");
          if (x >= 0) t = t.substring(0, x);
          s += t;
          return s;
     public String content()
          String s = "";
          org.w3c.dom.NodeList nodeList = domNode.getChildNodes();
          for (int i=0; i<nodeList.getLength(); i++)
          org.w3c.dom.Node node = nodeList.item(i);
          int type = node.getNodeType();
          //System.out.println(type);
          AdapterNode adpNode = new AdapterNode(node); //inefficient, but works
          if (type == ELEMENT_TYPE)
               if ( treeElement(node.getNodeName()) ) continue;
               s += "<" + node.getNodeName() + ">";
               s += adpNode.content();
               s += "</" + node.getNodeName() + ">";
          else if (type == TEXT_TYPE)
               s += node.getNodeValue();
          else if (type == ENTITYREF_TYPE)
               s += adpNode.content();
          else if (type == CDATA_TYPE)
               StringBuffer sb = new StringBuffer( node.getNodeValue() );
               for (int j=0; j<sb.length(); j++)
               if (sb.charAt(j) == '<')
                    sb.setCharAt(j, '&');
                    sb.insert(j+1, "lt;");
                    j += 3;
               else if (sb.charAt(j) == '&')
                    sb.setCharAt(j, '&');
                    sb.insert(j+1, "amp;");
                    j += 4;
               s += "<pre>" + sb + "\n</pre>";
          return s;
     public int index(AdapterNode child)
          int count = childCount();
          for (int i=0; i<count; i++)
          AdapterNode n = this.child(i);
          if (child.domNode == n.domNode) return i;
          return -1; // Should never get here.
     public AdapterNode child(int searchIndex)
          org.w3c.dom.Node node =
               domNode.getChildNodes().item(searchIndex);
          if (compress)
          int elementNodeIndex = 0;
          for (int i=0; i<domNode.getChildNodes().getLength(); i++)
               node = domNode.getChildNodes().item(i);
               if (node.getNodeType() == ELEMENT_TYPE
               && treeElement( node.getNodeName() )
               && elementNodeIndex++ == searchIndex)
               break;
          return new AdapterNode(node);
     public int childCount()
          if (!compress)
          return domNode.getChildNodes().getLength();
          int count = 0;
          for (int i=0; i<domNode.getChildNodes().getLength(); i++)
          org.w3c.dom.Node node = domNode.getChildNodes().item(i);
          if (node.getNodeType() == ELEMENT_TYPE
          && treeElement( node.getNodeName() ))
               ++count;
          return count;
     public class DomToTreeModelAdapter
     implements javax.swing.tree.TreeModel
     public Object getRoot()
          return new AdapterNode(document);
     public boolean isLeaf(Object aNode)
          AdapterNode node = (AdapterNode) aNode;
          if (node.childCount() > 0) return false;
          return true;
     public int getChildCount(Object parent)
          AdapterNode node = (AdapterNode) parent;
          return node.childCount();
     public Object getChild(Object parent, int index)
          AdapterNode node = (AdapterNode) parent;
          return node.child(index);
     public int getIndexOfChild(Object parent, Object child)
          AdapterNode node = (AdapterNode) parent;
          return node.index((AdapterNode) child);
     public void valueForPathChanged(TreePath path, Object newValue)
     private Vector listenerList = new Vector();
     public void addTreeModelListener(TreeModelListener listener)
          if ( listener != null
          && ! listenerList.contains( listener ) )
          listenerList.addElement( listener );
     public void removeTreeModelListener(TreeModelListener listener)
          if ( listener != null )
          listenerList.removeElement( listener );
     public void fireTreeNodesChanged( TreeModelEvent e )
          Enumeration listeners = listenerList.elements();
          while ( listeners.hasMoreElements() )
          TreeModelListener listener =
               (TreeModelListener) listeners.nextElement();
          listener.treeNodesChanged( e );
     public void fireTreeNodesInserted( TreeModelEvent e )
          Enumeration listeners = listenerList.elements();
          while ( listeners.hasMoreElements() )
          TreeModelListener listener =
               (TreeModelListener) listeners.nextElement();
          listener.treeNodesInserted( e );
     public void fireTreeNodesRemoved( TreeModelEvent e )
          Enumeration listeners = listenerList.elements();
          while ( listeners.hasMoreElements() )
          TreeModelListener listener =
               (TreeModelListener) listeners.nextElement();
          listener.treeNodesRemoved( e );
     public void fireTreeStructureChanged( TreeModelEvent e )
          Enumeration listeners = listenerList.elements();
          while ( listeners.hasMoreElements() )
          TreeModelListener listener =
               (TreeModelListener) listeners.nextElement();
          listener.treeStructureChanged( e );
pls help.
ramya

There's already some applet code in there, although it's commented out. Did you add that?
Anyway, the general principle for turning an app into an applet, is to replace the main() method with the Applet's (or JApplet's) init(), start(), and stop() methods. Also you won't be able to read data off the file system; use resources instead. (e.g., java.lang.Class.getResource)
I'm not sure what this has to do with JSP.
When you post code, please wrap it in &#91;code]&#91;/code] tags.

Similar Messages

  • Display .gif In Applet Problem

    I have been making a game. Very simply, the game has a main class and another truely important class that extends JFrame, it is the map. In it i need to upload .gif files and display them. It worked up until recently because i needed to make a sepperate class. I know how to use the getImage() for Images and the the way for ImageIcons, but for some reason, they never display (they display just whiteness). My Code is as follows
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import java.io.*;
    // when this puppy reads from a file, it'll be able to have 55 15 x 15 terrains per row
    // 35 15 x 15 terrains per column
    // arrows by everythign that u would need to consider in finding the problem
    // this is not the main class
    public class GameMap extends JPanel implements MouseListener, MouseMotionListener, KeyListener{
         public static final int MAX_BULLETS = 200;
         public static final int MAX_PLAYERS = 50;
         public static final int SPLAT_SIZE = 15;
         public static final int PLAYER_SIZE = 15;
         public static final int MAX_MESSAGES = 10;
         public static final int ROBOT_SIZE = 15;
         private static final int rowTerrains = 35;
         private static final int columnTerrains = 55;
         private static int currentBullets = 0;
         private static int currentPlayers = 0;
         private static int bulletRotation = 0;
         private static int aimX, aimY;
         private boolean mapLoaded;
         private boolean writingMessage;
         private boolean imagesLoaded;
         private int messageRotation;
         private int tileCoord;
         private String messageText = "";
         private String currentMap;
        private Bullet bullet[] = new Bullet[MAX_BULLETS];
        private Player player[] = new Player[MAX_PLAYERS];
        private Message message[] = new Message[MAX_MESSAGES];
        private Color backgroundColor = new Color(81, 141, 23);
        private Image offscreenMap; // offscreen image of map
        private Graphics mapGraphics;
         private ImageIcon yellowSplat1, yellowSplat2, yellowSplat3, yellowSplat4, yellowSplat5, bluePlayerBack, bluePlayerFront, bluePlayerRight, bluePlayerLeft, grass, tree, mountain, robot1;
         private Terrain terrain[] = new Terrain[(rowTerrains * columnTerrains)];
         public GameMap(){
              this(800, 450);
         public GameMap(int width, int height){
              addMouseListener(this);
              addMouseMotionListener(this);
              addKeyListener(this); // use method requestFocusInWindow() for this to work
              setPreferredSize(new Dimension(width, height));
              setBackground(backgroundColor);
              for (int x = 0; x < bullet.length; x++){
                   bullet[x] = new Bullet();
              for (int x = 0; x < player.length; x++){
                   player[x] = new Player();
              for (int x = 0; x < message.length; x++){
                   message[x] = new Message();
              for (int x = 0, currentX = 0, currentY = 0; x < (rowTerrains * columnTerrains); x++){
                   terrain[x] = new Terrain();
                   terrain[x].setX(currentX);
                   terrain[x].setY(currentY);
                   currentX += 15;
                   if (currentX > columnTerrains * 15){
                        currentX = 0;
                        currentY += 15;
              player[0].drawPlayer(0, 0);
              //loadMap("Map1.txt"); // this is called to load the map right when this object is initialized
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              Composite originalComposite = g2d.getComposite();
              if (imagesLoaded == false){
                   yellowSplat1 = new ImageIcon("yellow1.gif");
                   yellowSplat2 = new ImageIcon("yellow2.gif");
                   yellowSplat3 = new ImageIcon("yellow3.gif");
                   yellowSplat4 = new ImageIcon("yellow4.gif");
                   yellowSplat5 = new ImageIcon("yellow5.gif");
                   bluePlayerBack = new ImageIcon("BlueBack.gif");
                   bluePlayerFront = new ImageIcon("BlueFront.gif");
                   bluePlayerLeft = new ImageIcon("BlueLeft.gif");
                   bluePlayerRight = new ImageIcon("BlueRight.gif");
                   grass = new ImageIcon("Grass.gif");
                   tree = new ImageIcon("Tree.gif");
                   mountain = new ImageIcon("Mountain.gif");
                   robot1 = new ImageIcon("Robot1.gif");
              if (mapLoaded == false){ // so a map is loaded when game is started
                   loadMap("Map1.txt");
                   mapLoaded = true;
              g.drawImage(offscreenMap, 0, 0, this);
              for (int x = 0; x < bullet[0].totalBullets; x++){
                   if (bullet[x].getArrived()){
                        //find splat type and display it
                        g2d.setComposite(makeComposite(0.5f));
                        switch (bullet[x].getSplatType()){
                             case 0:
                                  yellowSplat1.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 1:
                                  yellowSplat2.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 2:
                                  yellowSplat3.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 3:
                                  yellowSplat4.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 4:
                                  yellowSplat5.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                   else{
                        g2d.setComposite(originalComposite);
                        g2d.setColor(Color.yellow);
                        g2d.fillOval(bullet[x].getX(), bullet[x].getY(), 3, 3);
              g2d.setComposite(originalComposite);
              g.setColor(Color.yellow);
              for (int x = 0; x < player[0].totalPlayers; x++){
                   if (player[x].getPlayerPosition().equals("Back")){
                        bluePlayerBack.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else if (player[x].getPlayerPosition().equals("Right")){
                        bluePlayerRight.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else if (player[x].getPlayerPosition().equals("Left")){
                        bluePlayerLeft.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else if (player[x].getPlayerPosition().equals("Front")){
                        bluePlayerFront.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else{
                        g2d.fillOval(player[x].getX(), player[x].getY(), 15, 15);
              if (writingMessage){
                   g2d.setColor(new Color(0, 0, 130));
                   g2d.setComposite(makeComposite(0.5f));
                   g2d.draw3DRect(8, 7, 800, 17, true);
                   g2d.setComposite(originalComposite);
                   g2d.setColor(Color.yellow);
                   g2d.drawString(messageText, message[0].getX(), 20);
              for (int x = 0; x < MAX_MESSAGES; x++){
                   if (message[x].isDisplayed()){
                        g2d.drawString(message[x].getMessage(), message[x].getX(), message[x].getY());
         private AlphaComposite makeComposite(float alpha) {
              int type = AlphaComposite.SRC_OVER;
              return(AlphaComposite.getInstance(type, alpha));
         public void drawBullet(int aimX, int aimY){
              bullet[bulletRotation].drawBullet(player[0].getX() + PLAYER_SIZE / 2, player[0].getY() + PLAYER_SIZE / 2, aimX, aimY);
              player[0].setPlayerPosition(bullet[bulletRotation].getPlayerPosition());
              bulletRotation++;
              if (bulletRotation >= MAX_BULLETS){
                   bulletRotation = 0;
         public void loadMap(String map){
              mapLoaded = false;
              currentMap = map;
              try{
                   BufferedReader in = new BufferedReader(new FileReader(map));
                   String input, string1, string2;
                   for (int x = 0; x < terrain.length; x++){
                        terrain[x].setFilled(false);
                   for (int x = 0, currentArray; x < terrain.length; x++){
                        if ((input = in.readLine()) != null) {
                             StringTokenizer st = new StringTokenizer(input);
                             currentArray = Integer.parseInt(st.nextToken());
                             terrain[currentArray].setTerrainType(st.nextToken());
                             terrain[currentArray].setFilled(true);
                        else{
                             break;
                   in.close();
                   offscreenMap = createImage(size().width, size().height);
                   mapGraphics = offscreenMap.getGraphics();
                   //mapGraphics.clearRect(0, 0, size().width, size().height);
                   // everything from here down is to be painted to mapGraphics... but it doesn't get this far cuz of an error
                   for (int x = 0; x < terrain.length; x++){
                        if (terrain[x].getTerrainType().equals("Grass")){
                             grass.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
                             System.out.println("terrain(" + x + ") is Grass");
                        else if (terrain[x].getTerrainType().equals("Tree")){
                             tree.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
                             System.out.println("terrain(" + x + ") is Tree");
                        else if (terrain[x].getTerrainType().equals("Mountain")){
                             mountain.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
                             System.out.println("terrain(" + x + ") is Mountain");
              catch (FileNotFoundException e){
                   System.out.println("Map not found");
              catch (IOException e){
                   System.out.println("IOException Error!");
              // **** mouse Listener ****//
         public void mouseClicked(MouseEvent e){}
         public void mousePressed(MouseEvent e){}
         public void mouseReleased(MouseEvent e){
              if (e.getButton() == 1){
                   //System.out.println("player[0].movePlayer(" + e.getX() + ", " + e.getY() + ")");
                   aimX = e.getX();
                   aimY = e.getY();
                   movePlayer(aimX, aimY);
              else if (e.getButton() == 3){
                   aimX = e.getX();
                   aimY = e.getY();
                   drawBullet(aimX, aimY);
         public void mouseEntered(MouseEvent e){
              if (isFocusOwner() != true){
                   requestFocusInWindow();
         public void mouseExited(MouseEvent e){}
         // **** end mouse listener ****//
         // **** mouse motion listener ****//
         public void mouseDragged(MouseEvent e){}
         public void mouseMoved(MouseEvent e){}
         // **** end mouse motion listener ****/
         public void keyPressed(KeyEvent e){}
         public void keyReleased(KeyEvent e){}
         public void keyTyped(KeyEvent e){}
    }I removed a few unnecessary methods from this code to make it easier to view. EVERYTHING works except for the images displaying. The reason i'm having this problem now is i just redid my workspace and copied the code and i think some glitch stopped it from compiling correctly all along so now i experience this problem in the applet viewer. Though, even before, i couldn't get anything to display in an applet.
    And yes, everything is in the same place as the html file.
    Thanks for your help!

    Here's a way to keep track of and paint images with a simple Rectangle array. And also a way to remove lengthy initialization code blocks from paintComponent. Move the images by moving the rectangles.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class GameMapRx
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new GameMapPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class GameMapPanel extends JPanel
        Image[] images;
        Rectangle[] rects;
        boolean firstTime;
        final int PAD;
        public GameMapPanel()
            loadImages();
            firstTime = true;
            PAD = 20;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            int w = getWidth();
            int h = getHeight();
            if(firstTime)
                initializeGameMap(w, h);
            for(int i = 0; i < rects.length; i++)
                Rectangle r = rects;
    g.drawImage(images[i], r.x, r.y, this);
    g2.draw(r);
    private void loadImages()
    String path = "images/duke/";
    String ext = ".gif";
    images = new Image[10];
    for(int i = 0; i < images.length; i++)
    try
    URL url = getClass().getResource(path + "T" + (i + 1) + ext);
    images[i] = ImageIO.read(url);
    catch(MalformedURLException mue)
    System.out.println("Bad URL: " + mue.getMessage());
    catch(IOException ioe)
    System.out.println("Unable to read: " + ioe.getMessage());
    private void initializeGameMap(int w, int h)
    rects = new Rectangle[images.length];
    int imageWidth = images[0].getWidth(this);
    int imageHeight = images[0].getHeight(this);
    int cols = (w - 2*PAD) / imageWidth;
    int xInc = imageWidth + (w - cols * imageWidth) / (cols + 1);
    int x0 = (w - cols * imageWidth -
    (cols - 1) * ((w - cols * imageWidth) / (cols + 1))) / 2;
    for(int i = 0; i < images.length; i++)
    int x = x0 + xInc * (i % cols);
    int rows = i / cols;
    int y = PAD + (imageHeight + PAD) * rows;
    rects[i] = new Rectangle(x, y, imageWidth, imageHeight);
    firstTime = false;

  • Using getter/setter for returing a string variable to display on an Applet

    have two classes called, class A and class testA.
    class A contains an instance variable called title and one getter & setter method. class A as follow.
    public class A extends Applet implements Runnable, KeyListener
         //Use setter and getter of the instance variable
         private String title;
         public void init()
              ASpriteFactory spriteFactory = ASpriteFactory.getSingleton();
              // Find the size of the screen .
              Dimension theDimension = getSize();
              width = theDimension.width;
              height = theDimension.height;
              //Create new ship
              ship = spriteFactory.createNewShip();
              fwdThruster = spriteFactory.createForwardThruster();
              revThruster = spriteFactory.createReverseThruster();
              ufo = spriteFactory.createUfo();
              missile = spriteFactory.createMissile();
              generateStars();
              generatePhotons();
              generateAsteroids();
              generateExplosions();
              initializeFonts();
              initializeGameData();
              //Example from Instructor
              //setMyControlPanel( new MyControlPanel(this) );
              // new for JDK 1.2.2
              addKeyListener(this);
              requestFocus();
         public void update(Graphics theGraphics)
              // Create the offscreen graphics context, if no good one exists.
              if (offGraphics == null || width != offDimension.width || height != offDimension.height)
                   // This better be the same as when the game was started
                   offDimension = getSize();
                   offImage = createImage(offDimension.width, offDimension.height);
                   offGraphics = offImage.getGraphics();
                   offGraphics.setFont(font);
              displayStars();
              displayPhotons();
              displayMissile();
              displayAsteroids();
              displayUfo();
              //displayShip();
              //Load the game with different color of the space ship          
              displayNewShip();
              displayExplosions();
              displayStatus();
              displayInfoScreen();
              // Copy the off screen buffer to the screen.
              theGraphics.drawImage(offImage, 0, 0, this);
         private void displayInfoScreen()
              String message;
              if (!playing)
                   offGraphics.setColor(Color.white);
                   offGraphics.drawString("\'A\' to Change Font Attribute", 25, 35);
                   offGraphics.drawString(getTitle(), (width - fontMetrics.stringWidth(message)) / 2, height / 2
                             - fontHeight);
                   message = "The Training Mission";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 2);
                   message = "Name of Author";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 2
                             + fontHeight);
                   message = "Original Copyright 1998-1999 by Mike Hall";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 2
                             + (fontHeight * 2));
                   if (!loaded)
                        message = "Loading sounds...";
                        int barWidth = 4 * fontWidth + fontMetrics.stringWidth(message);
                        int barHeight = fontHeight;
                        int startX = (width - barWidth) / 2;
                        int startY = 3 * height / 4 - fontMetrics.getMaxAscent();
                        offGraphics.setColor(Color.black);
                        offGraphics.fillRect(startX, startY, barWidth, barHeight);
                        offGraphics.setColor(Color.gray);
                        if (clipTotal > 0)
                             offGraphics.fillRect(startX, startY, (barWidth * clipsLoaded / clipTotal), barHeight);
                        offGraphics.setColor(Color.white);
                        offGraphics.drawRect(startX, startY, barWidth, barHeight);
                        offGraphics
                                  .drawString(message, startX + 2 * fontWidth, startY + fontMetrics.getMaxAscent());
                   else
                        message = "Game Over";
                        offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 4);
                        message = "'S' to Start";
                        offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 4
                                  + fontHeight);
              else if (paused)
                   offGraphics.setColor(Color.white);
                   message = "Game Paused";
                   offGraphics.drawString(message, (width - fontMetrics.stringWidth(message)) / 2, height / 4);
         public String getTitle() {
              System.out.print(title);
              return title;
         public void setTitle(String title) {
              this.title = title;
    }displayInfoScreen method in class A calls out for getTitle( ) to be displayed on an applet as an initial display string for the application.
    The instance variable title is set by setTitle method which is called out in class testA as follow,
    public class testA extends TestCase
          * testASprite constructor comment.
          * @param name
          *          java.lang.String
         public testA(String name)
              super(name);
          * Insert the method's description here.
          * @param args
          *          java.lang.String[]
         public static void main(String[] args)
              junit.textui.TestRunner.run(suite());
              // need to figure out how to get rid of the frame in this test
              System.exit(0);
         public static Test suite()
              return new TestSuite(testA.class);
          * Basic create and simple checks
         public void testCreate()
              A theGame = new A();
              assertNotNull("game was null!", theGame);
          * Basic create and simple checks
         public void testInit()
              A theGame = new A();
              Frame gameFrame = new Frame("THE GAME");
              gameFrame.add(theGame);
              int width = 640;
              int height = 480;
              gameFrame.setSize(width, height);
              // must pack to get graphics peer
              gameFrame.pack();
              theGame.resize(width, height);
              theGame.setTitle("TEST THE GAME");
              theGame.init();
              assertEquals("ASprite width not set", A.width, width);
              gameFrame.dispose();
              gameFrame.remove(theGame);
    }Basically, class testA invokes the init( ) method in class A and start the applet application. However, it displays a white blank display. If I change the getTitle( ) in the displayInfoScreen method to a fixed string, it works fine. Did I forget anything as far as using getter & setter method? Do I have to specify some type of handle to sync between setter and getter between two classes? Any feedback will be greatly appreciated.
    Thanks.

    Your class A extends runnable which leads me to believe that this is a multi-threaded application. In that case, title may or may not be a shared variable. Who knows? It's impossible to tell from what you posted.
    Anyway, what is happening is that your applet is being painted by the JFrame before setTitle is called. After that, who knows what's happening. It's a complicated application. I suspect that if you called setTitle before you added the applet to the frame, it would work.

  • Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    Hi folks,
    I am using a cascaded mapping in my OM. I have a graphical mapping followed by the Java mapping. It is a flat file to IDOC mapping. Everything works fine in Dev but when I transport the same objects to QA, the Operation mapping though it doesn't fail in ESR testing tool, gives the following message and there is no output generated for the same payload which is successfully tested in DEV. Please advise on what could be the possible reasons.
    Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    kalyan,
    There seems to be an invalid xml payload which causes this error in ESR not generating the tree view. Please find the similar error screenshot and rectify the payload.
    Mutti

  • JavaMapping in PI 7.1 Error:Unable to display tree view; Error when parsing

    hi,
    i get by testing in PI 7.1 (operation mapping) this ERROR:
    "Unable to display tree view; Error when parsing an XML document (Content is not allowed in prolog.)"
    this is my java-programm-code:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import com.sap.aii.mapping.api.StreamTransformation;
    import java.io.*;
    import java.util.Map;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    /*IMPORT statement imports the specified classes and its methods into the program */
    /Every Java mapping program must implement the interface StreamTransformation and its methods execute() and setParameter() and extend the class DefaultHandler./
    public class Mapping extends DefaultHandler implements StreamTransformation {
    Below is the declaration for all the variables we are going to use in the
    subsequent methods.
         private Map map;
         private OutputStream out;
         private boolean input1 = false;
         private boolean input2 = false;
         private int number1;
         private int number2;
         private int addvalue;
         private int mulvalue;
         private int subvalue;
         String lineEnd = System.getProperty("line.separator");
    setParamater() method is used to store the mapping object in the variable
    "map"
         public void setParameter(Map param) {
              map = param;
         public void execute(InputStream in, OutputStream out)
                   throws com.sap.aii.mapping.api.StreamTransformationException {
              DefaultHandler handler = this;
              SAXParserFactory factory = SAXParserFactory.newInstance();
              try {
                   SAXParser saxParser = factory.newSAXParser();
                   this.out = out;
                   saxParser.parse(in, handler);
              } catch (Throwable t) {
                   t.printStackTrace();
    As seen above execute() method has two parameters "in" of type
    InputStream and "out" of type OutputStream. First we get a new instance
    of SAXParserFactory and from this one we create a new Instance of
    SAXParser. To the Parse Method of SaxParser, we pass two parameters,
    inputstream "in" and the class variable "handler".
    Method "write" is a user defined method, which is used to write the
    string "s" to the outpurstream "out".
         private void write(String s) throws SAXException {
              try {
                   out.write(s.getBytes());
                   out.flush();
              } catch (IOException e) {
                   throw new SAXException("I/O error", e);
         public void startDocument() throws SAXException {
              write("");
              write(lineEnd);
              write("");
              write(lineEnd);
         public void endDocument() throws SAXException {
              write("");
              try {
                   out.flush();
              } catch (IOException e) {
                   throw new SAXException("I/O error", e);
         public void startElement(String namespaceURI, String sName, String qName,
                   Attributes attrs) throws SAXException {
              String eName = sName;
              if ("".equals(eName))
                   eName = qName;
              if (eName.equals("NUMBER1"))
                   input1 = true;
              if (eName.equals("NUMBER2"))
                   input2 = true;
         public void endElement(String namespaceURI, String sName, String qName)
                   throws SAXException {
              String eName = sName;
              if ("".equals(eName))
                   eName = qName;
              if (eName.equals("NUMBER1"))
                   input1 = false;
              if (eName.equals("NUMBER2"))
                   input2 = false;
         public void characters(char[] chars, int startIndex, int endIndex)
                   throws SAXException {
              String dataString = new String(chars, startIndex, endIndex).trim();
              if (input1) {
                   try {
                        number1 = Integer.parseInt(dataString);
                   } catch (NumberFormatException nfe) {
              if (input2) {
                   number2 = Integer.parseInt(dataString);
              if (input2 == true) {
                   addvalue = number1 + number2;
                   mulvalue = number1 * number2;
                   subvalue = number1 - number2;
                   write("" + addvalue + "");
                   write(lineEnd);
                   write("" + mulvalue + "");
                   write(lineEnd);
                   write("" + subvalue + "");
                   write(lineEnd);
    in developer studio 7.1 i dont get error.
    this happens by testing the mapping-programm in ESR.
    can somebody help me please?

    Make sure that the xml created out after the java mapping is a valid xml with only one root node.
    Regards,
    Prateek

  • Display tree in JTree

    Hi, I would like to ask you how can I display my Tree? in JTree?
    I create tree:
    Folder fol = new Folder(folderName, numFiles);
    DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(fol);
    ....But now I does not know how to display tree with folder names. When I use tree.setModel(...); it display object, but not folder names...
    And how can I use red font color for folder names with 0 files(numFiles = 0)?

    Hi, I would like to ask you how can I display my
    Tree? in JTree?
    I create tree:
    Folder fol = new Folder(folderName, numFiles);
    DefaultMutableTreeNode treeNode = new
    DefaultMutableTreeNode(fol);
    ....But now I does not know how to display tree with
    folder names. When I use tree.setModel(...); it
    display object, but not folder names...you need to walk through your tree and create a new DefaultMutableTreeNode for each of your nodes and add to its parent node of your JTree (remember there is a distinction between view and control). the user object of your DefaultMutable TreeNodes is the file/folder, which should be in its own class (see below) and overwrite toString() to return the name. then the JTree will show what you want.
    >
    And how can I use red font color for folder names
    with 0 files(numFiles = 0)?you need a tree cell renderer. it gets your file/folder object (see above) as a parameter. you can query it about the number of files and set the foreground/background accordingly.
    thomas

  • Display Tree structure using EVS or OVS

    Hi All,
        Here we have a requirement like display tree structure when I press F4. currently the sample application (using Object Value Selector or Extended Value Selector) is displaying the values in table, instead of table here we have to display it in tree.
       If it is not possible using either OVS or EVS please tell me what is the other way to solve the problem.
    Please give me any suggestion.
    Regards
    Suresh

    Suresh,
    You can emulate the behaviour by having a separate view for the tree structure.
    1.) Create a new view and put your tree structure UI + related logic in that view.
    2.) Create an input field and a linkToAction / button (with the text "Search".) aligned side by side.
    3.) On click of the search button, show the view containing tree as pop-up.
    You may develop upon this hint to meet your requirement.
    ~ Bala

  • Display tree node data in bold characters

    Hi,
    I have a requirement where I need to display tree nodes data in bold characters. If I click on a particular tree node, next time it should appear in normal font only which means that some task had done using that tree node. Is my question clear??
    Plz help me....
    thanks,
    ravindra.

    Hi Ravindra,
    I think it is possible, i have not done it but let me explain how we can do it.
    In <htmlb:treeNode> tag there is an attribute 'text' in
    which we specify title of that treeNode.
    Now you define a page attribute 'treeNodeTitle' type
    edpline and in onCreate assign it value <html><b>MyTreeNode</b></html>
    When you click on this node then you do event handling
    in onInputProcessing, there assign only 'MyTreeNode' to
    treeNodeTitle.
    sample code may look like this...
    <htmlb:treeNode
      id = 'treeNode1'
      text = '<%=treeNodeTitle %>' >
    </htmlb:treeNode>
    Page Attribute
    treeNodeTitle type edpline
    in onCreate
    treeNodeTitle = '<html><b>MyTreeNode</b></html>'
    in onInputProcessing
    in event-handling code for that treeNode write
    treeNodeTitle = 'MyTreeNode'
    I hope this will work.
    Regards,
    Narinder Hartala

  • Display Tree Structure in a List / Select Box

    I need info on the following
    1.display tree structure inside a select/combo/list box.
    2.Select a node element from the above tree structure.
    Thanks in advance

    Have you managed to do this?
    Faaiez

  • How to display FileDialog in applet?

    Hi all,
    I looked FileDialog constructors but only Frame can be the owner of the dialog? Is there a way to do display it in applet?
    Thank you.

    Try:
    JOptionPane.getFrameForComponent(this);
    Remember:
    Applets need to be signed to access the file system.

  • Porblem - Display Tree

    Hi all,
    I have a table with follow structure:
    ID NOT NULL NUMBER(38)
    NAME NOT NULL VARCHAR2(50)
    PARENT_ID NOT NULL NUMBER(38)
    when i want display tree data, i use sqlplus:
    SELECT LEVEL, name FROM tblFruits START WITH id=1 CONNECT BY PRIOR id=parent_id
    and get;
    LEVEL NAME
    1 Fruits
    2 Green Fruits
    3 Apples
    4 Tasty Apples
    3 Grape
    2 Red Fruits
    3 Apples
    but if i use a perl script to get too result, i get only 3 level,
    #!/usr/bin/perl -w
    use strict;
    use DBI;
    my $dbh = DBI->connect("dbi:Oracle:DATABASE", 'user', 'pass');
    if ( !defined $dbh ) {
    die $DBI::errstr;
    my $sth = $dbh->prepare("SELECT LEVEL, name from tblFruits start with id=1 connect by prior id=parent_id")
    or die "Error List";
    my ($lv, $name);
    $sth->execute
    or die "Error List";
    while(my @row = $sth->fetchrow_array()){
    ($lv, $name) = @row;
    print "$lv | $name\n";
    $dbh->disconnect;
    i get;
    LEVEL NAME
    1 Fruits
    2 Green Fruits
    3 Apples
    2 Red Fruits
    3 Apples
    i dont get good result, someone can help me please.

    Have you managed to do this?
    Faaiez

  • Display JSP in applet

    Is there anyway to load a JSP from within an applet?

    If you want to display the output of the jsp in a GUI object in the applet you can use the HttpURLConnection class. This will allow you to call the jsp and retrieve the response. How to display is up to you. Nor do I know how you would handle javascript or CSS.
    If you want the JSP to be displayed in the browser window that the applet window is running in, look into using JavaScript and LiveConnect.

  • Display Tree Nodes from LDIF

    I have to read the contents form an ldif file and display it with in a tree, in that the first dn, should be displayed as root dn, and next as child nodes with all the properties of dn.
    I displayed all the dn's but am not understanding how to take root dn and child nodes. please help me if any one know.
    Thanks,
    Raga

    Hi,
    When you delete a node and all of its children, what do you want to do with the grandchildren? If you want to set their parent_id to NULL, do that in a separate UPDATE statement first, then DELETE the original node and all its remaining descendants, as show below.
    If, when you say "children", you mean "descendants" (including
    children,
    children of children,
    children of children of children,
    and so on, to any level,
    ) then do a CONNECT BY query to find their primary keys, and DELETE everything in that list, like this:
    DELETE  subforms
    WHERE   id  IN
            SELECT  id
            FROM    subforms
            START WITH        id = :specified_id
            CONNECT BY  PRIOR id = parent_id
            );

  • Display tree hierarchy in adobe print form scenario

    Hi
    Can someone suggest what is the best way to create a tree structure in adobe print scenario ? can we display icon also next to the text in the tree. For example I want to get folder and file icons also along with their names in hierarchial manner.
    Regards
    vishal

    hi,
    to populate the dropdown list you can do it...
    1). manually or 
    2). by code
    1). <b>manually</b> go to interactive form->edit
         go to Object tab->field tab ->
         you must see something like
         List Items :
         Text     + x
         click on the green + sign...
         it promps you to type. type in the value press enter... and so  on...
    2) <b>by Code...</b>
        //set up contents of a drop down list dynamically...
        IWDAttributeInfo countryInfo = wdContext.nodeTravelData().getNodeInfo().
                getAttributeInfo().getAttribute("DestinationCountry");
        ISimpleTypeModifiable countryType =
                countryInfo.getModifiableSimpleType();
        IModifiableSimpleValueSet countryValueSet  =
                countryType.getSVServices().getModifiableSimpleValueSet();
        countryValueSet.put("1","Germany");
        countryValueSet.put("2","UK");
    This will work....
    regards,
    -amol gupta

  • Chess Piece display problem in applet

    Hi,
    I'm writing a chess game applet which will be played between to players over the internet. I'm currently working on the applet side at the moment and will develop the server side once I have completed the applet. I'm currently having problems displaying the actual chess pieces on the board at the moment. One of my design decisions was to make a Board class which extends a JPanel. I have painted the actual chess board squares within the Board JPanel. I then propose to draw the pieces on top of these squares (good design decsion? Can anyone suggest another way. I was thinking of having the images as a separate layer which will sit on top of the squares but wasn't sure how to implement it). The chess pieces are contained in a gif strip www.dur.ac.uk/j.d.p.murphy called ChessPieces02.gif . The problem I am having is to display several pieces at the same time. I lloked at a Java tutorial which suggested using g.clipRect() method to display a defined section of the strip (i.e. a single piece of a certain length). Below is the Board class that I am using.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends JPanel{
    // Holds location of the mousePressed event
    Point point = null;
    // Size of a square square on the board
    int square_size = 40;
    // Mediatracker to monitor the loading of the images
    MediaTracker tracker;
    Image image;
    void init() {
    tracker = new MediaTracker(this);
    image = Toolkit.getDefaultToolkit().getImage("ChessPieces02.gif");
    tracker.addImage(image, 0);
    try {
    //Start downloading the images. Wait until they're loaded.
    tracker.waitForAll();
    } catch (InterruptedException e) {
    e.printStackTrace();
    throw new Error("error");
    if (tracker.isErrorAny()) {
    throw new Error("Could not load image");
    addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (point == null)
    point = new Point(0, 0);
    int x = e.getX();
    int y = e.getY();
    System.out.println("X co-ord: " + x + " Y co-ord: " + y);
    // Floor the x and y values to the nearest unit of 25
    x = x - x % square_size;
    y = y - y % square_size;
    point.setLocation(x, y);
    repaint();
    System.out.println(point);
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    System.out.println("Chess Board Paint");
    // Loop to produce the black and white squares to represent the board
    for(int jj = 0; jj < 8; jj ++){
    for(int ii = 0; ii < 8; ii++){
    if(ii % 2 == jj % 2)
    g.setColor(Color.white);
    else
    g.setColor(Color.lightGray);
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    // Draw a highlighted square
    if (point != null){
    g.setColor(Color.green);
    g.fillRect( (int)point.getX(), (int)point.getY(), square_size, square_size);
    //imageStrip is the Image object representing the image strip.
    //imageWidth is the size of an individual image in the strip.
    //imageNumber is the number (from 0 to numImages)
    // of the image to paint.
    int stripWidth = image.getWidth(this);
    int stripHeight = image.getHeight(this);
    int imageWidth = stripWidth / 6;
    System.out.println("Width = " + imageWidth);
    g.clipRect(120, 0, imageWidth, stripHeight / 2);
    g.drawImage(image, 0 * imageWidth, 0, this);
    What code do i need to add more pieces to the board? I plan to make a ChessPiece array (8x8) which will holld all the chess pieces on the board. Should I hold this array in the board class to make drawing the pieces easier? Any other tips for game development would also be most welcome.
    Thanks

    cross post, I think.
    http://forum.java.sun.com/thread.jsp?thread=496287&forum=406

Maybe you are looking for

  • Help with centralising a box in the absolute middle og the browser screen

    Hello there, i was wondering if someone could help me out with a little problem im having. im trying to design a site which basically has a box in the middle of the browser where all the info is displayed. now i know that if u set the horizontal alig

  • The PDFs digitally signed are not compatible with the standard PDF/A

    Firmando digitalmente i file PDF/A-1b perdono la compatibilità con lo standard Dopo parecchi tentativi (per esser certo di escludere problemi eventualmente derivanti dal contenuto dell'elaborato), ho creato un PDF da Blocco Note (S.O.: Windows XP S.P

  • HT204291 How do you reset your password?

    How do you reset your password on iPad to use airplay?

  • OSX 10.6.8 UPGRADE WINDOW PROBLEM!

    Dear friends, I have a OSX 10.6.8 and from yesterday I CAN'T use Safari, Chrome, Firefox, no more! An Upgrade windows (that one you see here) appear and - if I accept the upgrading - he downloads me just a useless setup.exe file, even if I select the

  • RSCRM_BAPI in Process Chain

    Hi, We are having a RSCRM_BAPI which extracts data from a report and push it to a table. We need to include this process in our process chain. We are running on BI 7.0. How? regards, Sanjai