MouseEvent in Line-DragKing

hai,
In the following code if Frame is replaced by JFrame
it is not painted properly.
Leave the exceptions.
I want to implement the same using JFrame
Thanks in advance
anu
---------Start--DragKing.java---------
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class DragKing
extends Frame //javax.swing.JFrame
implements MouseListener, MouseMotionListener {
protected Point2D[] mPoints;
protected Point2D mSelectedPoint;
public DragKing() {
super("DragKing v1.0");
createUI();
wireEvents();
protected void createUI() {
setSize(300, 300);
setLocation(100, 100);
setVisible(true);
mPoints = new Point2D[9];
// Cubic curve.
mPoints[0] = new Point2D.Double(50, 75);
mPoints[1] = new Point2D.Double(100, 100);
mPoints[2] = new Point2D.Double(200, 50);
mPoints[3] = new Point2D.Double(250, 75);
// Quad curve.
mPoints[4] = new Point2D.Double(50, 175);
mPoints[5] = new Point2D.Double(150, 150);
mPoints[6] = new Point2D.Double(250, 175);
// Line
mPoints[7] = new Point2D.Double(50, 275);
mPoints[8] = new Point2D.Double(250, 275);
mSelectedPoint = null;
protected void wireEvents() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
addMouseListener(this);
addMouseMotionListener(this);
public void paint(Graphics g) { paint((Graphics2D)g); }
public void paint(Graphics2D g) {
g.setPaint(Color.black);
// Draw the cubic curve.
CubicCurve2D c = new CubicCurve2D.Float();
c.setCurve(
mPoints[0].getX(), mPoints[0].getY(),
mPoints[1].getX(), mPoints[1].getY(),
mPoints[2].getX(), mPoints[2].getY(),
mPoints[3].getX(), mPoints[3].getY());
g.draw(c);
// Draw the quadratic curve.
QuadCurve2D q = new QuadCurve2D.Float();
q.setCurve(
mPoints[4].getX(), mPoints[4].getY(),
mPoints[5].getX(), mPoints[5].getY(),
mPoints[6].getX(), mPoints[6].getY());
g.draw(q);
// Draw the line.
Line2D l = new Line2D.Float();
l.setLine(
mPoints[7].getX(), mPoints[7].getY(),
mPoints[8].getX(), mPoints[8].getY());
g.draw(l);
for (int i = 0; i < mPoints.length; i++) {
// If the point is selected, use the selected color.
if (mPoints[i] == mSelectedPoint)
g.setPaint(Color.red);
else
g.setPaint(Color.blue);
// Draw the point.
g.fill(getControlPoint(mPoints));
protected Shape getControlPoint(Point2D p) {
// Create a small square around the given point.
int side = 4;
return new Rectangle2D.Double(
p.getX() - side / 2, p.getY() - side / 2,
side, side);
public void mouseClicked(MouseEvent me) {}
public void mousePressed(MouseEvent me) {
mSelectedPoint = null;
for (int i = 0; i < mPoints.length; i++) {
Shape s = getControlPoint(mPoints[i]);
if (s.contains(me.getPoint())) {
mSelectedPoint = mPoints[i];
break;
repaint();
public void mouseReleased(MouseEvent me) {}
public void mouseMoved(MouseEvent me) {}
public void mouseDragged(MouseEvent me) {
if (mSelectedPoint != null) {
mSelectedPoint.setLocation(me.getPoint());
repaint();
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public static void main(String[] args) {
new DragKing();
---------End--DragKing.java---------

hai,
I got it.
the pbm is I've not called super.paint() in my paint md.
anu

Similar Messages

  • Problem with line clipping.

    Hi,
    In my applications there are various shapes and there is a Line Handle
    associated with every shape. That line handle's initial point is center of
    the shape and the end point is outside the shape.
    I am using g2d.clip() method to clip the line inside the shape so that
    Line shouldn't be visible from the center but from surface of the shape.
    My problem is that the line sometimes isn't visible ,specially if center point's x or y is same as line end points x or y.
    This is because of are clipping .
    Can anybody tell me how to negate this problem?
    I am posting small program to demonstrate the issue;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Area;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class EllipseDraw
    extends JPanel
    implements MouseMotionListener
         Line2D line = new Line2D.Double(new Point2D.Double(75, 75), new Point2D.Double(150, 60));
         Ellipse2D ellipse = new Ellipse2D.Double(50, 50, 50, 50);
         EllipseDraw()
              this.addMouseMotionListener(this);
         public static void main(String[] args)
              EllipseDraw ellipseDraw = new EllipseDraw();
              ellipseDraw.setBorder(BorderFactory.createRaisedBevelBorder());
              JFrame frame = new JFrame();
              frame.getContentPane().add(ellipseDraw);
              frame.setSize(300, 300);
              frame.setVisible(true);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              g2d.setStroke(new BasicStroke(2));
              Map renderHints = new HashMap();
              renderHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              renderHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
              g2d.setRenderingHints(renderHints);
              g2d.setPaint(Color.red);
              Area area = null;
              g2d.draw(ellipse);
              Shape currentClip = g2d.getClip();
              if (!ellipse.contains(line.getP2()))
                   area = new Area(line.getBounds2D());
                   area.subtract(new Area(ellipse));
                   g2d.clip(area);
                   g2d.draw(line);
                   g2d.setClip(currentClip);
              if (area != null)
                   g2d.draw(area);
         public void mouseDragged(MouseEvent e)
         public void mouseMoved(MouseEvent e)
              line.setLine(line.getP1(), e.getPoint());
              this.invalidate();
              this.repaint();
    }

    I solved the problem by growing the area .
    if (!ellipse.contains(line.getP2()))
                   Rectangle rect = line.getBounds();
                   rect.grow(10, 10);
                   area = new Area(rect);
                   area.subtract(new Area(ellipse));
                   g2d.clip(area);
                   g2d.draw(line);
                   g2d.setClip(currentClip);
              }

  • Draw line by dragging...

    I am trying to draw straight lines(by dragging the mouse) on the content pane of my internal frame. I have managed to get the line drawn... with 2 problems.
    1) really bad flicker while dragging
    2) when i try to draw the second line, the first line disappears.(due to the repaint I am currently using, I think)
    Could someone please help? thanks!
    Here is the code I,m using...
    private Point fp;
    contentpane.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                fp = e.getPoint();
                public void mouseReleased(Mouse Event e) {
                Graphics g = contentpane.getGraphics();
                g.setColor(Color.black);
                g.drawLine(fp.x, fp.y, e.getX(), e.getY());
    contentpane.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(MouseEvent e) {
                Graphics g = contentpane.getGraphics();
                g.setColor(Color.black);
                g.drawLine(fp.x, fp.y, e.getX(), e.getY());
                contentpane.repaint();

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Vector;
    public class Test extends JFrame {
      int[] line;
      int[] tmpLine = new int[4];
      boolean mouseDown=false;
      long lastDrawTime = 0;
      Vector lines = new Vector();
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent me) {
         line = new int[4];
         tmpLine[0]=line[0]=me.getX();
         tmpLine[1]=line[1]=me.getY();
         mouseDown=true;
          public void mouseReleased(MouseEvent me) {
         tmpLine[2]=line[2]=me.getX();
         tmpLine[3]=line[3]=me.getY();
         lines.add(line);
         repaint();
         mouseDown = false;
        addMouseMotionListener(new MouseMotionAdapter() {
          public void mouseDragged(MouseEvent me) {
         if (System.currentTimeMillis() - lastDrawTime > 100) {
           lastDrawTime = System.currentTimeMillis();
           tmpLine[2] = me.getX();
           tmpLine[3] = me.getY();
           repaint();
        setSize(200,200);
        show();
      public static void main(String[] args) {
        new Test();
      public void paint(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0,0, getWidth(), getHeight());
        g.setColor(Color.black);
        for (int x=0; x<lines.size(); x++) {
          int[] aLine = (int[])lines.get(x);
          g.drawLine(aLine[0],aLine[1],aLine[2],aLine[3]);
        if (mouseDown) {
          g.setColor(Color.cyan);
          g.drawLine(tmpLine[0], tmpLine[1], tmpLine[2], tmpLine[3]);

  • How to use interactive-fullscreen instead of fullscreen in Spark videoPlayer?

    Hi All,
    I'm trying the new videoPlayer component in Flash builder and want to use it in AIR application.
    When i press the fullscreen button i get into regular fullscreen (with no keyboard).
    Is there a way i can get into interactive fullscreen when pushing the videoPlayer fullscreen button?
    Thanks in advance,
    Lior

    Have a look at the code for the VideoPlayer.as its not that straight forward to override the behaviour.
    fullScreenButton_clickHandler(event:MouseEvent):void (line 1808 in latest sdk)
    there is a note inside the source - maybe raising a request on the adobe bug site for the SDK would be a good idea..
               // FIXME (rfrishbe): Should we make this FULL_SCREEN_INTERACTIVE if in AIR?
                systemManager.stage.displayState = StageDisplayState.FULL_SCREEN; (line 1872)

  • Adding dynamic components

    i have a frame cannot be resized. i have used box layout as the top level layout and on that i have used five panels with components having gridbag layout. Out of five panel one panel has set visible false, which is suppsed to get visible on the trigger of a Button.
    Problem : When i m clicking the button i m setting the visibility of the panel as true... but the panel is not showing on the screen(ideally should automatically get adjusted in the screen). i have done validate(). the problem which i could fig out was that its not getting adjusted in the given size as the resizable option of the frame is set to false. Now if i increase the size of the window dynamically i m able to see the component but i m get a flicking effect in the frame. Please ... suggest me some solution that enable me to add a panel in a frame that has a rezibale switched off.
    or some way by which i can setsize the frame , add the component without a flickering effect.

    example code:
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Vector;
    public class AvoidFlicker extends Panel
    implements MouseMotionListener, MouseListener
       Vector lines = new Vector();
       int x, y;
       public AvoidFlicker()
          addMouseMotionListener (this);
          addMouseListener(this);
       public void mouseClicked  (MouseEvent e) { }
       public void mouseEntered  (MouseEvent e) { }
       public void mouseExited   (MouseEvent e) { }
       public void mouseMoved    (MouseEvent e) { }
       public void mouseReleased (MouseEvent e) { }
       public void mousePressed  (MouseEvent e)
          x = e.getX();
          y = e.getY();
       public void mouseDragged (MouseEvent e)
          lines.addElement (new Rectangle (x, y, e.getX(), e.getY()));
          x = e.getX();
          y = e.getY();
          repaint();
       protected void paintBackground (Graphics g)
          Dimension size = getSize();
          for (int y = 0; y < size.height; y += 2)
             int blue = 255 - (y % 256);
             Color color = new Color (255, 255, blue);
             g.setColor (color);
             g.fillRect (0, y, size.width, 2);
       public void paintForeground (Graphics g)
          g.setColor (Color.black);
          int numberOfPoints = lines.size();
          for (int i = 0; i < numberOfPoints; i++)
             Rectangle p = (Rectangle) lines.elementAt (i);
             g.drawLine (p.x, p.y, p.width, p.height);
       public void paint (Graphics g)
          paintBackground (g);
          paintForeground (g);
       public void update (Graphics g)
          // override to not clear the background first
          // paint (g);
          paintForeground (g);
       public static void main (String[] args)
          AvoidFlicker panel = new AvoidFlicker();
          Frame f = new Frame ("Avoiding Flicker");
          f.add ("Center", panel);
          f.setSize (300, 300);
          f.show();
    }

  • Linking Button to PDF

    Hi guys, so I am definitely new at AS3 and Flash in general, but I have to do a project for work that requires me to build a portion of a website in Flash. I need to link a button to a PDF document that will be stored on our site on the internet. So far I have been able to successfully write code that allows me to link one of the buttons:
    var pdfURL:URLRequest = new URLRequest("images/Other/LetterDaniels.pdf");
    //PDF Link
    function pdfLink(event:MouseEvent):void {
        navigateToURL(pdfURL,"_blank");
    {Text.daniels_btn.addEventListener(MouseEvent.CLICK, pdfLink);
    Then I simply copied and paste this code and change it for the second button:
    var pdfURL:URLRequest = new URLRequest("images/Other/LetterDaniels.pdf"); (line 1)
    //PDF Link (line 4)
    function pdfLink(event:MouseEvent):void {
        navigateToURL(pdfURL,"_blank");
    {Text.daniels_btn.addEventListener(MouseEvent.CLICK, pdfLink); (line 9)
    var pdfURL:URLRequest = new URLRequest("images/Other/LetterColnar.pdf");
    //PDF Link
    function pdfLink(event:MouseEvent):void { (line 16)
        navigateToURL(pdfURL,"_blank");
    {Text.colnar_btn.addEventListener(MouseEvent.CLICK, pdfLink);
    When I do so, however, I get a series of error messages:
    Scene 1, Layer 'AS', Frame 1, Line 12    1151: A conflict exists with definition pdfURL in namespace internal.
    Scene 1, Layer 'AS', Frame 1, Line 16    1021: Duplicate function definition.
    ComponentShim (Compiled Clip), Line 1    5000: The class 'fl.core.ComponentShim' must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type.
    ComponentShim (Compiled Clip), Line 1    5000: The class 'fl.containers.UILoader' must subclass 'flash.display.MovieClip' since it is linked to a library symbol of that type.
    Can someone please help me with the code so that I can get rid of these error messages? I basically need three buttons to link to three different PDF files:
    Text.daniels_btn to images/Other/LetterDaniels.pdf
    Text.colnar_btn to images/Other/LetterColnar.pdf
    Text.hansen_btn to images/Other/LetterHansen.pdf
    Thanks!!

    to keep it simple you should use three different named functions and three different named Variables:
    function pdfLink1(event:MouseEvent):void {
        navigateToURL(pdfURL1,"_blank");
    function pdfLink2(event:MouseEvent):void {
        navigateToURL(pdfURL2,"_blank");
    function pdfLink3(event:MouseEvent):void {
        navigateToURL(pdfURL3,"_blank");

  • Need More Mouse Events

    [http://forums.sun.com/thread.jspa?messageID=10811388|http://forums.sun.com/thread.jspa?messageID=10811388]
    During search over net I found the above thread and it seems to be describing the same problem which I am also facing. For my application also I need to capture all the mouse events while dragging. I tried the soluiotn mentioned at this thread to solve this problem by overrinding the below method in several ways:
    protected AWTEvent coalesceEvents(AWTEvent existingEvent,AWTEvent newEvent);
    Even after several attempts, I could not succeed. Can you please suggest how to do that. I was not able to reply to above thread so creating this new thread.
    Thanks

    I wanted to see if a timer based approach does indeed produce a smoother curve than just simply listening for mouse drag events. What I came up with below was the resulting test code. Lo and behold, using a timer does indeed produce a smoother curve. But it wasn't because it was capturing more mouse positions, it was because it was capturing less. Ain't that a kicker? Another interesting thing is that according to the source code, coalesceEvents is a no-op. The documentation, however, would have you believe that it coalesces mouse events as I thought it did.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.GeneralPath;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.BorderFactory;
    public class Test {
        private static class TimerBasedPanel extends JPanel implements MouseListener {
            private GeneralPath line;
            private Timer mousePosQuerier;
            private Component mouseEvtSource;
            private int pointCount;
            public TimerBasedPanel(Component mouseEventSource) {
                mousePosQuerier = new Timer(15, new ActionListener() {
                    Point lastMousePoint = new Point(-1, -1);
                    public void actionPerformed(ActionEvent e) {
                        Point p = MouseInfo.getPointerInfo().getLocation();
                        if (p.x != lastMousePoint.x || p.y != lastMousePoint.y) {
                            lastMousePoint.setLocation(p);
                            SwingUtilities.convertPointFromScreen(p, mouseEvtSource);
                            line.lineTo(p.x, p.y);
                            pointCount++;
                            repaint();
                mouseEvtSource = mouseEventSource;
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                if(line != null) {
                    ((Graphics2D) g).draw(line);
            public void mousePressed(MouseEvent e) {
                line = new GeneralPath();
                line.moveTo(e.getX(), e.getY());
                pointCount = 1;
                mousePosQuerier.start();
            public void mouseReleased(MouseEvent e) {
                mousePosQuerier.stop();
                repaint();
                System.out.println("Timer Based, Points Captured: " + pointCount);
            public void mouseEntered(MouseEvent e){}
            public void mouseExited(MouseEvent e){}
            public void mouseClicked(MouseEvent e){}
        private static class DragEventsPanel extends JPanel
                implements MouseListener, MouseMotionListener{
            private GeneralPath line;
            private int pointCount;
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                if(line != null) {
                    ((Graphics2D) g).draw(line);
            public void mousePressed(MouseEvent e) {
                line = new GeneralPath();
                line.moveTo(e.getX(), e.getY());
                pointCount = 1;
            public void mouseDragged(MouseEvent e) {
                pointCount++;
                line.lineTo(e.getX(),e.getY());
                repaint();
            public void mouseReleased(MouseEvent e){
                System.out.println("DragEvent Based, Points Captured: " + pointCount);
            public void mouseEntered(MouseEvent e){}
            public void mouseExited(MouseEvent e){}
            public void mouseClicked(MouseEvent e){}
            public void mouseMoved(MouseEvent e) {}
        public static void main(String args[]) {
            JFrame frame = new JFrame();
            JPanel drawPanel = new JPanel() {
                @Override
                protected AWTEvent coalesceEvents(AWTEvent existingEvent,
                                                  AWTEvent newEvent) {
                    if(newEvent.getID() == MouseEvent.MOUSE_DRAGGED) {
                        return null;
                    }else {
                        return super.coalesceEvents(existingEvent, newEvent);
            TimerBasedPanel timerPanel = new TimerBasedPanel(drawPanel);
            DragEventsPanel dragPanel = new DragEventsPanel();
            drawPanel.setBorder(BorderFactory.createTitledBorder("Draw here"));
            timerPanel.setBorder(BorderFactory.createTitledBorder("Uses a timer"));
            dragPanel.setBorder(BorderFactory.createTitledBorder("Listens for drag events."));
            drawPanel.addMouseListener(timerPanel);
            drawPanel.addMouseListener(dragPanel);
            drawPanel.addMouseMotionListener(dragPanel);
            frame.setLayout(new java.awt.GridLayout(0,3));
            frame.add(drawPanel);
            frame.add(timerPanel);
            frame.add(dragPanel);
            frame.setSize(600,200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }Edited by: Maxideon on Sep 16, 2009 9:56 PM
    Minor error, but now fixed.

  • JavaFX Update Line Chart on Tab pane

    Hi all,
    I am wondering can anybody help with this problem.
    I have an application that can create a new tab when the LineChart FXML view is called by way of onMouseClicked event from a bar graph (using scenebuilder). However, I need this Line chart to update when the user clicks a new bar on the bar graph page to show this new data.
    Initially the Line chart tab will open and display data from the first bar graph click and when I click another bar in Tab A (bar chart) if it has the same number of rows it will refresh the LineChart tab otherwise I get an error. Then if I try to load another line graph tab using a different bar graph as the source I get a child duplication error
    (So tab A has a bar graph that calls tab B to represent data as a line graph, however it wont do it more then once when there is a different number of points to show)
    (Also tab C, another Bar chart will not load a new tab) Exceptions below & Class detail below.
    I am using clear() to empty the observable list I have which is used to populate the graph and table before it reads in the new data values
    What is the proper way/ best way to dynamically add another tab and update the chart in the tab with new values? Any help would be appreciated.
    I am getting the following exceptions:
    Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 11, Size: 7
      at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
      at java.util.ArrayList.add(ArrayList.java:473)
      at com.sun.javafx.collections.ObservableListWrapper.doAdd(ObservableListWrapper.java:101)
      at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:151)
      at com.sun.javafx.collections.VetoableListDecorator.add(VetoableListDecorator.java:320)
      at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderArea.addTab(TabPaneSkin.java:854)
      at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderArea.access$500(TabPaneSkin.java:659)
      at com.sun.javafx.scene.control.skin.TabPaneSkin.addTabs(TabPaneSkin.java:276)
      at com.sun.javafx.scene.control.skin.TabPaneSkin.lambda$initializeTabListener$463(TabPaneSkin.java:357)
      at com.sun.javafx.scene.control.skin.TabPaneSkin$$Lambda$108/885312968.onChanged(Unknown Source)
      at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
      at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
      at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
      at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
      at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
      at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
      at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:155)
      at java.util.AbstractList.add(AbstractList.java:108)
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:262)
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:241)
      at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
      at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
      at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
      at javafx.event.Event.fireEvent(Event.java:198)
      at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3437)
      at javafx.scene.Scene$ClickGenerator.access$7900(Scene.java:3365)
      at javafx.scene.Scene$MouseHandler.process(Scene.java:3733)
      at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
      at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
      at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
      at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
      at com.sun.glass.ui.View.notifyMouse(View.java:925)
      at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
      at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
      at com.sun.glass.ui.win.WinApplication$$Lambda$37/1146743572.run(Unknown Source)
      at java.lang.Thread.run(Thread.java:745)
    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:263)
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:241)
      at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
      at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
      at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
      at javafx.event.Event.fireEvent(Event.java:198)
      at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3437)
      at javafx.scene.Scene$ClickGenerator.access$7900(Scene.java:3365)
      at javafx.scene.Scene$MouseHandler.process(Scene.java:3733)
      at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
      at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
      at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
      at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
      at com.sun.glass.ui.View.notifyMouse(View.java:925)
      at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
      at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
      at com.sun.glass.ui.win.WinApplication$$Lambda$37/1146743572.run(Unknown Source)
      at java.lang.Thread.run(Thread.java:745)
    Class Information:
    //Call to the Line chart graph
    n.setOnMouseClicked(new EventHandler<MouseEvent>()
                    @Override
                    public void handle ( MouseEvent e )
                        String s1 = dt.getXValue();
                        String s = s1.trim();
                        if ( baseHash.containsKey(s) )
                            String value = (String) baseHash.get(s);
                            String hashValue = value.substring(6, 38);
                            System.out.println(hashValue);
                            FXMLLineChartController.setHash(hashValue);
                             try
                                  lineTab .setText("Line Graph (Rows Read)");
                                  lineTab.setContent(FXMLLoader.load(getClass().getResource("/javafxapplication2/FXMLLineChart.fxml")));
                                  Node aNode = (Node) e.getSource();
                                  Scene scene = aNode.getScene();
                                  thisTabPane = (TabPane) scene.lookup("#tabPane");
                                  thisTabPane.getTabs().add(lineTab);
                                  selectionModel.selectLast();
                                  //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                              catch ( IOException ex )
                                  Logger.getLogger(FXMLWrittenChartController.class.getName()).log(Level.SEVERE, null, ex);
    //Line Chart controller
    //Create the Graph
        @FXML
        private LineChart barChart;
    public void populateGraph ()
            System.out.println("Populate graph Line Chart");
            final CategoryAxis xAxis = new CategoryAxis();
            final NumberAxis yAxis = new NumberAxis();
            ObservableList<XYChart.Series<String, Number>> barChartData = FXCollections.observableArrayList();
            barChartData.clear();
            baseHash.clear();
            xAxis.setLabel("Query");
            yAxis.setLabel("Number of Executions");     
            series1.setName("Data from User DB2 for Query " +getHash() );
            for ( int i = 0; i < userLine.size(); i++ )
                    System.out.println(getHash() + " Usersize = " + userLine.size() + " base size " +baseLine.size());
                    series1.getData().add(new XYChart.Data<String, Number>(userLine.get(i).getBuildNumber(), (userLine.get(i).getDYN_Num_Executions())));
            barChartData.add(series1);
            barChart.setData(barChartData);

    Hi all,
    I am wondering can anybody help with this problem.
    I have an application that can create a new tab when the LineChart FXML view is called by way of onMouseClicked event from a bar graph (using scenebuilder). However, I need this Line chart to update when the user clicks a new bar on the bar graph page to show this new data.
    Initially the Line chart tab will open and display data from the first bar graph click and when I click another bar in Tab A (bar chart) if it has the same number of rows it will refresh the LineChart tab otherwise I get an error. Then if I try to load another line graph tab using a different bar graph as the source I get a child duplication error
    (So tab A has a bar graph that calls tab B to represent data as a line graph, however it wont do it more then once when there is a different number of points to show)
    (Also tab C, another Bar chart will not load a new tab) Exceptions below & Class detail below.
    I am using clear() to empty the observable list I have which is used to populate the graph and table before it reads in the new data values
    What is the proper way/ best way to dynamically add another tab and update the chart in the tab with new values? Any help would be appreciated.
    I am getting the following exceptions:
    Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index: 11, Size: 7
      at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
      at java.util.ArrayList.add(ArrayList.java:473)
      at com.sun.javafx.collections.ObservableListWrapper.doAdd(ObservableListWrapper.java:101)
      at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:151)
      at com.sun.javafx.collections.VetoableListDecorator.add(VetoableListDecorator.java:320)
      at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderArea.addTab(TabPaneSkin.java:854)
      at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderArea.access$500(TabPaneSkin.java:659)
      at com.sun.javafx.scene.control.skin.TabPaneSkin.addTabs(TabPaneSkin.java:276)
      at com.sun.javafx.scene.control.skin.TabPaneSkin.lambda$initializeTabListener$463(TabPaneSkin.java:357)
      at com.sun.javafx.scene.control.skin.TabPaneSkin$$Lambda$108/885312968.onChanged(Unknown Source)
      at com.sun.javafx.collections.ListListenerHelper$Generic.fireValueChangedEvent(ListListenerHelper.java:329)
      at com.sun.javafx.collections.ListListenerHelper.fireValueChangedEvent(ListListenerHelper.java:73)
      at javafx.collections.ObservableListBase.fireChange(ObservableListBase.java:233)
      at javafx.collections.ListChangeBuilder.commit(ListChangeBuilder.java:482)
      at javafx.collections.ListChangeBuilder.endChange(ListChangeBuilder.java:541)
      at javafx.collections.ObservableListBase.endChange(ObservableListBase.java:205)
      at javafx.collections.ModifiableObservableListBase.add(ModifiableObservableListBase.java:155)
      at java.util.AbstractList.add(AbstractList.java:108)
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:262)
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:241)
      at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
      at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
      at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
      at javafx.event.Event.fireEvent(Event.java:198)
      at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3437)
      at javafx.scene.Scene$ClickGenerator.access$7900(Scene.java:3365)
      at javafx.scene.Scene$MouseHandler.process(Scene.java:3733)
      at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
      at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
      at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
      at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
      at com.sun.glass.ui.View.notifyMouse(View.java:925)
      at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
      at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
      at com.sun.glass.ui.win.WinApplication$$Lambda$37/1146743572.run(Unknown Source)
      at java.lang.Thread.run(Thread.java:745)
    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:263)
      at javafxapplication2.FXMLExecutionChartController$3.handle(FXMLExecutionChartController.java:241)
      at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
      at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
      at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
      at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
      at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
      at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
      at javafx.event.Event.fireEvent(Event.java:198)
      at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3437)
      at javafx.scene.Scene$ClickGenerator.access$7900(Scene.java:3365)
      at javafx.scene.Scene$MouseHandler.process(Scene.java:3733)
      at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
      at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
      at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
      at java.security.AccessController.doPrivileged(Native Method)
      at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
      at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
      at com.sun.glass.ui.View.notifyMouse(View.java:925)
      at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
      at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
      at com.sun.glass.ui.win.WinApplication$$Lambda$37/1146743572.run(Unknown Source)
      at java.lang.Thread.run(Thread.java:745)
    Class Information:
    //Call to the Line chart graph
    n.setOnMouseClicked(new EventHandler<MouseEvent>()
                    @Override
                    public void handle ( MouseEvent e )
                        String s1 = dt.getXValue();
                        String s = s1.trim();
                        if ( baseHash.containsKey(s) )
                            String value = (String) baseHash.get(s);
                            String hashValue = value.substring(6, 38);
                            System.out.println(hashValue);
                            FXMLLineChartController.setHash(hashValue);
                             try
                                  lineTab .setText("Line Graph (Rows Read)");
                                  lineTab.setContent(FXMLLoader.load(getClass().getResource("/javafxapplication2/FXMLLineChart.fxml")));
                                  Node aNode = (Node) e.getSource();
                                  Scene scene = aNode.getScene();
                                  thisTabPane = (TabPane) scene.lookup("#tabPane");
                                  thisTabPane.getTabs().add(lineTab);
                                  selectionModel.selectLast();
                                  //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                              catch ( IOException ex )
                                  Logger.getLogger(FXMLWrittenChartController.class.getName()).log(Level.SEVERE, null, ex);
    //Line Chart controller
    //Create the Graph
        @FXML
        private LineChart barChart;
    public void populateGraph ()
            System.out.println("Populate graph Line Chart");
            final CategoryAxis xAxis = new CategoryAxis();
            final NumberAxis yAxis = new NumberAxis();
            ObservableList<XYChart.Series<String, Number>> barChartData = FXCollections.observableArrayList();
            barChartData.clear();
            baseHash.clear();
            xAxis.setLabel("Query");
            yAxis.setLabel("Number of Executions");     
            series1.setName("Data from User DB2 for Query " +getHash() );
            for ( int i = 0; i < userLine.size(); i++ )
                    System.out.println(getHash() + " Usersize = " + userLine.size() + " base size " +baseLine.size());
                    series1.getData().add(new XYChart.Data<String, Number>(userLine.get(i).getBuildNumber(), (userLine.get(i).getDYN_Num_Executions())));
            barChartData.add(series1);
            barChart.setData(barChartData);

  • How to draw only straight line instead of angled one??

    Dear friends,
    I saw a very good code posted by guru here(I think is camickr),
    But I tried to change it and I hope to draw only straight line instead of angled one, can you help how to do it??
    Thanks so much.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class DrawingArea extends JPanel
         Vector angledLines;
         Point startPoint = null;
         Point endPoint = null;
         Graphics g;
         public DrawingArea()
              angledLines = new Vector();
              setPreferredSize(new Dimension(500,500));
              MyMouseListener ml = new MyMouseListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.white);
         public void paintComponent(Graphics g)
              // automatically called when repaint
              super.paintComponent(g);
              g.setColor(Color.black);
              AngledLine line;
              if (startPoint != null && endPoint != null)
                   // draw the current dragged line
                   g.drawLine(startPoint.x, startPoint.y, endPoint.x,endPoint.y);
              for (Enumeration e = angledLines.elements(); e.hasMoreElements();)
                   // draw all the angled lines
                   line = (AngledLine)e.nextElement();
                   g.drawPolyline(line.xPoints, line.yPoints, line.n);
         class MyMouseListener extends MouseInputAdapter
              public void mousePressed(MouseEvent e)
                   if (SwingUtilities.isLeftMouseButton(e))
                        startPoint = e.getPoint();
              public void mouseReleased(MouseEvent e)
                   if (SwingUtilities.isLeftMouseButton(e))
                        if (startPoint != null)
                             AngledLine line = new AngledLine(startPoint, e.getPoint(), true);
                             angledLines.add(line);
                             startPoint = null;
                             repaint();
              public void mouseDragged(MouseEvent e)
                   if (SwingUtilities.isLeftMouseButton(e))
                        if (startPoint != null)
                             endPoint = e.getPoint();
                             repaint();
              public void mouseClicked( MouseEvent e )
                   if (g == null)
                        g = getGraphics();
                   g.drawRect(10,10,20,20);
         class AngledLine
              // inner class for angled lines
              public int[] xPoints, yPoints;
              public int n = 3;
              public AngledLine(Point startPoint, Point endPoint, boolean left)
                   xPoints = new int[n];
                   yPoints = new int[n];
                   xPoints[0] = startPoint.x;
                   xPoints[2] = endPoint.x;
                   yPoints[0] = startPoint.y;
                   yPoints[2] = endPoint.y;
                   if (left)
                        xPoints[1] = startPoint.x;
                        yPoints[1] = endPoint.y;
                   else
                        xPoints[1] = endPoint.x;
                        yPoints[1] = startPoint.y;
         public static void main(String[] args)
              JFrame frame = new JFrame("Test angled lines");
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              DrawingArea d = new DrawingArea();
              frame.getContentPane().add( d );
              frame.pack();
              frame.setVisible(true);
    }

    Change the AngledLine class to store two points instead of 3 points (I would rename the class to be StraightLine). The code is much simpler because you just store the starting and ending points and you don't need to calculate the middle point.

  • How to delete the logical lines in JTextArea

    Hi all,
    Now that I know how to find the logical line count in JTextArea as
    I found the following in the forum.
    public static int getLineCount (JTextArea _textArea)
    boolean lineWrapHolder = _textArea.getLineWrap();
    _textArea.setLineWrap(false);
    double height = _textArea.getPreferredSize().getHeight();
    _textArea.setLineWrap(lineWrapHolder);
    double rowSize = height/_textArea.getLineCount();
    return (int) (_textArea.getPreferredSize().getHeight() / rowSize);
    I want to delete the 4th line to the last line and append ... at the 4th, if the getLineCount exceeds 3. Does any body know how to do so?
    The intention is for the multiline tooltip as I just want to show
    the first three logical line and ... if the string is too long.
    Thanks
    Pin

    The code looks good to me. The only thought I have is that the y coordinate for the rowThree point is wrong and is referencing row four.
    I've been playing around with using a JTextArea as a renderer for a JTable. I have it working so that "..." appear when the text exceeds 2 rows. Try clicking on "B" in the letter column and then the update cell button a few times to add text. My code is slightly different than yours.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TestTable extends JFrame
         private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         JTable table;
         Vector row;
         public TestTable()
              Object[][] data = { {"1", "A"}, {"2", "B"}, {"3", "C"} };
              String[] columnNames = {"Number","Letter"};
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              table = new JTable(model)
                   public String getToolTipText( MouseEvent e )
                        int row = rowAtPoint( e.getPoint() );
                        int column = columnAtPoint( e.getPoint() );
                        if (row == 0)
                             return null;
                        else
                             return row + " : " + column;
              table.setRowSelectionInterval(0, 0);
              table.setColumnSelectionInterval(0, 0);
              table.setRowHeight(0,34);
              table.setRowHeight(1,34);
              table.setRowHeight(2,34);
              table.setDefaultRenderer(Object.class, new TextAreaRenderer(2));
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              JPanel buttonPanel = new JPanel();
              getContentPane().add( buttonPanel, BorderLayout.SOUTH );
              JButton button2 = new JButton( "Update Cell" );
              buttonPanel.add( button2 );
              button2.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        String value = (String)table.getValueAt(row, column);
                        value += value;
                        table.setValueAt( value, row, column );
                        DefaultTableModel model = (DefaultTableModel)table.getModel();
                        model.fireTableCellUpdated(row, column);
                        table.requestFocus();
         public static void main(String[] args)
              TestTable frame = new TestTable();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
         private class TextAreaRenderer extends JTextArea implements TableCellRenderer
              public TextAreaRenderer(int displayRows)
                   setRows(displayRows);
                   setLineWrap( true );
              public Component getTableCellRendererComponent(JTable table,
                                             Object value,
                                             boolean isSelected,
                                             boolean hasFocus,
                                             int row,
                                             int column)
                   setText( value.toString() );
                   Dimension d = getPreferredSize();
                   int maximumHeight = getRows() * getRowHeight();
                   if (d.height > maximumHeight)
                        setSize(d);
                        int offset = viewToModel( new Point(d.width, maximumHeight - 1) );
                        replaceRange( "...", offset-3, getDocument().getLength() );
                   return this;
    }

  • How to draw and copy a line?

    I would like to draw a line in a XYLineChart and then copy this line, in order to get this result
    [http://s14.postimage.org/4cip47ult/A02519.png]
    First left mouse click on point 1, then second mouse click on point 2: my goal is to have now a copy (clone) of this line (same lenght, same slope) that I can place anywhere on the chart, in this example by a third left mouse click on point 3.
    How to do this?
    Here is the code to draw a line on the chart
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.chart.CategoryAxis;
    import javafx.scene.chart.LineChart;
    import javafx.scene.chart.NumberAxis;
    import javafx.scene.chart.XYChart;
    import javafx.scene.control.Label;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Line;
    import javafx.scene.shape.LineTo;
    import javafx.scene.shape.MoveTo;
    import javafx.scene.shape.Path;
    import javafx.stage.Stage;
    public class Lines extends Application {
    Path path;
    public static void main(String[] args) {
        launch(args);
    @Override
    public void start(Stage stage) {
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis(0.5, 9.5, 0.1);
        yAxis.setTickUnit(1);
        //yAxis.setPrefWidth(35);
        yAxis.setMinorTickCount(10);
        yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis) {
            @Override
            public String toString(Number object) {
                String label;
                label = String.format("%7.2f", object.floatValue());
                return label;
        final LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);
        lineChart.setCreateSymbols(false);
        lineChart.setAlternativeRowFillVisible(false);
        lineChart.setLegendVisible(false);
        XYChart.Series series1 = new XYChart.Series();
        series1.getData().add(new XYChart.Data("Jan", 1));
        series1.getData().add(new XYChart.Data("Feb", 4.5));
        series1.getData().add(new XYChart.Data("Mar", 2.5));
        series1.getData().add(new XYChart.Data("Apr", 6.5));
        series1.getData().add(new XYChart.Data("May", 4.5));
        series1.getData().add(new XYChart.Data("Jun", 8.5));
        series1.getData().add(new XYChart.Data("Jul", 6.5));
        BorderPane bp = new BorderPane();
        bp.setCenter(lineChart);
        Scene scene = new Scene(bp, 800, 600);
        lineChart.setAnimated(false);
        lineChart.getData().addAll(series1);
        Lines.MouseHandler mh = new Lines.MouseHandler( bp );
        bp.setOnMouseClicked( mh );
        bp.setOnMouseMoved( mh );
        stage.setScene(scene);
        path = new Path();
        path.setStrokeWidth(1);
        path.setStroke(Color.BLACK);
        scene.setOnMouseDragged(mh);
        scene.setOnMousePressed(mh);
        bp.getChildren().add(path);
        stage.setScene(scene);
        stage.show();
    class MouseHandler implements EventHandler< MouseEvent > {
    private boolean gotFirst    = false;
    private Line    line;
    private Pane    pane;
    private double  x1, y1, x2, y2;
    public MouseHandler( Pane pane ) {
        this.pane = pane;
    @Override
    public void handle( MouseEvent event ) {
        if( event.getEventType() == MouseEvent.MOUSE_CLICKED ) {
            if( !gotFirst ) {
                x1 = x2 = event.getX();
                y1 = y2 = event.getY();
                line = new Line( x1, y1, x2, y2 );
                pane.getChildren().add( line );
                gotFirst = true;
            else {
                line = null;
                gotFirst = false;
            else {
                if( line != null ) {
                    x2 = event.getX();
                    y2 = event.getY();
                    // update line
                    line.setEndX( x2 );
                    line.setEndY( y2 );
      }Thanks all.
    Edited by: 932518 on 16-nov-2012 1.54

    Sorry for the simplistic question - but where are the photos you are intending to add going to be coming from?
    If it is the pictures you take - then it almost seems like you need to first upload them to a cloud service like OneDrive or iCloud and then provide the URL to Google Maps

  • How to connect two JComponents with line

    Hi,
    I have GUI which draws different shapes(ovals, rectangles etc) as JComponants on a JPanel . I need to be able to select by clicking a JComponant and connect it to another JComponant on the JPanel. Once I haved established a connection I would like to be able to move the connected JComponants yet maintain the connection. Can you please look at my code and advise as to how this can be achieved.
    Thanks.
    LineSelector selector = new LineSelector(windowPanel);
    windowPanel.addMouseListener(selector);
    class windowPanel extends JPanel
    ArrayList lines;
    public windowPanel()
    lines = new ArrayList();
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.white);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    for(int j = 0; j < lines.size(); j++)
    g2.draw((Line2D) lines.get(j));
    protected void addConnectingLine(Component c1, Component c2)
    Rectangle r1 = c1.getBounds();
    Rectangle r2 = c2.getBounds();
    lines.add(new Line2D.Double(r1.getCenterX(), r1.getCenterY(),
    r2.getCenterX(), r2.getCenterY()));
    repaint();
    class LineSelector extends MouseAdapter
    windowPanel conPanel;
    Component firstSelection;
    boolean firstComponentSelected;
    public LineSelector(windowPanel cp)
    conPanel = cp;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    Component[] c = conPanel.getComponents();
    Rectangle rv = new Rectangle();
    for(int j = 0; j < c.length; j++)
    c[j].getBounds(rv);
    if(rv.contains(p))
    if(firstComponentSelected)
    conPanel.addConnectingLine(c[j], firstSelection);
    firstComponentSelected = false;
    else
    firstSelection = c[j];
    firstComponentSelected = true;
    break;
    }

    Hi,
    these threads can help you
    http://forum.java.sun.com/thread.jspa?threadID=488823&messageID=2292924
    http://forum.java.sun.com/thread.jspa?forumID=20&threadID=607264
    L.P.

  • TextLineMirrorRegions - problems if more than one in a line

    The example in the AS3.0 reference for TextLineMirrorRegions shows text elements that turn red when clicked. It works fine when each region falls on its own line. But if the line width is changed from 150 to 850, so both regions fall in the same line, only the first one turns red no matter which one you click.
    I discoverd this while writing an html parser that would underline and activate lnks (eg <a href=...>text</a>) and found that if two links were on the same line, only one is underlined and no matter which one you click you go to the link of the first. So the underlining code pasted into the example code looks like this:
            var groupVector:Vector.<ContentElement>=new Vector.<ContentElement>  ;
        groupVector.push(new TextElement("one", blackFormat)); 
        groupVector[groupVector.length-1].eventMirror=myEvent;  // underline this element when added
        groupVector.push(new TextElement(" and ", blackFormat));
        groupVector.push(new TextElement("two", blackFormat));
        groupVector[groupVector.length-1].eventMirror=myEvent;
        groupVector.push(new TextElement(" and ", blackFormat));
        groupVector.push(new TextElement("three", blackFormat));
        groupVector[groupVector.length-1].eventMirror=myEvent;
        groupVector.push(new TextElement(".", blackFormat));
    myEvent has a listener for "addedToStage" that looks like this:
    private function myHandler(event):void {
        var line:TextLine=event.target as TextLine;
        var region:TextLineMirrorRegion=line.getMirrorRegion(myEvent);
        var selected:TextElement=region.element as TextElement;
        trace("underlining " + selected.text);
        var box:Sprite = new Sprite();
        box.graphics.lineStyle(1, color, 1);
        var color=0x000000;
        box.graphics.moveTo(region.bounds.x , region.bounds.y + region.bounds.height);
        box.graphics.lineTo(region.bounds.x + region.bounds.width, region.bounds.y + region.bounds.height);
        line.addChild(box);
    With a narrow line width in the createLines function, everything works properly. But if it is widened, all three events dispatched reference the first mirror region so the word "one" gets underlined three times (the trace shows this.)
    I've inspected textLine.mirrorRegions and all three are there. When the event is triggered, the region referenced always shows nextRegion as null. I can't see anything in the event that indicates which region to act on - what am I missing? On the mouse click event, I can determine the mouse position but I still can't figure out how to get the userData (which has the href url) from the right mirror region from that (unless, I guess, I iterate through all the line's regions and inspect their bounds - but that seems like a kludge, and still doesn't help with the addedToStage event.)

    update: I have this working now my iterating through textLine.mirrorRegions on each call, but think there must be a better way. So for underlining:
                //var region:TextLineMirrorRegion=line.getMirrorRegion(dispatcher);
                for each (region in line.mirrorRegions) {
                   if (region.mirror==dispatcher) {
                        // draw the sprite
    Similarly for the link click, by looking at the region bounds and mouseEvent.localX.
    Which means the underline sprite gets drawn three times for the single line of text. I could keep track of which ones have been drawn, I guess, but is there an easier path than iteration?

  • MovieClip Filter Causing issues with EventListeners (mouseEvent.ROLL_OVER)

    Hello,
    I have been working on a flash photo gallery for the web. It loads thumbnails from an xml file into a loader which is then made the child of a movieclip.
    The thumbnails are animated and triggered with mouse events of ROLL_OVER and ROLL_OFF. I have this working, or appearing to, when the movieclip containing the loaded thumbnail has no filters applied to it.
    I want add a drop shadow on the ROLL_OVER event and remove the drop shadow on the ROLL_OFF event. I also have this working, however my problem arises when I mouse over the very edge of the movieclip. This cauese the ROLL_OVER and ROLL_OFF function to fire in rapid succession, creating a flashing dropshadow. This looks aweful and I really have no idea what would be causing this issue.
    Thanks in advance for any advice!
    Regards.

    Thanks for the reply.
    I also found it difficult to believe that the filter was causing issues with the roll over/out events. I will expand on the example code you provided so you get an idea of what I am trying to accomplish and where my issues arise.
    EDIT: I should add that the issue is only present when I tween AND add a filter. If I only add a filter or if I only tween I have no issues but the combination or adding a filter and tweening causes the OVER/OUT events to fire rapidly.
    //This code does not result in a flashing animation
    myClip.addEventListener(MouseEvent.ROLL_OVER, overClip);
    myClip.addEventListener(MouseEvent.ROLL_OUT, outClip);
    function overClip(e:MouseEvent):void
       myTween =  new Tween(myClip, "scaleX", Regular.easeOut, myClip.scaleX, 1.5 , 3, true);
       myTween =  new Tween(myClip, "scaleY", Regular.easeOut, myClip.scaleY, 1.5 , 3, true);
    function outClip(e:MouseEvent):void
       myTween =  new Tween(myClip, "scaleX", Regular.easeOut, myClip.scaleX, 1 , 3, true);
       myTween =  new Tween(myClip, "scaleY", Regular.easeOut, myClip.scaleY, 1 , 3, true);
    //However if i add these lines of code to add and remove a filter I can observe the flashing effect when the mouse is near the edge of the moveclip
    myClip.addEventListener(MouseEvent.ROLL_OVER, overClip);
    myClip.addEventListener(MouseEvent.ROLL_OUT, outClip);
    function overClip(e:MouseEvent):void
       myClip.filters = [myDropShadowFilter];
       myTween =  new Tween(myClip, "scaleX", Regular.easeOut, myClip.scaleX, 1.5 , 3, true);
       myTween =  new Tween(myClip, "scaleY", Regular.easeOut, myClip.scaleY, 1.5 , 3, true);
    function outClip(e:MouseEvent):void
       myClip.filters = [];
       myTween =  new Tween(myClip, "scaleX", Regular.easeOut, myClip.scaleX, 1 , 3, true);
       myTween =  new Tween(myClip, "scaleY", Regular.easeOut, myClip.scaleY, 1 , 3, true);
    Is there something obviously wrong with this approach to adding a filter/tweening? I am fairly new to flash.
    Thanks again!
    Message was edited by: Dafunkz

  • How to clear a line of ImageIcons like in tetris?

    If I have a JPanel with different ImageIcons in it like tetris and if the line is filled it will be removed. Does anyone know how i can redraw the area occupied by the ImageIcons? should I redraw the entire panel "down " to overlap it? Thanks

    Load your images with ImageIO.read(url_file_inputStream) to get BufferedImages.
    There are two general approaches to something like this. One is using components: JLabels
    set in a layout manager that forms a grid (eg, GridLayout or GridBagLayout). You set the
    images in the labels with setIcon(new ImageIcon(image)). To get the image to disappear use
    setIcon(null).
    The other approach is a graphic approach in which you draw everything. Here is an example
    of how you could put this together with this second approach:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class DrawingControl extends JPanel {
        BufferedImage[] images;
        boolean[] showRows;
        int size = 5;
        final int PAD = 25;
        public DrawingControl() {
            initImages();
            showRows = new boolean[size];
            for(int j = 0; j < showRows.length; j += 2)
                showRows[j] = true;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            // Draw a centered grid.
            double xInc = (double)(w - 2*PAD)/size;
            double yInc = (double)(h - 2*PAD)/size;
            g2.setPaint(Color.red);
            for(int j = 0; j <= size; j++) {
                double y = PAD + j*yInc;
                for(int k = 0; k <= size; k++) {
                    g2.draw(new Line2D.Double(PAD, y, w-PAD, y));
            for(int j = 0; j <= size; j++) {
                double x = PAD + j*xInc;
                for(int k = 0; k <= size; k++) {
                    g2.draw(new Line2D.Double(x, PAD, x, h-PAD));
            // Draw images in visible rows.
            int iw = images[0].getWidth();
            int ih = images[0].getHeight();
            for(int j = 0; j < size; j++) {
                if(!showRows[j])
                    continue;
                for(int k = 0; k < size; k++) {
                    int n = (j*size + k) % images.length;
                    int x = (int)(PAD + k*xInc + (xInc-iw)/2);
                    int y = (int)(PAD + j*yInc + (yInc-ih)/2);
                    g2.drawImage(images[n], x, y, this);
        private void initImages() {
            int s = 40, type = BufferedImage.TYPE_INT_RGB;
            images = new BufferedImage[4];
            double theta = 0;
            AffineTransform at = new AffineTransform();
            for(int j = 0; j < images.length; j++) {
                images[j] = new BufferedImage(s, s, type);
                Graphics2D g2 = images[j].createGraphics();
                g2.setBackground(Color.orange);
                g2.clearRect(0,0,s-1,s-1);
                g2.setPaint(Color.blue);
                g2.drawRect(0,0,s-1,s-1);
                g2.setStroke(new BasicStroke(4f));
                at.setToRotation(theta, s/2, s/2);
                g2.setTransform(at);
                g2.setPaint(Color.green.darker());
                g2.drawLine(10,s/2,s/2,s-10);
                g2.drawLine(s/2,s-10,s-10,s/2);
                g2.dispose();
                theta += Math.PI/2;
        public static void main(String[] args) {
            DrawingControl test = new DrawingControl();
            test.addMouseListener(test.rowToggle);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private MouseListener rowToggle = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                int w = getWidth();
                double h = getHeight();
                if(p.x > PAD && p.x < w-PAD && p.y > PAD && p.y < h-PAD) {
                    double yInc = (h - 2*PAD)/size;
                    int row = (int)((p.y - PAD)/yInc);
                    showRows[row] = !showRows[row];
                    repaint();
    }

Maybe you are looking for