Draw figures from a xml and then draw anothers when I click on them

This is what I have to do:
I got a XML file with the info of a drawing: circles, rectangles.....
I read the file and I draw the figures on a JPanel.
And now what I have to do is this:
When I click on a figure I have to recognize what figure is, for example, rectangle number 2 on the XML file. Then I have to read the XML and foud what I have to draw when I click on that figure, this info is on the XML:
<Transition Rectangle="2" NextDraw="Rectangle 3" />
How do I draw all these figures and keep the info I need (name and number of the figure)? And how do I manage mouse events for recognize the click on a figure for draw anothers.
Sorry for my bad english and thanks

I don't know the structure of your XML file.
Anyway, I guess it's something like the following :
shapes.xml
<?xml version="1.0" encoding="UTF-8"?>
<shapes>
     <Transition Rectangle="1" NextDraw="Rectangle 2" />
     <Transition Rectangle="2" NextDraw="Rectangle 3" />
     <Transition Rectangle="3" NextDraw="Circle 1" />
     <Transition Circle="1" NextDraw="Circle 2" />
     <Transition Circle="2" NextDraw="Circle 3" />
     <Transition Circle="3" />
</shapes>Here the java code. Plz, take a look at it and adapt it to your needs.
XMLParserHandler.java
import java.util.HashMap;
import java.util.Map;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLParserHandler extends DefaultHandler {
     Map<String, String> shapes;
     public XMLParserHandler(){
          shapes = new HashMap<String, String>();
     public void startDocument() throws SAXException {
          //System.out.println("Start Shapes Document.xml");
          shapes = new HashMap<String, String>();
     public void endDocument() throws SAXException {
          //System.out.println("End Shapes shapes.xml");
     public void startElement(String uri, String localName, String qName,
               Attributes attributes) throws SAXException {
          //System.out.println("Start Element : " + qName);
          //display(attributes);
          if("TRANSITION".equals(qName.toUpperCase())){
               String key = null;
               String value = "";
               int n = attributes.getLength();
               String attrName;
               for (int i = 0; i < n; i++) {
                    attrName = attributes.getQName(i);
                    if(! "NEXTDRAW".equals(attrName.toUpperCase())){
                         key = new String(attrName+" "+attributes.getValue(i));
                    }else{
                         value = new String(attributes.getValue(i));
               if(key!=null){
                    shapes.put(key.toUpperCase(), value.toUpperCase());
     public void endElement(String uri, String localName, String qName)
               throws SAXException {
          //System.out.println("End Element : " + qName);
     public void characters(char[] ch, int start, int length)
               throws SAXException {
          //System.out.println(new String(ch, start, length));
     public void error(SAXParseException e) throws SAXException {
          throw e;
     public void fatalError(SAXParseException e) throws SAXException {
          throw e;
     public Map<String, String> getShapes() {
          return shapes;
     private void display(Attributes attrs){
          int n = attrs.getLength();
          for (int i = 0; i < n; i++) {
               System.out.println("***"+attrs.getQName(i)+" = "+attrs.getValue(i));
MyPanel.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
     static String CIRCLE = "CIRCLE";
     static String RECTANGLE = "RECTANGLE";
     public List shapeList;
     int currentIndex = 0;
     Shape currentShape;
     public MyPanel(Map shapes, String entry) {
          createShapeList(shapes, entry);
          addMouseListener(new MyMouseListener());
     private String getShapeName(String value){
          return value.split("\\s+")[0];
     private void createShapeList(Map shapes, String entry){
          shapeList = new ArrayList();
          Shape shape=null;
          String key = new String(entry);
          String value ;
          int i=0;
          do{
               value=getShapeName(key);
               System.out.println(value);
               if(CIRCLE.equals(value)){
                    shape = new Ellipse2D.Double(5, 5+40*i, 20, 20);
                    System.out.println("==> added circle");
               }else if(RECTANGLE.equals(value)){
                    shape = new Rectangle2D.Double(5, 5+40*i, 20, 20);
                    System.out.println("==> added rectangle");
               shapeList.add(shape);
               key = (String)shapes.get(key);
               i++;
          }while(value!=null&&value.trim().length()>0);
          currentShape = (Shape)shapeList.get(currentIndex);
     class MyMouseListener extends MouseAdapter{
          public void mouseClicked(MouseEvent e) {
               int x = e.getX();
               int y = e.getY();
               if(currentShape.contains(x, y)){
                    if(currentIndex<shapeList.size()-1){
                         currentIndex++;
                         currentShape = (Shape)shapeList.get(currentIndex);
                         repaint();
     public void paint(Graphics g) {
          Graphics2D g2 = (Graphics2D) g;
          g2.setPaint(Color.red);
          for (int i = 0; i < currentIndex+1; i++) {
               g2.fill((Shape)shapeList.get(i));
Main.java
import java.io.File;
import java.util.Map;
import javax.swing.JFrame;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Main {
     public static void main(String[] args) {
          SAXParserFactory spf = SAXParserFactory.newInstance();
          SAXParser parser;
          Map myShapes = null;
          try {
               parser = spf.newSAXParser();
               XMLParserHandler handler = new XMLParserHandler();
               parser.parse(new File("shapes.xml"), handler);
               myShapes = handler.getShapes();
               String entry = "RECTANGLE 1";
               //Create and set up the window.
               JFrame frame = new JFrame("MyFrame");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               // Create and set up the content pane.
               MyPanel newContentPane = new MyPanel(myShapes, entry);
               newContentPane.setOpaque(true); // content panes must be opaque
               frame.setContentPane(newContentPane);
               // Display the window.
               frame.setSize(400, 400);
               frame.setResizable(false);
               frame.setVisible(true);
          }catch(Exception e){
               e.printStackTrace();
NB: as mentioned in the Main class (see main method), you should provide the main entry for your xml file : String entry = "RECTANGLE 1";Hope That Helps

Similar Messages

  • Pictures turn to black and white exclamation marks when i click on them!

    Could someone please help me! My iphoto randomly deleted all of my photos from it's library, and i have spent ages re-importing them. now when i click on a picture to view it in large it changes to a large, blurry exclamation mark within a second! What is going on?!

    Welcome to the Apple Discussions.
    The ! or ? turns up when iPhoto loses the connection between the thumbnail in the iPhoto Window and the file it represents.
    My guess is that what has happened here is that your database has been damaged and the re-importing effort hasn’t worked because you’ve been importing to the same damaged DB.
    Try these in order - from best option on down...
    1. Do you have an up-to-date back up? If so, try copy the library6.iphoto file from the back up to the iPhoto Library (Right Click -> Show Package Contents) allowing it to overwrite the damaged file.
    2. Download iPhoto Library Manager and use its rebuild function. This will create a new library based on data in the albumdata.xml file. Not everything will be brought over - no slideshows, books or calendars, for instance - but it should get all your albums and keywords back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one.
    3. If neither of these work then you'll need to create and populate a new library.
    To create and populate a new *iPhoto 08* library:
    Note this will give you a working library with the same Events and pictures as before, however, you will lose your albums, keywords, modified versions, books, calendars etc.
    In the iPhoto Preferences -> Events Uncheck the box at 'Imported Items from the Finder'
    Move the iPhoto Library to the desktop
    Launch iPhoto. It will ask if you wish to create a new Library. Say Yes.
    Go into the iPhoto Library (Right Click -> Show Package Contents) on your desktop and find the Originals folder. From the Originals folder drag the individual Event Folders to the iPhoto Window and it will recreate them in the new library.
    When you're sure all is well you can delete the iPhoto Library on your desktop.
    In the future, in addition to your usual back up routine, you might like to make a copy of the library6.iPhoto file whenever you have made changes to the library as protection against database corruption.
    Regards
    TD

  • How can i remove items from list that have been deleted when i click on them it keeps showing empty

    how can i remove items from the list that have been deleted when i click on them it keeps showing folder empty

    Actually, Reader SHOULD keep showing documents that no longer exist, I disagree. It's no big deal, and people will quickly realise why they can't open the file. They open more files, the old ones move off.
    The REASON why it should not check is that checking whether a file exists can take a long time when things aren't good. For instance if a file server goes down, or a memory card is unplugged. That in turn would mean delays opening the File menu, and I've seen some software that can sit there for several minutes. That would really give people something of which to complain...

  • I want to use ODI to read XML messages from JMS queue and then process it..

    I want to use oracle ODI (Oracle Data Integrator) to read XML messages from JMS queue and then process it.. i also want to process and validate the data in it....
    Could anyone please tell me the steps to achieve the same. I tried some ways which i got on OTN, but not able to implement it exactly...
    As i m very new to ODI, it will be great if you provide detailed steps..
    Thanks in advance for your help....

    Hi,
    Were you able to do it? We are facing this same issue now and, despite the fact the docs say otherwise, it does not seem to be a trivial task.
    TIA,
    Tedi

  • Adobe creative cloud has stopped working, all my individual programmes from adobe open and work fine, but when I try to open adobe cloud it starts to open then says adobe cloud has stopped working, looking for a solution then shuts down, I can not open it

    Adobe creative cloud has stopped working, all my individual programmes from adobe open and work fine, but when I try to open adobe cloud it starts to open then says adobe cloud has stopped working, looking for a solution then shuts down, I can not open it at all.

    Without proper system information and the application logs nobody can tell you much.
    Troubleshoot Creative Cloud download and install issues
    Mylenium

  • HT204053 My wife and I have an iphone each using one apple id. How do we stop items being deleted from one phone and then find it has been deleted from the other?

    My wife and I have an iphone each using one apple id. How do we stop phone contacts being deleted from one phone and then find it has been deleted from the other?
    Also this works when one of us downloads an app it appears on the other iphone

    You need to use separate iCloud accounts. This will mean that you can both have your own separate contracts and calendars and put an end to them being deleted by each other.
    Whether or not you have a separate iTunes account, is up to you. If you have a separate iTunes accounts you will not be able to access the music, books, apps that have been purchased by the other. This may be exactly what you want, but it also means that you both may end up purchasing the same item.

  • How can I get my iPad to play just one song from my playlist and then stop automatically?

    I am a music teacher and I use the iPod on my iPad to play songs in class.  I have a long playlist of songs to choose from in each class, and I want to play just one song at a time.  I want to be able to start one song from my playlist and then walk away from my iPad and have it stop automatically when that song is over.  (I know how to make it repeat the same song over and over, but tha'ts not what I need.  I also know how to push "pause," but I don't want to have to walk away from the children to do it.) How can I make it play one song from a playlist at a time?

    I don't believe that there is a way to do that except, perhaps, creating a separate Playlist for each song.
    Suggestions for features to Apple at: http://www.apple.com/feedback/ipad.html

  • I have a Macbook Pro that I have just renewed and transferred over my old hard drive (also from a Macbook Pro). Now when I turn on the computer and ITunes opens I get error (-50) and then error 5002 when I try to sign in to ITunes Store - Help!

    I have a Macbook Pro that I have just renewed and transferred over my old hard drive (also from a Macbook Pro). Now when I turn on the computer and ITunes opens I get error (-50) and then error 5002 when I try to sign in to ITunes Store - Help!
    My dealer has tried and failed (twice) to correct this and I have tried deleting the two items in the Itunes folder but no luck!

    were you able to get help on this?  I need help on error 5002 as well.  thank you

  • I want to send a response from the servlet and then call another servlet.

    Hi,
    I want to send a response from the servlet and then call another servlet. can this happen. Here is my scenario.
    1. Capture all the information from a form including an Email address and submit it to a servlet.
    2. Now send a message to the browser that the request will be processed and mailed.
    3. Now execute the request and give a mail to the mentioned Email.
    Can this be done in any way even by calling another servlet from within a servlet or any other way.
    Can any one Please help me out.
    Thanks,
    Ramesh

    Maybe that will help you (This is registration sample):
    1.You have Registration.html;
    2.You have Registration servlet;
    3.You have CheckUser servlet;
    4.And last you have Dispatcher between all.
    See the code:
    Registration.html
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
      <HEAD>
        <TITLE>Hello registration</TITLE>
      </HEAD>
      <BODY>
      <H1>Entry</H1>
    <FORM ACTION="helloservlet" METHOD="POST">
    <LEFT>
    User: <INPUT TYPE="TEXT" NAME="login" SIZE=10><BR>
    Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
    <P>
    <TABLE CELLSPACING=1>
    <TR>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="logon" VALUE="Entry">
    </SMALL>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="registration" VALUE="Registration">
    </SMALL>
    </TABLE>
    </LEFT>
    </FORM>
    <BR>
      </BODY>
    </HTML>
    Dispatcher.java
    package mybeans;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Dispatcher extends HttpServlet {
        protected void forward(String address, HttpServletRequest request,
                               HttpServletResponse response)
                               throws ServletException, IOException {
                                   RequestDispatcher dispatcher = getServletContext().
                                   getRequestDispatcher(address);
                                   dispatcher.forward(request, response);
    Registration.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Registration extends Dispatcher {
        public String getServletInfo() {
            return "Registration servlet";
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext ctx = getServletContext();
            if(request.getParameter("logon") != null) {          
                this.forward("/CheckUser", request, response);
            else if (request.getParameter("registration") != null)  {         
                this.forward("/registration.html", request, response);
    CheckUser.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class CheckUser extends Dispatcher {
        Connection conn;
        Statement stat;
        ResultSet rs;
          String cur_UserName;
        public static String cur_UserSurname;;
        String cur_UserOtchestvo;
        public String getServletInfo() {
            return "Registration servlet";
        public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            try{
                ServletContext ctx = getServletContext();
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:oci:@eugenz","SYSTEM", "manager");
                stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
               String queryDB = "SELECT ID, Login, Password FROM TLogon WHERE Login = ? AND Password = ?";
                PreparedStatement ps = conn.prepareStatement(queryDB); 
               User user = new User();
            user.setLogin(request.getParameter("login"));
            String cur_Login = user.getLogin();
            ps.setString(1, cur_Login);
            user.setPassword(request.getParameter("password"));
            String cur_Password = user.getPassword();
            ps.setString(2, cur_Password);
         Password = admin");
            rs = ps.executeQuery();
                 String sn = "Zatoka";
            String n = "Eugen";
            String queryPeople = "SELECT ID, Surname FROM People WHERE ID = ?";
           PreparedStatement psPeople = conn.prepareStatement(queryPeople);
                      if(rs.next()) {
                int logonID = rs.getInt("ID");
                psPeople.setInt(1, logonID);
                rs = psPeople.executeQuery();
                rs.next();
                       user.setSurname(rs.getString("Surname"));
              FROM TLogon, People WHERE TLogon.ID = People.ID";
                       ctx.setAttribute("user", user);
                this.forward("/successLogin.jsp", request, response);
            this.forward("/registration.html", request, response);
            catch(Exception exception) {
    }CheckUser.java maybe incorrect, but it's not serious, because see the principe (conception).
    Main is Dispatcher.java. This class is dispatcher between all servlets.

  • I am new in indesign scripting, please tell me how to write a script to get  content of a element in xml and then sort all the content

    I am new in indesign scripting, please tell me how to write a script to get  content of a element in xml and then sort all the content

    Hi,
    May the below code is useful for you, but I dont know how to sort.
    Edit the tag as per your job request.
    alert(app.activeDocument.xmlElements[0].contents)
    //Second alert
    var xe = app.activeDocument.xmlElements[0].evaluateXPathExpression("//marginalnote");
    alert(xe.length)
    for(i=0; i<xe.length; i++)
        alert(xe[i].texts[0].contents)
    Regards
    Siraj

  • How to read two text files using the Read from spreadsheet.vi and then plot it

    I need to read two text files using the read from spreadsheet function and then plot these files over time.
    The file with the .res extention is the RMS values (dt and df) and the second file contains the amplitude of a frequency spectrum.
    I really appreciate any help..thanks
    Attachments:
    RMS.txt ‏1 KB
    FREQUENCY.txt ‏1 KB

    From NI Example Finder:
    Write to Text File.vi
    Read from Text File.vi
    Jean-Marc
    LV2009 and LV2013
    Free PDF Report with iTextSharp

  • How can I remove a person's face from a photo and then replace the spot with a person's face from another photo?

    How can I remove a person's face from a photo and then replace the spot with a person's face from another photo?

    In Editor, go to the expert tab.
    Open picture B, the one you wish to select the "replacement" face from to add to another picture.
    Use one of the selection tools, e.g. selection brush, lasso tool, to select the face. You will see an outline ("marching ants") once the selection is complete
    Go to Edit menu>copy to copy the selection to the clipboard
    Open picture A, then go to Edit>paste
    Use the move tool to position the face from picture B to cover the face on A
    In the layers palette you should see picture A as the background layer, and face B on a separate layer

  • I am not able to transfer emails from outlook 2007 in Windows 8 to outlook 2011 in Mac.  I export .pst file to my hard drive from win 8 and then import in outlook 11 in mac, the folders including subfolders are created but there are hardly one email

    i am not able to transfer emails from outlook 2007 in Windows 8 to outlook 2011 in Mac.  I export .pst file to my hard drive from win 8 and then import in outlook 11 in mac, the folders including subfolders are created but there are hardly one email.  Please help

    Post your question in the MS Mac forums since it's their software you're having issues with:
    http://answers.microsoft.com/en-us/mac

  • I have a Mac 10.5.8 Dual. I cannot get any videos that I have stored to play. I have tried QT and then DL two out side players from apple site and then went to install and comp said can not be installed on this comp.

    I have a Mac 10.5.8 Dual. I cannot get any videos that I have stored to play. I have tried QT and then DL two out side players from apple site and then went to install and comp said can not be installed on this comp.

    When Microsoft decided not to support Windows Media any more, they made Flip4Mac available for free. If you have not taken advantage of that free download, this might be a good time.
    It may not completely solve the problem, but your Mac will play more with the free player. No need to pay for the Upgrades.
    http://www.telestream.net/flip4mac/

  • When I upload photos to iPhoto from my iPhone and then press delete from iPhone it does not delete them, how do I fix this?

    When I upload photos to iPhoto from my iPhone and then press delete from iPhone it does not delete them, how do I fix this?

    I am having the same problems as this person. I see that someone said there is no way to retrieve the pictures once it gets stuck in recovery mode.
    Then further along someone said that there are data retrieval methods except they have something to do with jail breaking a phone.
    My phone is already jail broken. It was kind of a gift from the company I work for- it was a fellow employees before. He jail broke it and then it was given to me. After I got it I activated the 4 and tried to back up everything. It didn't work and "Springboard" forced the phone into safety mode. So I could use it with the old dude's apps and my contacts. I made the mistake of using the phone for wedding dress shopping with a friend. I took tons of pictures.
    After this I found out the messages I was seeing meant it was jail broken. At&t said to force restore the phone - iTunes wouldn't recognize it in safety mode. I'm an idiot and didn't realize what this meant for my pictures. It didn't work (error 1611) - thankfully. Now it is stuck in recovery mode (iTunes icon and USB cable picture).
    Can I access that media in any way? It never suceeded restoring itself so is it still there? The phone is jail broken already so is there a method I can use?

Maybe you are looking for

  • How to handle vendor down payments on invoice payment?

    Hi, The Vendor down payments are required to be manually cleared before payment against the Invoice to the Vendor. There is great amont of risk involved if manual clearing of down payments is not done. The invoices are likely to be paid fully in spit

  • Export SQL View to Flat File with UTF-8 Encoding

    I've setup a package in SSIS to export a SQL view to a flat file and it's working fine.  I now need to make that flat file UTF-8 encoded.  The package executes but still shows the files as ANSI encoded. My package consists of a Source (SQL View) -> D

  • Strange ora-1403 and 6508 errors after compiling forms in 10.1.2.0.2

    Hi, today we migrated our Application Server to 10.1.2.0.2 and totally unexpected (it was not mentioned in the upgrade guide of 400 pages...) we had to recompile all 9.0.4-executables So we installed Developer Suite 10.1.2.0.2 and recompiled all libr

  • Any known problems with the 1.2.3 update??

    My iPod is behaving just fine thank you so I'm always a bit leery to install any updates since I really got burned the absolute FIRST time that I tried to install an update less than a week after acquiring my video iPod. I've been told by others here

  • Add executable to flash

    I would like to add a .exe file to flash.  Example.  Goto flash website click on tech support and fire remote access.exe  Is this possible. TIA