Paint on a Graph XY

Hello,
I am making a program to control two DC motors. I write a word in the program and the engines draw it on paper.
Now I need to see on the screen the moves that are making the engines, for that I have two values for a graph X and Y, but i don't know how to draw on the graph with this data, just I get to move the pointer.
Thanks for the help
Greetings

I understand that the "graph" is building up continuously during the movement.
A graph draws an array and if a new array is going to be displayed, the old one is removed....
So what you have to do is to create an array and then replacing data during movement.
Norbert
CEO: What exactly is stopping us from doing this?
Expert: Geometry
Marketing Manager: Just ignore it.

Similar Messages

  • Paint drawing unscrolled graph over scrolled graph! JScrollPane JViewport

    I am planning to create a JScrollPane that has a scrollable JPanel. I have created a special paint method for the JPanel.
    The JPanel contains a simple graph.
    The graph will be scrolled with the JScrollPane.
    evreything is good until now.
    I want to draw (over the JPanel) another graph which I dont want it to be scrolled by the JScrollPane.
    I want: When moving the scrolls, the graph moves but the special graph does not get effected.
    I planned to overrirde the paint method of the JViewport object. I can see that the plan is good and the result is 80% pluasable, however, I am experiencing some effects:
    1- sometimes the special graph does not get painted!
    2- sometimes when moving the scrolls the up and down, the special graph does move, as if the contents are not updated.
    I am using Java 5 update 6!
    Here is my code, please test it your self:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test{
         public static void main(String[]args){
              JFrame f=new JFrame();
              JPanel p=new JPanel(){
                   public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        g.setColor(Color.red);
                        for(int i=0;i<4000;i+=20){
                             g.drawLine(0,i,800,i);
              JViewport port=new JViewport(){
                   public void paint(Graphics g){
                        super.paint(g);
                        g.fillRect(0,0,70,70);
              port.setView(p);
              p.setPreferredSize(new Dimension(500,4000));
              JScrollPane pane=new JScrollPane();
              pane.setViewport(port);
              f.add(pane);
              f.pack();
              f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
              f.setVisible(true);
    }

    This makes use of the fact that heavyweight/awt components are rendered over lightweight/swing components. Another way to do this is with a glass pane (JRootPane api). The tutorial has an example of glass pane use.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FloatingControls
        private JPanel getContent()
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.setLayout(overlay);
            panel.add(getControls());
            panel.add(getGraphicComponent());
            return panel;
        private JScrollPane getGraphicComponent()
            JPanel p=new JPanel()
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    g.setColor(Color.red);
                    for(int j=0;j<4000;j+=20)
                        g.drawLine(0,j,800,j);
            p.setPreferredSize(new Dimension(500,4000));
            return new JScrollPane(p);
        private JPanel getControls()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            Panel awtPanel = new Panel(gridbag)
                public void paint(Graphics g)
                    super.paint(g);
                    int w = getWidth();
                    int h = getHeight();
                    g.setColor(Color.blue);
                    g.fillRect(0,0,w-1,2);      // top
                    g.fillRect(0,2,2,h-5);      // left
                    g.fillRect(0,h-3,w-1,2);    // bottom
                    g.fillRect(w-3,2,2,h-5);    // right
                public Dimension getPreferredSize()
                    // beware of different plaf settings
                    return new Dimension(350, 45);
            awtPanel.setBackground(Color.pink);
            for(int j = 0; j < 4; j++)
                awtPanel.add(new JButton("button " + (j+1)), gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setOpaque(false);
            gbc.insets = new Insets(0,5,0,20);
            // an option, works with insets
            //gbc.fill = GridBagConstraints.HORIZONTAL;
            panel.add(awtPanel, gbc);
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new FloatingControls().getContent());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Im looking for a drawing app that i can draw on a grid paper

    im looking for a drawing app that i can draw on a grid paper any suggestions?

    an app that when i open it has a graph paper on it and i can use the grid to draw things. something like paint but has graph paper on it

  • Looking for a grid paper app HELP???

    an app that when i open it has a graph paper on it and i can use the grid to draw things. something like paint but has graph paper on it

      See if this helps  graph paper.

  • Swing with third party libraries

    I know that within the Java SDK there is an extensive ability to create 2D and 3D graphics for use in an application. However, what is the situation with 3rd part libraries (e.g. specifically looking at Open Inventor from numerical algorithms group). Is it easy to use these libraries within swing? For instance, from my limited knowledge so far I would envisgae creating some sort of 'pane' in which I could then simply paint a chart/graph that I'd created with the NAG library. Is it this easy or much more involved? To what extent are libraries compatible? As you can see I at a fairly basic level here so any help much appreciated.
    Cheers

    Close this thread as it makes little sense.

  • Graphics libraries

    I know that within the Java SDK there is an extensive ability to create 2D and 3D graphics for use in an application. However, what is the situation with 3rd part libraries (e.g. specifically looking at Open Inventor from numerical algorithms group). Is it easy to use these libraries within swing or other GUI API? For instance, from my limited knowledge so far I would envisgae creating some sort of 'pane' in which I could then simply paint a chart/graph that I'd created with the NAG library. Is it this easy or much more involved? To what extent are libraries compatible? As you can see I at a fairly basic level here so any help much appreciated.
    Cheers

    I went to google and typed in 'turtle graphics'. I got many links, but this may be what you want:
    http://www.turtleg.com/
    I should add, I've never heard of Turtle Graphics before.
    m

  • After use AffineTransform change also width of stroke

    Hi, may be you can help me. After use AffineTransform change also width of stroke. I want to paint a function graph and calculate that values but tje width of pen is also changed. May be, do I something incorrectly.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.Rectangle2D;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.print.*;
    public class MyFrame extends JFrame {
         public static final double MM_TO_PAPER_UNITS = 1 / 25.4 * 72;
         public static double widthA4 = 210 * MM_TO_PAPER_UNITS;
         public static double heightA4 = 297 * MM_TO_PAPER_UNITS;
         public static double leftMargin = 4.0 * MM_TO_PAPER_UNITS;
         public static double topMargin = 4.0 * MM_TO_PAPER_UNITS;
         JButton button;
         MyPanel panel;
         GridBagConstraints gridBagConstraints;
         public void init() {
              panel = new MyPanel();
              button = new JButton("Print");
              getContentPane().setLayout(new GridBagLayout());
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              gridBagConstraints = new GridBagConstraints();
              gridBagConstraints.fill = GridBagConstraints.BOTH;
              gridBagConstraints.weightx = 1.0;
              gridBagConstraints.weighty = 1.0;
              add(panel, gridBagConstraints);
              gridBagConstraints = new GridBagConstraints();
              gridBagConstraints.gridx = 0;
              gridBagConstraints.gridy = 1;
              add(button, gridBagConstraints);
              setSize(500, 500);
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        PrinterJob printJob = PrinterJob.getPrinterJob();
                        PageFormat pf = printJob.defaultPage();
                        pf.setOrientation(PageFormat.LANDSCAPE);
                        Paper paper = pf.getPaper();
                        paper.setSize(widthA4, heightA4);
                        paper.setImageableArea(leftMargin, topMargin, widthA4 - 2
                                  * leftMargin, heightA4 - 2 * topMargin);
                        pf.setPaper(paper);
                        printJob.setCopies(1);
                        Book book = new Book();
                        book.append(panel, pf, 1);
                        printJob.setPageable(book);
                        if (printJob.printDialog()) {
                             try {
                                  printJob.print();
                             } catch (Exception PrinterExeption) {
                                  PrinterExeption.printStackTrace();
              setVisible(true);
         public static void main(String[] args) {
              MyFrame myFrame = new MyFrame();
              myFrame.init();
         class MyPanel extends JPanel implements Printable {
              final int leftPadding = 20;
         final int rightPadding = 10;
         final int topPadding = 10;
         final int bottomPadding = 20;
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2 = (Graphics2D) g;
                   paingMyGrafik(g2);
              public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
                   Graphics2D g2 = (Graphics2D) graphics;
                   // affine transformation for grip of the panel`s content to the size
                   // A4
                   double W = pageFormat.getImageableWidth();
                   double H = pageFormat.getImageableHeight();
                   double minX = pageFormat.getImageableX();
                   double minY = pageFormat.getImageableY();
                   g2.transform(new AffineTransform((W) / this.getWidth(), 0, 0, (H)
                             / this.getHeight(), minX, minY));
                   paingMyGrafik(g2);
                   return 0;
              private void paingMyGrafik(Graphics2D g2) {
                   // here paint i my grafik
                   AffineTransform old = g2.getTransform();
                   g2.transform(toEndCoordinate());
                   BasicStroke stroke = new BasicStroke(0.2f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER);
         g2.setStroke(stroke);
                   g2.drawLine(1899, 20, 1901, 20);
         g2.drawLine(1901, 20, 1901, 25);
         g2.drawLine(1901, 25, 1905, 26);
                   g2.setTransform(old);
              private AffineTransform toUsualyCoordinate(){
    AffineTransform at = new AffineTransform();
    //mirror reflection relative to ox
    at.concatenate(new AffineTransform(1,0,0,-1,0,0));
    //parallel shift (x,y) -> (x, y-h)
    at.concatenate(AffineTransform.getTranslateInstance(0,-this.getHeight()));
    return at;
    private AffineTransform toEndCoordinate(){
    AffineTransform at = new AffineTransform();
    at.concatenate(toUsualyCoordinate());
    at.concatenate((new AffineTransform((double)(this.getWidth()-leftPadding-rightPadding)/this.getWidth(),0,0,(double)(this.getHeight()-topPadding-bottomPadding )/this.getHeight(),leftPadding,bottomPadding)));
    at.concatenate(new AffineTransform(-this.getWidth()/(getMinX()-getMaxX()-2),0,0,this.getHeight()/(getMaxY()-getMinY()+10),this.getWidth()*(getMinX()-1)/(getMinX()-getMaxX()-2),-this.getHeight()*(getMinY()-5)/(getMaxY()-getMinY()+10)));
    return at;
              private int min(int a, int b) {
                   return (a < b) ? a : b;
              private double getMinX(){
                   return 1900;
              private double getMaxX(){
                   return 2000;
              private double getMinY(){
                   return 20;
              private double getMaxY(){
                   return 30;
    }

    The right answer is here ( http://www.javable.com/forum/thread.jspa?messageID=100080&#100080)
    It is necessary to apply BasicStroke before use AffineTransform.
    GeneralPath gp = new GeneralPath();
    g2.setStroke(stroke);
    gp.lineTo((float) xval, (float) yval);
    g2.draw(gp.createTransformedShape(transform));--------

  • Image displayed by child window captured by parent window.

    This is a rather peculiar problem.
    My application starts with a JFrame which takes some file as an input and then open another window and plot the graph.What happens is whatever is drawn on the child window(graph) is captured by the parent window which looks quite odd.Could anyone help me out the how to solve this problem??

    sure... here are the codes......
    //parent window:
    package igib.genebrowser;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import igib.genebrowser.menu.*;
    import igib.genebrowser.plot.*;
    public class GeneBrowserMain extends JFrame
         public GeneBrowserMain()
              super("GenomeBrowser-1.0");
              Container cp = this.getContentPane();
              cp.setLayout(new BorderLayout());
              DrawFeature df = new DrawFeature();
              cp.add(df, BorderLayout.CENTER);
         public static void main(String args[])
              Point p = new Point(400,300);
              GeneBrowserMain gbm = new GeneBrowserMain();
              GeneBrowserMenu menu = new GeneBrowserMenu();
              gbm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              gbm.setSize(300,200);
              gbm.setLocation(p);
              gbm.setJMenuBar(menu);
              gbm.setResizable(false);
              gbm.setVisible(true);
    //GeneBrowserMenu file
    package igib.genebrowser.menu;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import igib.genebrowser.plot.*;
    import igib.genebrowser.menu.*;
    import igib.genebrowser.*;
    public class GeneBrowserMenu extends JMenuBar implements ActionListener
         JMenu fileMenu;
         JMenuItem open;
         JMenuItem quit;
         GeneBrowserMain gbm;
         public GeneBrowserMenu()
              this.gbm = gbm;
              fileMenu = new JMenu("File");
              this.add(fileMenu);
         open = new JMenuItem("open");
              fileMenu.add(open);
              quit = new JMenuItem("quit");
              fileMenu.add(quit);
              open.addActionListener(this);
              quit.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == open)
                   try
                             Point p = new Point(300,200);
                             FileOpenWindow f = new FileOpenWindow();
                             f.setSize(450,250);
                             f.setLocation(p);
                             f.setVisible(true);
                   catch(Exception ex)
              if(e.getSource() == quit)
                   System.exit(1);
    //FileOpenWindow which takes file as input and opens GBMainFrame and plot graphs
    package igib.genebrowser.menu;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.colorchooser.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import java.io.FileWriter;
    import java.io.BufferedReader.*;
    import java.io.File;
    import igib.genebrowser.util.*;
    import igib.genebrowser.plot.*;
    import igib.genebrowser.*;
    //import java.io.*;
    public class FileOpenWindow extends JFrame implements ActionListener, ItemListener
         public JTabbedPane tPane ;
         public File seqFile, repeatFile, snpFile, geneFile;
         JLabel sequenceFile, repeatfile, snpfile, genefile, jb, winsize, shiftsize;
         JButton browse1, browse2, ok1, ok2, browse3, browse4, browse5, browse6;
         JTextField jtf1, jtf2, jtf3, jtf4, jtf5, jtf6;
         File f;
         PlotGraph pg;
         GBMainFrame gb;
         GeneBrowserMain gbm;
         JComboBox shiftSize, winSize;
         public FileOpenWindow()
              super("Open File");
              ImageIcon icon = new ImageIcon("images/middle.gif");
              Container cp = this.getContentPane();
              tPane = new JTabbedPane();
              JPanel jp1 = addNCBI();
              JPanel jp2 = addOther();
              tPane.addTab("NCBI", icon, jp1);
    tPane.setSelectedIndex(0);
              tPane.addTab("Other", icon, jp2);
    tPane.setSelectedIndex(0);
              //tPane.add(jp1);
              cp.add(tPane,BorderLayout.CENTER);
              this.setResizable(false);
         private JPanel addNCBI()
              JPanel cp = new JPanel();
              cp.setLayout(new GridLayout(8,5));
    //***********************1st row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************1st row*************************************************//
    //***********************2nd row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************2nd row*************************************************//
    //***********************3rd row*************************************************//
              jb = new JLabel(" Sequence");
              cp.add(jb);
              sequenceFile = new JLabel(" File :");
              cp.add(sequenceFile);
              browse1 = new JButton("browse");
              cp.add(browse1);
              jtf1 = new JTextField(" ");
              cp.add(jtf1);
              jb = new JLabel(" ");
              cp.add(jb);
    //***********************3rd row*************************************************//
    //***********************4th row*************************************************//
                   jb = new JLabel(" Repeat");
                   cp.add(jb);
                   repeatfile = new JLabel(" File :");
                   cp.add(repeatfile);
                   browse2 = new JButton("browse");
                   cp.add(browse2);
                   jtf2 = new JTextField(" ");
                   cp.add(jtf2);
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************4th row*************************************************//
    //***********************5th row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************5th row*************************************************//
    //***********************1st row*************************************************//
                   winsize = new JLabel("Window Size: ");
                   cp.add(winsize);
                   winSize = new JComboBox();
                   winSize.addItem("100");
                   winSize.addItem("500");
                   winSize.addItem("1000");
                   winSize.addItem("5000");
                   cp.add(winSize);
                   jb = new JLabel(" ");
                   cp.add(jb);
                   shiftsize = new JLabel("Shift Size: ");
                   cp.add(shiftsize);
                   shiftSize = new JComboBox();
                   shiftSize.addItem("25");
                   shiftSize.addItem("50");
                   shiftSize.addItem("100");
                   shiftSize.addItem("500");
                   cp.add(shiftSize);
    //***********************1st row*************************************************//
    //***********************5th row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************5th row*************************************************//
    //***********************6th row*************************************************//
                   for(int i = 0; i < 2; i++)
                        jb = new JLabel(" ");
                        cp.add(jb);
                   ok1 = new JButton("OK");
                   cp.add(ok1);
                   for(int i = 0; i < 2; i++)
                        jb = new JLabel(" ");
                        cp.add(jb);
    //***********************6th row*************************************************//
                   browse1.addActionListener(this);
                   browse2.addActionListener(this);
                   ok1.addActionListener(this);
                   shiftSize.addItemListener(this);
                   winSize.addItemListener(this);
                   return cp;
         private JPanel addOther()
              JPanel cp = new JPanel();
              cp.setLayout(new GridLayout(9,5));
    //***********************1st row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************1st row*************************************************//
    //***********************2nd row*************************************************//
              jb = new JLabel(" ");
              cp.add(jb);
              sequenceFile = new JLabel("sequenceFile :");
              cp.add(sequenceFile);
              browse3 = new JButton("browse");
              cp.add(browse3);
              jtf3 = new JTextField(" ");
              cp.add(jtf3);
              jb = new JLabel(" ");
              cp.add(jb);
    //***********************2nd row*************************************************//
    //***********************3rd row*************************************************//
                   jb = new JLabel(" ");
                   cp.add(jb);
                   repeatfile = new JLabel("RepeatFile :");
                   cp.add(repeatfile);
                   browse4 = new JButton("browse");
                   cp.add(browse4);
                   jtf4 = new JTextField(" ");
                   cp.add(jtf4);
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************3rd row*************************************************//
    //***********************4th row*************************************************//
              jb = new JLabel(" ");
              cp.add(jb);
              snpfile = new JLabel("SNP File :");
              cp.add(snpfile);
              browse5 = new JButton("browse");
              cp.add(browse5);
              jtf5 = new JTextField(" ");
              cp.add(jtf5);
              jb = new JLabel(" ");
              cp.add(jb);
    //***********************4th row*************************************************//
    //***********************5th row*************************************************//
              jb = new JLabel(" ");
              cp.add(jb);
              genefile = new JLabel("Gene File :");
              cp.add(genefile);
              browse6 = new JButton("browse");
              cp.add(browse6);
              jtf6 = new JTextField(" ");
              cp.add(jtf6);
              jb = new JLabel(" ");
              cp.add(jb);
    //***********************5th row*************************************************//
    //***********************6th row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************6th row*************************************************//
    //***********************1st row*************************************************//
                   winsize = new JLabel("Window Size: ");
                   cp.add(winsize);
                   winSize = new JComboBox();
                   winSize.addItem("100");
                   winSize.addItem("500");
                   winSize.addItem("1000");
                   winSize.addItem("5000");
                   cp.add(winSize);
                   jb = new JLabel(" ");
                   cp.add(jb);
                   shiftsize = new JLabel("Shift Size: ");
                   cp.add(shiftsize);
                   shiftSize = new JComboBox();
                   shiftSize.addItem("25");
                   shiftSize.addItem("50");
                   shiftSize.addItem("100");
                   shiftSize.addItem("500");
                   cp.add(shiftSize);
    //***********************1st row*************************************************//
    //***********************6th row*************************************************//
              for(int i = 0; i < 5; i++)
                   jb = new JLabel(" ");
                   cp.add(jb);
    //***********************6th row*************************************************//
    //***********************7th row*************************************************//
                   for(int i = 0; i < 2; i++)
                        jb = new JLabel(" ");
                        cp.add(jb);
                   ok2 = new JButton("OK");
                   cp.add(ok2);
                   for(int i = 0; i < 2; i++)
                        jb = new JLabel(" ");
                        cp.add(jb);
    //***********************7th row*************************************************//
              browse3.addActionListener(this);
              browse4.addActionListener(this);
              browse5.addActionListener(this);
              browse6.addActionListener(this);
              ok2.addActionListener(this);
              return cp;
         public void actionPerformed(ActionEvent e)
              if(e.getSource()==ok1)
                   String ncbi = "";
                   String repeat= "";
                   try
                        ncbi = jtf1.getText();
                        repeat = jtf2.getText();
                        System.out.println("NCBI" + ncbi + "www");
                        if( ncbi.equals(" ") && repeat.equals(" "))
                             System.out.println("NCBI333" + ncbi);
                             DisplayInfo di = new DisplayInfo("Sorry!, Please select some file", "");
                             di.setSize(450,100);
                             di.setLocation(600,600);
                             di.setVisible(true);
                             GBFileProp.snpFile = "";
                             GBFileProp.geneFile = "";
                             return;
                   catch(Exception ex)
                   GBFileProp.fileFormat="NCBI";
                   GBFileProp.fileName = ncbi;
                   GBFileProp.repeatFile = repeat;
                   ReadNCBI readFile1 = new ReadNCBI(ncbi);
                   ReadRepeatFile rrf = new ReadRepeatFile(repeat);
                   try
                        gb = new GBMainFrame();
                        gb.setSize(1200,750);
                   catch(Exception ex)
                        DisplayInfo di = new DisplayInfo("Sorry!, Wrong File", "Enter file in \".gbk\" format");
                        di.setSize(450,100);
                        di.setLocation(600,600);
                        di.setVisible(true);
                   setVisible(false);
                   setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              if(e.getSource()==ok2)
                   String sequence= "";
                   String repeat= "";
                   String snp= "";
                   String gene= "";
                   try
                        sequence = jtf3.getText();
                        repeat = jtf4.getText();
                        snp = jtf5.getText();
                        gene = jtf6.getText();
                        if( sequence.equals(" ") && repeat.equals(" ") && snp.equals(" ") && gene.equals(" "))
                                                      DisplayInfo di = new DisplayInfo("Sorry!, Please select some file", "");
                             di.setSize(450,100);
                             di.setLocation(600,600);
                             di.setVisible(true);
                             System.out.println("File " + GBFileProp.repeatFile);
                             return;
                   catch(Exception ex)
                   GBFileProp.fileFormat="Other";
                   GBFileProp.fileName = sequence;
                   GBFileProp.repeatFile = repeat;
                   GBFileProp.snpFile = snp;
                   GBFileProp.geneFile = gene;
                   ReadGeneFile a = new ReadGeneFile(gene);
                   ReadSNPFile rsp = new ReadSNPFile(snp);
                   GCReadFile grf = new GCReadFile(sequence);
                   ReadRepeatFile rrf = new ReadRepeatFile(repeat);
                   try
                        gb = new GBMainFrame();
                        gb.setSize(1200,800);
                   catch(Exception ex)
                        DisplayInfo di = new DisplayInfo("Sorry!, Wrong File", "Enter file in corresponding format");
                        di.setSize(450,100);
                        di.setLocation(600,600);
                        di.setVisible(true);
                   setVisible(false);
                   setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              if(e.getSource()==browse1)
                   String w;
                   Fselect(1);
                   try
                   w=f.toString();
                   jtf1.setText(w);
                   catch(Exception ex)
              if(e.getSource()==browse2)
                   String w;
                   Fselect(4);
                   try
                   w=f.toString();
                   jtf2.setText(w);
                   catch(Exception ex)
              if(e.getSource()==browse3)
                   String w;
                   Fselect(3);
                   try
                   w=f.toString();
                   jtf3.setText(w);
                   catch(Exception ex)
              if(e.getSource()==browse4)
                   String w;
                   Fselect(2);
                   try
                   w=f.toString();
                   jtf4.setText(w);
                   catch(Exception ex)
              if(e.getSource()==browse5)
                   String w;
                   Fselect(4);
                   try
                   w=f.toString();
                   jtf5.setText(w);
                   catch(Exception ex)
              if(e.getSource()==browse6)
                   String w;
                   Fselect(2);
                   try
                   w=f.toString();
                   jtf6.setText(w);
                   catch(Exception ex)
              if(e.getActionCommand().equals("sequence_ncbi"))
                   final JFileChooser chooser = new JFileChooser();
                   FileFilter type1 = new ExtensionFilter ("Fasta File(.faa)", new String[] {".faa",".txt"});
                   chooser.addChoosableFileFilter (type1);
                   chooser.setFileFilter (type1);
                   int returnVal = chooser.showOpenDialog(this);
                   if (returnVal == JFileChooser.APPROVE_OPTION)
                        seqFile = chooser.getSelectedFile();
              else if(e.getActionCommand().equals("sequence_other"))
                   final JFileChooser chooser = new JFileChooser();
                   FileFilter type1 = new ExtensionFilter ("Fasta File(.faa)", new String[] {".faa",".txt"});
                   chooser.addChoosableFileFilter (type1);
                   chooser.setFileFilter (type1);
                   int returnVal = chooser.showOpenDialog(this);
                   if (returnVal == JFileChooser.APPROVE_OPTION)
                        seqFile = chooser.getSelectedFile();
         public void itemStateChanged (ItemEvent e)
              GBFileProp.windowsize = (int)Integer.parseInt(winSize.getSelectedItem().toString());
              GBFileProp.shiftsize = (int)Integer.parseInt(shiftSize.getSelectedItem().toString());
         public void Fselect(int sel)
                   final JFileChooser chooser = new JFileChooser();
         ImageIcon openIcon = new ImageIcon("images/open.gif");
                   FileFilter type1 = new ExtensionFilter ("NCBI File(.gbk)", new String[] {".gbk",".txt"});
                   FileFilter type2 = new ExtensionFilter ("ptt File(.ptt)", new String[] {".ptt",".txt"});
                   FileFilter type3 = new ExtensionFilter ("Fasta File(.faa)", new String[] {".faa",".txt"});
                   FileFilter type4 = new ExtensionFilter ("Text File(.txt)", new String[] {".txt",".txt"});
                   chooser.setCurrentDirectory (new File (System.getProperty ("user.dir")));
                   if(sel == 1)
                        chooser.addChoosableFileFilter (type1);
              chooser.setFileFilter (type1);
                   if(sel == 2)
                        chooser.addChoosableFileFilter (type2);
              chooser.setFileFilter (type2);
                   if(sel == 3)
                        chooser.addChoosableFileFilter (type3);
              chooser.setFileFilter (type3);
                   if(sel == 4)
                        chooser.addChoosableFileFilter (type4);
              chooser.setFileFilter (type4);
         int returnVal = chooser.showOpenDialog(this);
                   if (returnVal == JFileChooser.APPROVE_OPTION)
                        f = chooser.getSelectedFile();
                        //System.out.println("path of open "+ f);
    //GBMainFrame file
    package igib.genebrowser;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import igib.genebrowser.menu.*;
    import igib.genebrowser.plot.*;
    import igib.genebrowser.util.*;
    public class GBMainFrame extends JFrame
         GBMainMenu gb;
         PlotGraph pg;
         JPanel jf = new JPanel();
         JPanel jf1;
         LineGraph lg, lg1;
         JPanel jp1, jp2;
         JLabel jl;
         public GBMainFrame()
              super("File: " + GBFileProp.fileName + " " + GBFileProp.repeatFile + " " + GBFileProp.snpFile + " " + GBFileProp.geneFile);
              Container cp = this.getContentPane();
              cp.setLayout(new BorderLayout());
              cp.setSize(1024,600);
              Color c1=new Color(255,100,100);
              jf = new JPanel(new GridLayout(1,15));
    cp.add(jf, BorderLayout.NORTH);
              pg = new PlotGraph();
              pg.setBackground(Color.white);
              cp.add(pg, BorderLayout.CENTER);
              GBFileProp.jsb.setUnitIncrement(5);
              cp.add(GBFileProp.jsb, BorderLayout.SOUTH);
              lg1 = new LineGraph();
              lg1.setBackground(Color.white);
              lg1.setSize(50, 1000);
              cp.add(lg1, BorderLayout.EAST);
              lg = new LineGraph();
              lg.setBackground(Color.white);
              cp.add(lg, BorderLayout.WEST);
              gb = new GBMainMenu();
              jf.add(gb);
              setVisible(true);
              repaint();
    //PlotGraph File
    package igib.genebrowser.plot;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.image.*;
    import java.io.*;
    //import Acme.JPM.Encoders.*;
    //import Acme.*;
    import java.awt.print.*;
    import java.awt.Component;
    import java.awt.print.PrinterJob;
    import igib.genebrowser.menu.*;
    import igib.genebrowser.util.*;
    import igib.genebrowser.*;
    public class PlotGraph extends JPanel implements MouseListener,MouseMotionListener
         int xcoordinate;
         JScrollBar scrollBar;
         int mouseX;
         int mouseY;
         String st1 = " ";
         JScrollPane jsp;
         int check;
         int n;
         double base;
         int value;
         String repeatSymbol = "!";
         int position[] = new int[1500];
         public PlotGraph(String st)
              check = 0;
              GBFileProp.check = false;
         setVisible(true);
              ToolTipManager.sharedInstance().setInitialDelay(0);
              addMouseListener(this);
              addMouseMotionListener(this);
         public PlotGraph()
              check = 0;
              //System.out.println(GBFileProp.gcmax + "max y");
              if(GBFileProp.genescore>5)
              GBFileProp.filesize = GBFileProp.readGeneEnd[GBFileProp.genescore - 6];
              //System.out.println(GBFileProp.seqscore + " GBFileProp.seqscore");
              if(GBFileProp.filesize < GBFileProp.seqscore)
                   GBFileProp.filesize = GBFileProp.seqscore;
              if(GBFileProp.snpscore>5)
                   if(GBFileProp.filesize < GBFileProp.readSNPPosition[GBFileProp.snpscore-6])
                        GBFileProp.filesize = GBFileProp.readSNPPosition[GBFileProp.snpscore-6];
              if(GBFileProp.repeatscore>2)
                   if(GBFileProp.filesize < GBFileProp.endRepeatPosition[GBFileProp.repeatscore-2])
                        GBFileProp.filesize = GBFileProp.endRepeatPosition[GBFileProp.repeatscore-2];
              GBFileProp.scrollsize = (int)GBFileProp.filesize/285;
              GBFileProp.check = true;
         setVisible(true);
              addMouseListener(this);
              addMouseMotionListener(this);
              try
              AdjustmentListener lst = new AdjustmentListener()
                   public void adjustmentValueChanged(AdjustmentEvent e)
                        int i = e.getValue();
                        value = i;
                        GBFileProp.defaultStartCoordinate = (int)(e.getValue()*10*base);
                        GBFileProp.defaultEndCoordinate = GBFileProp.defaultStartCoordinate + (int)(10000*base);
                        repaint();
              GBFileProp.jsb.addAdjustmentListener(lst);
              catch(Exception e)
                   System.out.println("error here" + e);
    //******************** For Painting all the graph**********************************//
         public void paintComponent(final Graphics g)
              super.paintComponent(g);
              Font f = new Font("Times-Roman", Font.PLAIN, 16);
              g.setFont(f);
              GBFileProp.scrollsize = (int)GBFileProp.filesize/285;
              base = (double)(100.0/GBFileProp.zoomSize);
              n = (int)(GBFileProp.filesize/base);
              GBFileProp.jsb.setMaximum(n/10);
              if(GBFileProp.checkSave)
                   GBFileProp.checkSave = false;
                   Image img = this.createImage(1200,800);               
                   Graphics gph = img.getGraphics();
                   this.paint(gph);
                   try
                        OutputStream os = new FileOutputStream(GBFileProp.save);
                        GifEncoderTest ge = new GifEncoderTest(img,os);
                        ge.encode();
                        os.close();
                        catch(Exception e){}
              if(GBFileProp.checkPrint)
                   try
                        GBFileProp.checkPrint = false;
                        RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);
                        PrinterJob pj=PrinterJob.getPrinterJob();
                        pj.printDialog();
                        pj.print();
                   catch (Exception PrintException)
                        System.out.println("print error" + PrintException);
                        GBFileProp.checkPrint = false;
              if(SetVisibleClass.isMerge)
                        GBFileProp.snpposition = 500;
                        GBFileProp.geneposition = 500;
                        GBFileProp.repeatposition = 500;
                        GBFileProp.userdefinedpoint = 500;
                   else
                        GBFileProp.snpposition = 450;
                        GBFileProp.geneposition = 400;
                        GBFileProp.repeatposition = 150;
                        GBFileProp.userdefinedpoint = 500;
              if(GBFileProp.check)
                   try
                        if(SetVisibleClass.isSNP)
                        drawSNPPage(g);
                   catch(Exception e)
                        System.out.println("Error in snp plotting");
                   try
                        drawGenePage(g);
                   catch(Exception e)
                        System.out.println("Error in gene plotting");
                   try
                        if(SetVisibleClass.isGC)                    
                        drawGCPage(g);
                   catch(Exception e)
                        //System.out.println("Error in GC plotting");
                   try
                        drawUserDefinedPage(g);
                   catch(Exception e)
                        System.out.println("Error in User Defined plotting");
                   try
                        if(SetVisibleClass.isRepeat)                    
                             drawRepeatPage(g);
                   catch(Exception e)
                        System.out.println("Error in Repeat plotting");
    //******************** For Painting all the graph**********************************//
    //***************************** For Painting Gene**********************************//
         public void drawGenePage(Graphics g1)
              Graphics2D g = (Graphics2D)g1;
              g1.setColor(Color.darkGray);
              g.drawLine(0,650,(int)10000,650);
              //g1.setColor(Color.b);
              BasicStroke pen = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
    g.setStroke(pen);
    //****************************** X coordinate *************************************//
              for(int i = 0; i < 10000; )
                   int xcor = (GBFileProp.defaultStartCoordinate + (int)(i*base));
                   String xCoordinate = "" + xcor;
                   g.drawLine((int)(i/10),645,(int)(i/10),655);
                   g.drawString(xCoordinate,(int)(i/10),665);
                   i = i + 1000; //+ (int)(1000/base);
    //****************************** X coordinate *************************************//
              if(SetVisibleClass.isGene)
                   g1.setColor(Color.darkGray);
                   g1.drawString("Gene:", 10, (GBFileProp.geneposition - 25));
                   g1.setColor(GBColorSymbol.cGene);
                   for (int i = 0; i < GBFileProp.genescore ; i++) // - 5 to b subtracted from genescore
                        int basestart = (int)((GBFileProp.readGeneStart[i] - (int)(GBFileProp.defaultStartCoordinate))/base); ///10;
                        int baseend = (int)((GBFileProp.readGeneEnd[i] - (int)(GBFileProp.defaultStartCoordinate))/base);
                        if(basestart >=0 && baseend <=(int)(10000))
                             checkGenePosition(i);
                             g.drawLine((int)((basestart/10)),GBFileProp.geneposition,(int)((baseend/10)),GBFileProp.geneposition);
                             arrow(true,true,i, g, basestart, baseend);
                        if(basestart >=0 && baseend > (int)(10000))
                             checkGenePosition(i);
                             g.drawLine(basestart/10,GBFileProp.geneposition,1000,GBFileProp.geneposition);
                             arrow(true,false,i, g, basestart, 10000);
                        if(basestart < 0 && baseend <= (int)(10000))
                             checkGenePosition(i);
                             g.drawLine(0,GBFileProp.geneposition,baseend/10,GBFileProp.geneposition);
                             arrow(false,true,i, g, 0, baseend);
                        if(basestart < 0 && baseend > (int)(10000))
                             checkGenePosition(i);
                             g.drawLine(0,GBFileProp.geneposition,1000,GBFileProp.geneposition);
                   //System.out.println("GeneSt: " + GBFileProp.readGeneStart[i] + " GeneEd: " + GBFileProp.readGeneEnd[i] + " No " + i + "GeneScore " + GBFileProp.genescore);     
    //*****************************End For Painting Gene**********************************//
    //*****************************Start For Painting snp**********************************//
         public void drawSNPPage(Graphics g1)
              //System.out.println(GBFileProp.snpscore + "for snp");
              Graphics2D g = (Graphics2D) g1;
              BasicStroke pen = new BasicStroke();
              g.setStroke(pen);
              //g.setColor(Color.Red);
              g.drawString("SNP", 20, GBFileProp.snpposition);
              g.setColor(GBColorSymbol.cSnp);
              for(int i = 0; i < GBFileProp.snpscore; i++)
                   int basePosition = (int)((GBFileProp.readSNPPosition[i] - GBFileProp.defaultStartCoordinate)/base);
                   //System.out.println(" position " + (basePosition/10));
                   //g.drawString("|",(basePosition/10),GBFileProp.snpposition);
                   g.drawString(GBColorSymbol.snpSymValues[GBColorSymbol.snpSym],(basePosition/10),GBFileProp.snpposition);
                                                                                                                  //Line SNP score
              //System.out.println(GBFileProp.snplinescore);
              for(int i = 0; i < GBFileProp.snplinescore-1; i++)
                   int basePosition = (int)((GBFileProp.readSNPStartPosition[i] - GBFileProp.defaultStartCoordinate)/base);
                   //g.drawString("|",(basePosition/10),GBFileProp.snpposition);
                   g.drawString(GBColorSymbol.snpSymValues[GBColorSymbol.snpSym],(basePosition/10),GBFileProp.snpposition);
              for(int i = 0; i < GBFileProp.snplinescore-1; i++)
                   int basestart = (int)((GBFileProp.readSNPStartPosition[i] - (int)(GBFileProp.defaultStartCoordinate))/base); ///10;
                   int baseend = (int)((GBFileProp.readSNPEndPosition[i] - (int)(GBFileProp.defaultEndCoordinate))/base);
                   System.out.println(basestart + "     " + baseend);
                   if(basestart >=0 && baseend <=(int)(10000))
                             g.drawLine((int)((basestart/10)),GBFileProp.snpposition,(int)((baseend/10)),GBFileProp.snpposition);
                   if(basestart >=0 && baseend >(int)(10000))
                             g.drawLine((int)((basestart/10)),GBFileProp.snpposition,(int)((1000)),GBFileProp.snpposition);
                   if(basestart < 0 && baseend <=(int)(10000))
                             g.drawLine((int)((0)),GBFileProp.snpposition,(int)((baseend/10)),GBFileProp.snpposition);
                   if(basestart < 0 && baseend > (int)(10000))
                             g.drawLine((int)((0)),GBFileProp.snpposition,(int)((1000)),GBFileProp.snpposition);
    //*****************************Start For Painting GCPlotting**********************************//
         public void drawGCPage(Graphics g1)
              Graphics2D g = (Graphics2D) g1;
              g1.setColor(Color.darkGray);
              g.drawString("GC Percentage", 20, 20);
              BasicStroke pen = new BasicStroke();
              g.setStroke(pen);
              g1.setColor(Color.black);
              //System.out.println(GBFileProp.seqscore + " score");
              for(int i = 0; i < (int)((10000)*base); )
                   //System.out.println(GBFileProp.defaultEndCoordinate + " " i" " + GBFileProp.defaultStartCoordinate);
                        //System.out.println(GBFileProp.gcposition);
                        int firstPosition = (int)GBFileProp.GCPercentage[(int)((((int)(i) + GBFileProp.defaultStartCoordinate)/GBFileProp.shiftsize))] * (3*100)/GBFileProp.gcmax;
                        int secondPosition = (int)GBFileProp.GCPercentage[(int)((((int)((i+GBFileProp.shiftsize)) + GBFileProp.defaultStartCoordinate)/GBFileProp.shiftsize))] * (3*100)/(GBFileProp.gcmax);
                        g.drawLine((int)((i/10)/base), GBFileProp.gcposition - firstPosition, (int)(((i+GBFileProp.shiftsize)/10)/base), GBFileProp.gcposition - secondPosition);
                        i = i + GBFileProp.shiftsize;
              for(int i = 0; i < GBFileProp.seqscore -1; i++)
                   int firstPosition = (int)Integer.parseInt(GBFileProp.GCPoint.elementAt(i).toString()) * 3;
                   int secondPosition = (int)Integer.parseInt(GBFileProp.GCPoint.elementAt(i+50).toString()) * 3;
                   //int secondPosition = (int)GBFileProp.GCPercentage[i+50] * 3;
                   //g.drawString("|",basePosition,300);
                   g.drawLine((int)(i/10), 300 - firstPosition, (int)(i+50)/10, 300 - secondPosition);
                   i = i + 49;
    //*****************************End For Painting GCPlotting**********************************//
    //*****************************Start For Painting Repeat File**********************************//
         public void drawRepeatPage(Graphics g1)
              int check = 0;
              Graphics2D g = (Graphics2D) g1;
              g.setColor(Color.darkGray);
              g.drawString("Repeat", 10, 480);
              for (int i = 0; i < GBFileProp.repeatscore ; i++)//- 1 to b subtracted from repeatscore
                   int basestart = (int)((GBFileProp.startRepeatPosition[i] - (int)(GBFileProp.defaultStartCoordinate))/base); ///10;
                   int baseend = (int)((GBFileProp.startRepeatPosition[i] - (int)(GBFileProp.defaultStartCoordinate))/base);
                   if(basestart > 0 && basestart < 10000)
                        try
                             if(GBFileProp.repeatFamily.equals("LINE"))
                                  System.out.println(" Line" );
                                  GBFileProp.repeatposition = 575;
                                  repeatSymbol = GBColorSymbol.repeatSymValues[GBColorSymbol.lineSym];
                                  if(GBFileProp.repeatName[i].length() >= 2)
                                       if(GBFileProp.repeatName[i].substring(0,2).equals("L1"))
                                            g.setColor(GBColorSymbol.cL1);
                                            g.drawString(repeatSymbol, (int)(basestart/10), GBFileProp.repeatposition);
                                       else if(GBFileProp.repeatName[i].substring(0,2).equals("L2"))
                                            g.setColor(GBColorSymbol.cL2);
                                            g.drawString(repeatSymbol, (int)(basestart/10), GBFileProp.repeatposition);
                                       else if(GBFileProp.repeatName[i].substring(0,2).equals("L3"))
                                            g.setColor(GBColorSymbol.cL3);
                                            g.drawString(repeatSymbol, (int)(basestart/10), GBFileProp.repeatposition);

  • How could stop this thread that calls an externall function ?

    Hi all.
    i need an help about syncronization of two thread.
    the first one is smt like that
    Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.dynamic) {                    
                                  c.adjustLayout();
                             c.repaint();
                             try {
                                  Thread.sleep(delayMillis);
                             catch (InterruptedException ex) {
                                  // ignore
              t.start();where c.adjustLayout(); & c.repaint(); are syncronized over a astructure called G using syncronized(G)
    now the second thread is:
         Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.updateVisible) {
                                  c.updateVisibleGraph();
                             try {
                                  Thread.sleep(delayMillis);
                                  Thread.yield();
                             catch (InterruptedException ex) {
                                  // ignore
              });where the function c.updateVisibleGraph(); is syncronized over G as well. the problem is that this function, takes seconds, and block thread A and B (both of them ar suyncronized, so if B is running A cannot run).
    how can i stop c.updateVisibleGraph(); in the middle of the exectuion or each 50ms.
    is this possible?
    thanks
    Edited by: ELStefen on 26-ago-2010 16.08
    Edited by: ELStefen on 26-ago-2010 16.11

    isocdev_mb wrote:
    Using a synchronized-block is not designed to give up the lock for little while, it holds the lock until the block ends. Your requirement needs a far more fine-grained approach, quite different from your sketched implementation.
    It would involve quite an amount of guessing of what's behind the G and c your mentioning to suggest a way out. Please elaborate on what you're trying to achieve so that we can suggest how to do that...
    P.S. this forum likes problems to come with a simple working example, which you did not provide and a description of what you'd like to achieve, some context.as i thought, damn.
    Well give a working example is quite complex for the time being. Is a big project and take out this part is quite complex. But i can explain the goal.
    Practically there's a Graph (G)
    this graph is used by 2 thread, one is the update the edges and vertices, adding and removing them. the other one thread is the painter of the graph.
    the problem is when the first thread is updating the structure of G, sometimes this operation takes time (seconds) and being synchronized on G it blocks the paint thread as well.
    the thing that i would like to have is keep the painting working each tot millisecond. the updating thread works when necessary. if the update operation takes to long, it has to be stopped in the middle (and it has to restart after the paint) in a way that the paint thread can be executed.
    as the code is, and as you said, synchronizing the entire block code cannot works as i want.
    is this more clear? any clue about how can i solve this?
    many thanks
    Edited by: ELStefen on 27-ago-2010 12.43

  • Recursive Solution to Iteration

    hey there guys, i have a problem here that i'm dealing with and i can't tackle it.
    basically i need to change the code in this program so that it creates the snowflakes thorugh iteration and not recursion. Can anyone help?
    import java.applet.Applet ;
        import java.awt.* ;
        import java.lang.Math ;
        import java.util.Random;
    public class Blizzard extends Applet   {
          Graphics graph;
       public void drawStar( int x, int y, int size )   {
               int endX ;
          int endY ;
          int endSize;
                if ( size <= 2 ) return;
        // Six lines radiating from (x,y)
        for ( int i = 0; i < 6; i++ )
          endX = x + (int)(size*Math.cos( (2*Math.PI/6)*i ));
          endY = y - (int)(size*Math.sin( (2*Math.PI/6)*i ));
                graph.drawLine( x, y, endX, endY );
            drawStar( endX, endY, size/3 );
      public void paint ( Graphics gr )
        graph      = gr;
        int width  = getSize().width;
        int height = getSize().height;
        int min;
        //create a random object and see with the current time
        Random rand = new Random(System.currentTimeMillis());
        setBackground( Color.white );
        gr.setColor  ( Color.blue  );
        //create a blizzard
        int numberOfFlakes = rand.nextInt(50);
           for (int i = 0; i < numberOfFlakes; i++){
                   int x    = rand.nextInt( width);
               int y    = rand.nextInt( height);
             int size = rand.nextInt( 40 );
                        if (size > 30)
                     gr.setColor(Color.blue);
                      else if (size > 20 && size <=30)
                         gr.setColor(Color.red);
                        else
                     gr.setColor(Color.green);
                     drawStar(x, y, size);
    }

    Make a diagram of how this thing executes and you should see right off that it is not as complicated as you ara trying to make it: No stack, you are in the same scope because your function is doing in-order printing in your recursive loop.
      public void drawStar( int x, int y, int size )   {
        int endX ;
         int endY ;
         int endSize;
        //if ( size <= 2 ) return; exit condition size <=2
        while (size > 2) {  //notice exit condition size <=2
          // Six lines radiating from (x,y)
          for ( int i = 0; i < 6; i++ ){
            endX = x + (int)(size*Math.cos( (2*Math.PI/6)*i ));
            endY = y - (int)(size*Math.sin( (2*Math.PI/6)*i ));
            size = size/3;
            graph.drawLine( x, y, endX, endY );

  • Painting graph from loop?

    * I am having a hard time trying to figure out why this is not working
    * the input file is single line entries (these numbers are from the file and the format)
    * 1
    * 891.67
    * 1968.12
    * 198031.88
    * 2859.79
    * 200000
    * 5.35
    * nl
    * 2
    * 882.89
    * 1976.9
    * 196054.98
    * 2859.79
    * 200000
    * 5.35
    * nl
    * 3 and so on, depending on what the other program is writing.
    * could someone please tell me why this is not painting as I expected it should?
    * right now it only paints the grid hash marks. What did I do wrong?
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.io.*;
    import javax.swing.JOptionPane;
    public class graph extends Frame
         Line2D lineu = new Line2D.Double(20, 40, 20, 300);
         Line2D linel = new Line2D.Double(370, 300, 20,300);
         Stroke drawingStroke = new BasicStroke(2);
         public static String[] aa;
         public void paint(Graphics y)
              Graphics2D graph1 = (Graphics2D)y;
         graph1.setStroke(drawingStroke);
         graph1.setPaint(Color.black);
         graph1.draw(lineu);
         graph1.setPaint(Color.black);
         graph1.draw(linel);
         for(int x = 20; x < 370; x++)
              Line2D hash = new Line2D.Double(x, 300, x, 305);
              graph1.draw(hash);
              x = x + 5;
         for(int x = 45; x < 300; x++)
              graph1.setPaint(Color.black);
              Line2D hash2 = new Line2D.Double(15, x, 20, x);
              graph1.draw(hash2);
              x = x + 5;
         try
                   File file = new File("temp.sto");
                   FileInputStream FIS = new FileInputStream(file);
                   BufferedReader BR = new BufferedReader(new InputStreamReader(FIS));
                   aa = new String[3];
                   for (int i = 0; i < aa.length; i++)
                        aa[i] = BR.readLine();
                   for (int j = 0; j < aa.length; j++)
                             int month = Integer.parseInt(aa[j]);
                             int monthI = Integer.parseInt(aa[j+1]);
                             int monthPrin = Integer.parseInt(aa[j+2]);
                             int amtlft = Integer.parseInt(aa[j+3]);
                             int monthp = Integer.parseInt(aa[j+4]);
                             int totloan = Integer.parseInt(aa[j+5]);
                             int intval = Integer.parseInt(aa[j+6]);
                             System.out.println(aa[j]);
                                  graph1.setPaint(Color.red);
                                  Line2D monthID = new Line2D.Double(month+20, monthI, month+20, monthI + 5);
                             graph1.draw(monthID);
                             graph1.drawString("Monthly Interest", 50, 50);
                             graph1.setPaint(Color.green);
                                  Line2D monthPrinD = new Line2D.Double(month+20, monthPrin, month+20, monthPrin + 5);
                                  graph1.draw(monthPrinD);
                                  graph1.drawString("Monthly Principle", 50, 60);
                                  graph1.setPaint(Color.red);
                                  Line2D amtlftD = new Line2D.Double(month+20, amtlft, month+20, amtlft + 5);
                                  graph1.draw(amtlftD);
                                  graph1.drawString("Amount Left", 50, 70);
                                  graph1.setPaint(Color.black);
                                  graph1.drawString("The full loan of " + totloan + " with " + intval + "% interest", 50, 80);
                                  graph1.drawString("has a monthly payment of " + monthp, 50, 90);
                             j = j + 6;
                             if (aa[j+8]=="zzz" || aa[j+8] == "")
                                  j=100000000;
         }catch (FileNotFoundException e)
                   JOptionPane.showMessageDialog(null, "The file is not where you think it is. I can not continue.");
                   System.exit(0);
              }catch (Exception e)
         public static void main(String args[])
              Frame frame = new graph();
         frame.addWindowListener(new WindowAdapter()
         public void windowClosing(WindowEvent we)
              System.exit(0);
         frame.setSize(400, 400);
         frame.setVisible(true);
    }

    Please post code in code tags and indent it properly.

  • The selected objects cannot be joined as they are invalid objects,( Compound paths, closed paths, Text Objects, Graphs, Live Paint group). You can use Join command to connect two or more paths, paths in groups; ot to close an open path.

    Hi I was trying to join two Ractangle Tool objects but getting this type of Error in illustrator cs6 :-
    The selected objects cannot be joined as they are invalid objects,( Compound paths, closed paths, Text Objects, Graphs, Live Paint group).
    You can use Join command to connect two or more paths, paths in groups; ot to close an open path.
    Please assist me asap.

    Yes, I know this is an old post, but I’m trying to clean them up. Did you solve this problem, if so what was the solution?
    This sound like a firewall issue. I would start by disabling the firewall and seeing if you can connect. If this works then you know where the problem is,
    Garth Jones | My blogs: Enhansoft and
    Old Blog site | Twitter:
    @GarthMJ

  • Using of JLoox components in Swing/AWT Paint

    I am facing problem in using JLoox components in Swing/AWT Paint method.I am able to use the JLoox components in Constructor of Swing JFrame and facing problem while using the JLoox components in Paint method.If anybody used JLoox please suggest the way to use it.

    Yes I have used JLOOX since last 2 years.
    There is a LxGraph derived from LxAbstract and LxView derived from LxAbstractView. This LxAbstractView is in turn derived from JComponent. LxGraph is a model for LxView (same apporch like MVC). You create components (i.e. LxRectangle, LxCircle, LxLine, LxLink, etc) and add it to either graph or in view). Finally this view (i.e. LxView) is added to a java container (JPanel, JScrollBar, etc.) You cannot pass JLoox component into JFrame constructor.
    -regards,
    Pratap

  • Help Creating a Graph (of sorts) for Professional Driver Daily Logs

    Hey All!
    I'm working on a project for myself, that could go commercial if it gets as good as I'm hoping it will. This application (which I'm calling Truck Manager) will manage income and expenses, help plan trips, track trip/load information and do the US-MCSA/DOT regulated Driver's Daily Log. This log is a line graph that runs from midnight to midnight and has four lines: (1) Off Duty; (2) Sleeper Berth; (3) On Duty, Driving; and (4) On Duty, Not Driving. If anyone needs to see a paper form of this log book, just ask and I'll scan in one of my copies and post.
    Anyway, I'm using J2D to handle the log book "pages" and have already gotten the grid laid out just fine...it runs from midnight to midnight and is broken into 15-minute increments, with the four required lines described above. Now that I have that done, I've hit a logic block that is keeping me from figuring out the best and/or simplest way to log the status changes and time lines. For example, let's say that I work the following day:
    Midnight until 06:00 == off duty
    06:00 until 06:15 == on duty, not driving: performing pre-trip inspection
    06:15 until 08:00 == on duty, driving to customer to be loaded
    08:00 until 08:15 == on duty, not driving: being loaded (only required to log 15 minutes for this)
    08:15 until 09:00 == off duty (still being loaded)
    09:00 until 12:00 == on duty, driving (heading toward delivery)
    12:00 until 12:45 == off duty (lunch)
    12:45 until 15:00 == on duty, driving (heading toward delivery)
    15:00 until 15:15 == on duty, not driving (being unloaded)
    15:15 until 16:00 == off duty, (still being unloaded)
    16:00 until 20:00 == on duty, driving (heading home)
    20:00 until midnight == sleeper (ran out of hours)
    This graph would look like the following (provided each dash represents one 15-minute block:
    <pre>
    1. -----------------------| |---| |---| |---|
    2. | | | | | | | |----------------
    3. | -------| | |------------| |---------| | |----------------|
    4. |-| |-| |-|
    </pre>
    Though the above graph is crappy, it should give the idea of what needs to be done. At each change of status (i.e., from off duty to on duty, not driving) there must be a vertical line between the statuses, not going above and below like in the example above. Then, once the status changes again, the horizontal line needs to be drawn from the vertical line of the last status change to the time of the new status change and then the vertical line to the new status.
    The way the driver's daily log works is like this...When I come on duty, I am required to do a pre-trip inspection of my truck/trailer, which requires 15 minutes on duty, not driving, so I log that all at once, including the vertical line up to the 3rd line of the graph, which is on duty, driving. Then, in this example, I drive for 1.75 hours, until I arrive at my pick-up. Once I get there, I draw the horizontal line on line 3 of the graph, the vertical line down to line 4 (on duty, not driving), the 15-minute horizontal line and the vertical line up to line 1 (off duty). When I get ready to leave the pick-up after I am loaded, I draw the horizontal line across line 1, the vertical line down to line 3 and then drive until I stop.
    Other things that are desired for this graph logic is to take into account the US-MCSA/DOT regulations for drivers that state the following:
    a. A driver may not be on duty for more than 14 hours, without a 10-hour break
    - Nothing stops this "14-hour clock" except a 10-hour break, so if a driver comes on duty at 06:00 and spends 15 minutes doing the pre-trip inspection and then goes off duty for the next 8 hours, the 14-hour clock is still running and the driver will only have 5 hours and 45 minutes to work (roughly).
    b. A driver may not drive for more than 11 hours, without a 10-hour break, provided the 14-hour rule is obeyed.
    - In other words, even if a driver only drives for a total of 7 hours, but the 14-hour clock expires, the driver may not complete his/her 11 hours of driving allowed.
    c. A driver must take a break of 10 consecutive hours in each 24-hour period.
    *** This is confusing because the 10-hour break can span midnight and still be considered consecutive, even though part of the break is on one graph and the other part is on another graph.
    In taking these rules into account, I would like the graphing part of the program's logic to change the horizontal line color from blue (the regular line color) to red if the driver is in violation of the rules above. Where this gets really complicated is where the same status crosses midnight from day-to-day.
    As I said, I have successfully gotten the grid painted using java.awt.Graphics2D methods, but am having trouble coming up with the logic for drawing the driver status throughout the day. All data will be stored in a MySQL database table and can be pulled at any time that it is needed. The user will be entering the current status change time, as well as location (city and state) and a comment (which is not required, except for when doing a pre-trip inspection, fueling, loading or unloading), then clicking a button labeled "Update Log".
    Any help with the logic for this part of the application is greatly appreciated. If you can provide sample code to help demonstrate the logic you are describing, I will be grateful.
    Thank you all for your assistance. If you would like a better idea of what the daily log graph looks like, you can run the class below.
    Cheers,
    Sean
    <pre>
    * DriverLog.java: Driver's Daily Log entry screen. By completing the small form at the bottom of
    * dialog, the system will automatically update your log.
    * Created on Sep 30, 2010, 2:03:18 PM
    package net.pekinsoft.trkmgr.gui;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Toolkit;
    * @author Sean Carrick
    public class DriverLog extends javax.swing.JFrame {
    // Private class-level variables.
    * @code{java.awt.Graphics2D} object that we will use for drawing on our
    * view port, which is a @code{javax.swing.JPanel} on our form. This view
    * port will hold our driver's log graph that shows the driver's status at
    * different times of the day based upon the data the driver provides.
    private Graphics2D canvas;
    * @code{java.awt.geom.Point} object to hold the starting x, y coordinates
    * for the driver's daily log off duty line.
    private Point offDutyStartPoint;
    * @code{java.awt.geom.Point} object to hold the ending x, y coordinates
    * for the driver's daily log off duty line.
    private Point offDutyEndingPoint;
    * @code{java.awt.geom.Point} object to hold the starting x, y coordinates
    * for the driver's daily log sleeper berth line.
    private Point sleeperStartPoint;
    * @code{java.awt.geom.Point} object to hold the ending x, y coordinates
    * for the driver's daily log sleeper berth line.
    private Point sleeperEndingPoint;
    * @code{java.awt.geom.Point} object to hold the starting x, y coordinates
    * for the driver's daily log driving line.
    private Point drivingStartPoint;
    * @code{java.awt.geom.Point} object to hold the ending x, y coordinates
    * for the driver's daily log driving line.
    private Point drivingEndingPoint;
    * @code{java.awt.geom.Point} object to hold the start x, y coordinates
    * for the driver's daily log not driving line.
    private Point notDrivingStartPoint;
    * @code{java.awt.geom.Point} object to hold the ending x, y coordinates
    * for the driver's daily log not driving line.
    private Point notDrivingEndingPoint;
    * @code{int} that holds the number of 15-minute blocks in a 24-hour period.
    private static final int qtrHourBlocks = (24 * 60) / 15;
    /** Creates new form DriverLog */
    public DriverLog() {
    // Initialize the window's components. {handled by NetBeans}
    initComponents();
    // Center the window on the screen.
    Toolkit tk = Toolkit.getDefaultToolkit();
    int winX = (tk.getScreenSize().width - getWidth()) / 2;
    int winY = (tk.getScreenSize().height - getHeight()) / 2;
    setLocation(winX, winY);
    // Initialize our drawing canvas.
    canvas = (Graphics2D) viewPort.getGraphics();
    // Next, we need to initialize our line starting and ending point objects.
    int qtr = (viewPort.getHeight() / 8);
    int y = qtr + 20;
    int startX = 20;
    int endX = viewPort.getWidth() - 20;
    offDutyStartPoint = new Point(startX, y);
    offDutyEndingPoint = new Point(endX, y);
    y = (qtr * 2) + 20; // Double the value of y
    sleeperStartPoint = new Point(startX, y);
    sleeperEndingPoint = new Point(endX, y);
    y = (qtr * 3) + 20; // Triple the value of y.
    drivingStartPoint = new Point(startX, y);
    drivingEndingPoint = new Point(endX, y);
    y = (qtr * 4) + 20; // Quadruple the value of y.
    notDrivingStartPoint = new Point(startX, y);
    notDrivingEndingPoint = new Point(endX, y);
    // Now that our objects have been initialized, we need to draw our grid.
    paint();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    bgrpStatus = new javax.swing.ButtonGroup();
    viewPort = new javax.swing.JPanel();
    lblStatusChange = new javax.swing.JLabel();
    txtStatusChange = new javax.swing.JFormattedTextField();
    rbtnOffDuty = new javax.swing.JRadioButton();
    rbtnSleeper = new javax.swing.JRadioButton();
    rbtnDriving = new javax.swing.JRadioButton();
    rbtnNotDriving = new javax.swing.JRadioButton();
    btnUpdate = new javax.swing.JButton();
    lblComment = new javax.swing.JLabel();
    txtComment = new javax.swing.JTextField();
    lblLocation = new javax.swing.JLabel();
    txtLocation = new javax.swing.JTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Driver's Daily Log");
    setAlwaysOnTop(true);
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowOpened(java.awt.event.WindowEvent evt) {
    formWindowOpened(evt);
    addWindowStateListener(new java.awt.event.WindowStateListener() {
    public void windowStateChanged(java.awt.event.WindowEvent evt) {
    formWindowStateChanged(evt);
    javax.swing.GroupLayout viewPortLayout = new javax.swing.GroupLayout(viewPort);
    viewPort.setLayout(viewPortLayout);
    viewPortLayout.setHorizontalGroup(
    viewPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 674, Short.MAX_VALUE)
    viewPortLayout.setVerticalGroup(
    viewPortLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGap(0, 351, Short.MAX_VALUE)
    lblStatusChange.setText("Status Change Time:");
    txtStatusChange.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
    new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("HH:mm"))));
    bgrpStatus.add(rbtnOffDuty);
    rbtnOffDuty.setSelected(true);
    rbtnOffDuty.setText("Off Duty");
    bgrpStatus.add(rbtnSleeper);
    rbtnSleeper.setText("Sleeper");
    bgrpStatus.add(rbtnDriving);
    rbtnDriving.setText("Driving");
    bgrpStatus.add(rbtnNotDriving);
    rbtnNotDriving.setText("On Duty; Not Driving");
    btnUpdate.setMnemonic('U');
    btnUpdate.setText("Update Driver Log");
    btnUpdate.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    btnUpdateActionPerformed(evt);
    lblComment.setText("Reason/Comment:");
    lblLocation.setText("Location: City, ST:");
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(viewPort, javax.swing.GroupLayout.DEFAULT_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(lblLocation)
    .addComponent(lblStatusChange))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(txtStatusChange, javax.swing.GroupLayout.PREFERRED_SIZE, 50,
    javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(18, 18, 18)
    .addComponent(rbtnOffDuty)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(rbtnSleeper)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(rbtnDriving)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(rbtnNotDriving)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
    65, Short.MAX_VALUE)
    .addComponent(btnUpdate))
    .addGroup(layout.createSequentialGroup()
    .addComponent(txtLocation, javax.swing.GroupLayout.DEFAULT_SIZE,
    232, Short.MAX_VALUE)
    .addGap(18, 18, 18)
    .addComponent(lblComment)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(txtComment, javax.swing.GroupLayout.PREFERRED_SIZE,
    227, javax.swing.GroupLayout.PREFERRED_SIZE)))))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(viewPort, javax.swing.GroupLayout.DEFAULT_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(lblStatusChange)
    .addComponent(txtStatusChange, javax.swing.GroupLayout.PREFERRED_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(rbtnOffDuty)
    .addComponent(rbtnSleeper)
    .addComponent(rbtnDriving)
    .addComponent(rbtnNotDriving)
    .addComponent(btnUpdate))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(txtComment, javax.swing.GroupLayout.PREFERRED_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(lblComment)
    .addComponent(lblLocation)
    .addComponent(txtLocation, javax.swing.GroupLayout.PREFERRED_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // KEEP AS LAST LINE IN THIS FUNCTION!!! //
    paint();
    private void formWindowStateChanged(java.awt.event.WindowEvent evt) {                                       
    // Draw the driver's daily log grid.
    paint();
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
    // Draw the driver's daily log grid.
    paint();
    private void paint() {
    drawOutline();
    * @code{net.pekinsoft.gui.DriverLog.drawOutline()} function handles the
    * rendering of the driver's daily log grid outline only.
    private void drawOutline() {
    // Set up the starting point for our log grid's upper-left corner.
    int x = 0; // 20 points down from the top.
    int y = 0; // 20 points in from the left.
    int offset = 28;
    // Get the height and width of our log grid from the panel.
    int h = 112;
    int w = 671;
    // Set the color of our border to Red.
    canvas.setStroke(new BasicStroke(1));
    canvas.setPaint(Color.BLACK);
    // Draw our log graph outline.
    canvas.drawRect(x, y, w, h);
    // Draw our log's horizontal lines.
    for ( int i = 1; i < 5; i++ ) {
    canvas.drawLine(x, y + (i * offset), w + offset, y + (i * offset));
    // Draw our log's hour lines.
    for ( int i = 1; i < 24; i++ ) {
    canvas.drawLine(x + (i * offset), 0, x + (i * offset), 112);
    // Draw our log's 30-minute ticks.
    for ( int i = 1; i < 48; i++ ) {
    for ( int j = 0; j < 5; j++ ) {
    canvas.drawLine(x + (i * (offset / 2)), y + (j * offset),
    x + (i * (offset / 2)), (y + (j * offset) + 10));
    // Draw our log's 15-minute ticks.
    for ( int i = 1; i < 96; i++ ) {
    for ( int j = 0; j < 5; j++ ) {
    canvas.drawLine(x + (i * (offset / 4)), y + (j * offset),
    x + (i * (offset / 4)), (y + (j * offset) + 5));
    canvas.drawLine(0, 112, 0, 122);
    canvas.drawLine(w, 112, w, 122);
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new DriverLog().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.ButtonGroup bgrpStatus;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JLabel lblComment;
    private javax.swing.JLabel lblLocation;
    private javax.swing.JLabel lblStatusChange;
    private javax.swing.JRadioButton rbtnDriving;
    private javax.swing.JRadioButton rbtnNotDriving;
    private javax.swing.JRadioButton rbtnOffDuty;
    private javax.swing.JRadioButton rbtnSleeper;
    private javax.swing.JTextField txtComment;
    private javax.swing.JTextField txtLocation;
    private javax.swing.JFormattedTextField txtStatusChange;
    private javax.swing.JPanel viewPort;
    // End of variables declaration
    </pre>
    Edited by: 799477 on Oct 1, 2010 2:42 PM

    <blockquote>Sean, I checked your code and seen that package net.pekinsoft..., is this an Illinois Company by any chance?</blockquote>
    Yes, this is a company that I have tried (unsuccessfully) to start in central Illinois...I'm guessing that the "Pekin" part gave it away.
    <blockquote>Thanks for posting the DB TABLE -- we'll need that later, plus I wanted to see if you would respond.</blockquote>
    Not a problem on the DB table. Why wouldn't I respond...I want and NEED help here... ;-)
    <blockquote>I have a few questions but don't want to complicate your line of thinking, so I'll just describe generally how I have approached a big project like this. </blockquote>
    I will answer them the best that I can.
    <blockquote>For one thing, I do not start with a GUI or even consider what I want it to look like... I start with the data, and how that data is broken down into different classes, and then how those classes come together to form an Object Hierarchy. I have and do maintain a large MySQL database myself with 18 TABLES. Some of the TABLES hold very little information which I use as static final information. As a matter of fact, one of those TABLES is called status and contains 5 fields. This status TABLE is storing 7 rows of information because I have 7 different levels. The fields in my status TABLE are status_id, status_type, status_title, status_desc, and status_icon. This means I will have 7 icons to represent the different status levels, a description, a title, a type (maybe yours could be ON or OFF duty for example), and the ID of the status.
    Another thing at this stage of development is that I don't make up my mind concretely about any of the data or how the data will fit together. I want to remain as flexible as possible, so that as my design develops, the design allows for the addition or subtraction of data and different data types to be created. In other words, I completely atomize all structure, associations, relationships, dependencies, or just anything in general that makes two or more pieces of information stick together.
    At this point, all I have is a loose bag of primitive data types with no structure whatsoever. Like I just tore up a piece of paper into a hundred pieces and threw into the air letting the pieces fall where they may.
    While I'm at this point, I will make decisions about which languages and platform would be the best to raise the beast. In my case, I chose to run it on the internet, so I chose MySQL to store the data, SQL to communicate to the DB, and the server uses a PHP scripting engine to spit out the HTML, also PHP lets me create OO classes very similar to a JAVA class. This is a very important step and must be made now, not later -- you don't want to do all this work only to find out that it should have been done in another language! Been there done that.
    Once I've decided all of the above, then I come back and decide how the data should be organized. NOW I make all the database TABLES. Then I write a class definition for each of the db tables. Each class will provide methods for saving, editing, and retrieving info to and from the db using SQL.
    Once I get to this point I will make FORMS for the easy entry of data. The FORMS, CLASSES and and db TABLES all mirror each other now, so the CLASSES handle all the info from FORM to DB, DB to FORM. Notice at this point I am still dealing with data and data flow, NOT the display of pretty information -- not even close.
    Ok, enough about this Sean, let me know if this helps any.</blockquote>
    This information was helpful, but also how I typically approach a large project.
    The only problem with what you talk about above is dealing with allowing "wiggle-room" for changing the data because the data that I'm storing is codified by the federal government through the CSA-2010 laws that regulate the trucking industry. Therefore, I really don't have any wiggle-room with the data at all.
    As for choosing Java over another language, I made this choice because I don't like limiting myself (or others) on what operating system they use and platform-independence is one of the best things about Java (provided you don't use any OS-specific code, which I try like hell not to do). I am a huge Linux guy, but have to use Windows to update my GPS and would like to be able to use this application no matter which OS I'm booted into. Just so you understand, I am fluent in multiple languages, including PHP, Java, Python, Ruby, C/C++, BASIC and Bash. I am also very big on OOP and always leave accessing the database to the class that holds that data (i.e., LogEntry class will access the database to store and retrieve the log data). I am also using MySQL as the database back-end, because it is the SQL server that I am most comfortable with and also has versions for various OSes. I use the mysql-connector.jar library for accessing MySQL from Java, so that's not even an issue.
    As for "static final" data in the database, I do store my statuses, with the status_id numbers the same as the row number on the hard-copy Driver's Daily Log books. These records simply hold the status_id and description (i.e., 1, "Off Duty").
    I believe that I've got the logic for logging an entry such as: 08:00-10:00, On Duty, Driving, status location Indianapolis, IN, comment: Tire check. This whole entry is on the same day and therefore fairly easy to graph. The type of entry that I'm having problems figuring the logic for is one where the last change of duty status was before midnight and the current change of duty status is after midnight, on the next day. For example, I typically stop for the night (my DOT 10-hour break) at 5:00 PM (17:00) and am in the sleeper across midnight, then get going at 3:00 AM (03:00). I'm having trouble figuring out how many hours to log on the current day. In the example that I just gave, I'm not getting how I can figure out when to start at midnight and when to start out at the prior status change time through code. Nothing that I try seems to work correctly and I keep getting horizontal status lines outside of my graph area.
    As for what data I need to store and how I need to store it, I am very flexible, except with the daily log data, since it is federally mandated. Once I figure out the logic for actually logging the statuses and changes of status properly, I will create the class for storing and retrieving the database data...for now I'm just using hard-coded times to get the graphing logic right without the overhead of database access. Changing this code to use the data from the database will be a snap in comparison to figuring out the graphing functionality.
    Thanks for your insights and assistance. I look forward to seeing what other ideas you have to share.
    Sean

  • Panel is not getting refreshed.i see a jam of old and new graph and lines

    hi friends
    i am attaching my code .when i adjust the slider position the size of the graph will increase(scaling).when i scroll to see the entire graph the screen is not getting refreshed properly.
    no leads ..can be 3,12 ...try any arbitary ...(stored in a txt file)
    myfile.txt=consider some 600 random numbers for testing.
    public class ECGDisplay extends JFrame implements WindowListener
          Container contain;
          JSlider sliderX,sliderY,sliderCount;
          JTextField Xval,Yval,Count;
          int [] time=new int[600];
          int []Volt=new int[600];
         Simpanel[] panelname;
          float relX=1;
          float relY=1;
          LineBorder lineborder,lineborder1;
          JPanel ScalingAdjustersPanel,ECGDisplayPanel;
          JScrollPane Scroll;
          JViewport vp;
          JRadioButton RbX,RbY,RbCount;
          ButtonGroup group;
          private FileInputStream in;
          String horizontalScalingSliderLabel = "mm/S";
          String verticalScalingSliderLabel = "mm/mV";
          String heightOfTileSliderLabel ="Height of tile in uV";
          boolean flag=false;
          int LeadCount;
          int x=20,y=15;
          int count=4;
          JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
          java.awt.Dimension screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    public ECGDisplay()
         super();     
         this.setTitle("ECG FRAME");
         this.addWindowListener(this);
         this.setSize (screen.width, screen.height);
         contain=getContentPane();
         EcgLeadCount();
         EcgWindowCreation(LeadCount);
    void  EcgLeadCount( )
              try
               FileInputStream in = new FileInputStream("no_Leads.txt");
               BufferedReader br = new BufferedReader(new InputStreamReader(in));
               LeadCount=Integer.parseInt(br.readLine());
               in.close();
               catch (Exception e)
                 System.err.println ("Error while reading no of leads");
    void PanelAdjuster()
              for(int i=0;i<LeadCount;i++)
              panelname.setPreferredSize(new Dimension((30*x),(count*y)));
    void readMyFile(int i)
              try
              FileInputStream in = new FileInputStream("myfile.txt");
              BufferedReader br = new BufferedReader(new InputStreamReader(in));
              String strLine;
              for (int j = 0; j < Volt.length; j++)
                   Volt[j] = Integer.parseInt(br.readLine());
                   in.close();
              catch (Exception e)
                   System.err.println ("Error writing to file");
    public void EcgWindowCreation(int LeadCount)
         for(int i=0;i<600;i++)
              time[i]=i;
              ScalingAdjustersPanel=new JPanel();
              ECGDisplayPanel=new JPanel();
              panelname=new Simpanel[LeadCount];
              for(int i=0;i<LeadCount;i++)
                   panelname[i] =new Simpanel();
                   System.out.println(panelname[i]);
                   readMyFile(i);
                   ECGDisplayPanel.add(panelname[i]);
              ScalingAdjustersPanel.setPreferredSize(new Dimension(200,(screen.height-50)));
              ScalingAdjustersPanel.setLayout(new BoxLayout(ScalingAdjustersPanel,BoxLayout.Y_AXIS));
              ECGDisplayPanel.setLayout(new BoxLayout(ECGDisplayPanel,BoxLayout.Y_AXIS));
         sliderX=new JSlider(10,50,20);
         sliderY=new JSlider(15,50,15);
              sliderCount=new JSlider(4,10,4);
              ScalingAdjustersPanel.add(sliderCount);
              sliderCount.setBorder(BorderFactory.createTitledBorder("uV"));
              sliderCount.setMajorTickSpacing(2);
              sliderCount.setMinorTickSpacing(1);
              sliderCount.setPaintTicks(true);
              sliderCount.setPaintLabels(true);
              sliderCount.setVisible(false);
              sliderCount.addChangeListener(new SliderChange());     
              ScalingAdjustersPanel.add(sliderX);
              sliderX.setBorder(BorderFactory.createTitledBorder(horizontalScalingSliderLabel));
              sliderX.setMajorTickSpacing(10);
              sliderX.setMinorTickSpacing(5);
              sliderX.setPaintTicks(true);
              sliderX.setPaintLabels(true);
              sliderX.addChangeListener(new SliderChange());
              sliderX.setVisible(true);
              ScalingAdjustersPanel.add(sliderY);
              sliderY.setBorder(BorderFactory.createTitledBorder(verticalScalingSliderLabel));
              sliderY.setMajorTickSpacing(10);
              sliderY.setMinorTickSpacing(5);
              sliderY.setPaintTicks(true);
              sliderY.setPaintLabels(true);
              sliderY.addChangeListener(new SliderChange());
              sliderY.setVisible(false);
              RbX=new JRadioButton ("horizontal Scaling",true);
              RbY=new JRadioButton ("vertical Scaling");
              RbCount=new JRadioButton ("height Of Tile");
              group=new ButtonGroup ();
              group.add(RbX);
              group.add(RbY);
              group.add(RbCount);
         ScalingAdjustersPanel.add(RbX);
              ScalingAdjustersPanel.add(RbY);
              ScalingAdjustersPanel.add(RbCount);
              RbX.addActionListener(new buttonSelected());
              RbY.addActionListener(new buttonSelected());
              RbCount.addActionListener(new buttonSelected());
              lineborder = new LineBorder(Color.GRAY,2,true);
              lineborder1 = new LineBorder(Color.RED,2,true);
              ScalingAdjustersPanel.setBorder(lineborder);
              JScrollPane Scroll=new JScrollPane(ECGDisplayPanel);
              contain.setLayout(new BorderLayout());
              splitPane.setOneTouchExpandable(true);
         splitPane.add(ScalingAdjustersPanel);
         splitPane.add(Scroll);
              contain.add(splitPane,BorderLayout.CENTER);     
              setVisible(true);
    public void windowClosing(WindowEvent evt)
              this.setVisible(false);
              this.dispose();
    public void windowOpened(WindowEvent evt) {}
    public void windowClosed(WindowEvent evt) {}
    public void windowIconified(WindowEvent evt) {}
    public void windowDeiconified(WindowEvent evt) {}
    public void windowActivated(WindowEvent evt) {}
    public void windowDeactivated(WindowEvent evt) {}          
    public class SliderChange implements ChangeListener
              public void stateChanged(ChangeEvent AE)
                   Object sliderOBJ=AE.getSource();
                   if(sliderOBJ==sliderX)
                        x= sliderX.getValue();
                        relX=(float)x/20;
                   else if (sliderOBJ==sliderY)
                        y= sliderY.getValue();
                        relY=(float)(((float)y*count)/(15*4));
                   else if(sliderOBJ==sliderCount)
                        count=sliderCount.getValue();
                        relY=(float)(((float)y*count)/(15*4));
                   PanelAdjuster();
                   ECGDisplayPanel.repaint();
                   ECGDisplayPanel.updateUI();
    public class buttonSelected implements ActionListener
         public void actionPerformed(ActionEvent e)
              JRadioButton slid1=(JRadioButton)e.getSource();
              if(slid1==RbX)
              sliderX.setVisible(true);
              sliderY.setVisible(false);
              sliderCount.setVisible(false);
              if(slid1==RbY)
              sliderX.setVisible(false);
              sliderY.setVisible(true);
              sliderCount.setVisible(false);
              if(slid1==RbCount)
              sliderX.setVisible(false);
              sliderY.setVisible(false);
              sliderCount.setVisible(true);
    public class Simpanel extends JPanel
         public void paintComponent(Graphics g)
              g.setColor(Color.BLUE);
              for(int i=0;i<599;i++)
                   g.drawLine((int)(time[i]*relX),(int)(Volt[i]*relY),(int)(time[i+1]*relX),(int)(Volt[i+1]*relY));
              Graphics2D g2=(Graphics2D) g;
         //drawing a rectangle
         double leftX=0;
         double topY=0;
              double width=x;
              double height=y;
                   g2.setColor(Color.RED);
              for(int j=0;j<=count;j++)
                   for(int i=0;i<30;i++)
                             Rectangle2D rect=new Rectangle2D.Double(leftX,topY,width,height);
                             g2.draw(rect);
                             leftX=leftX+x;
                        leftX=0;
                        topY=topY+y;
    public static void main(String args[])
              ECGDisplay frame=new ECGDisplay();
    Edited by: garlapati on Apr 7, 2009 10:18 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    From the [custom painting tutotial|http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html]:
    Most of the standard Swing components have their look and feel implemented by separate "UI Delegate" objects. The invocation of super.paintComponent(g) passes the graphics context off to the component's UI delegate, which paints the panel's background. For a closer look at this process, see the section entitled "Painting and the UI Delegate" in the aforementioned SDN article.

Maybe you are looking for