Categories
discuss

Mouse moved event within JPanel

I’m having some issues with getting my mouse events to work. I have a JPanel inside of a JLayeredPane which is in a JScrollPane. Admittedly, I am fairly new to working with Swing, but essentially, I want the JPanel to react to the mouse moving, but have been unable to get it to work.

public class CellHighlighter extends JPanel implements MouseMotionListener{

    public CellHighlighter(){

    }

    public void mouseMoved(MouseEvent evt){
        System.out.println(evt.getPoint().x + ", " + evt.getPoint().y);
    }

    public void mouseDragged(MouseEvent evt){System.out.println("message");}

}

Any help would be much appreciated, thanks in advance!

Answer

Are you registering your JPanel Object with the MouseListener? Something like:

    public CellHighlighter(){
       this.addMouseMotionListener(this);
    }

Or maybe you need to add the MouseListener to The ScrollPane or LayeredPane?

Categories
discuss

Is there any way to quickly determine if a browser supports CORS-enabled images not tainting the browser?

Is there a quick test to determine if a browser supports CORS-enabled images not tainting a canvas when drawn on them. I know Chrome 15 supports this, Firefox 9Beta but not Firefox 8, Safari doesn’t, IE9 doesn’t. But there must be a pretty simple test to determine this, is basically drawing on a canvas with an image and seeing if you get an exception when you try to get image data, or is there any other easy way to determine this.

Answer

Here is how I tested for CORS tained canvas support. If someone has a way without having to load an image, please post it here:

function CanvasFunctions() {
    var _initialized = false, _corsNotSupported = false;


    function DrawImage(image, src) {
        jQuery.when(initialized()).then(function () { 
            if (_corsNotSupported) {
               image.src = GetProxyImage(src);
            } else {
               image.src = src;
            } 
        }
    }

    function initialized() {
        if (_initialized) {
            return true;
        }

        var dfd = $.Deferred();

        var src = 'http://example.com/corsImage.jpg',
            image.onload = function () {
                var canvas = document.createElement('canvas');
                canvas.width = 250;
                canvas.height = 250;
                var ctx = canvas.getContext('2d');
                ctx.drawImage(image, 0, 0, 200, 200);
                try {
                    var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1;
                    console.log('Canvas was not tainted by CORS image, hit: ' + hit);
                } catch (e)  {
                    console.log('Canvas was tainted by CORS image, reverting to passthru for images');
                    _corsNotSupported = true;
                }
                _initialized = true;
                dfd.resolve(true);
            });

        image.src = src;


        return dfd.promise();
    }
}
Categories
discuss

Move a div in a curved path (like tweening in Flash old days)?

I’d like to build a function like

fromHeretoThere(x1,y1,x2,y2){
  //....
}

So that I can move a <div> or an image from one point on the HTML page to another point in a curve.

Is this doable only using Canvas? HTML5? any plugin/scripts yo suggest?

Answer

Edit: Here’s a work in progress that packages up the second concept described below as a re-usable JS object. You can edit the code or visually drag the curve to see the resulting code:

http://phrogz.net/SVG/animation_on_a_curve.html


I’d personally use SVG, which makes this sort of thing (animating along an arbitrary Bézier curve) trivial using the <animateMotion> element. As a bonus, you can even cause it to calculate the rotation for you. Some examples:

Note that you don’t even have to actually use SVG to display the result; you could simply create an off-screen SVG with this animation and sample the transform of the animated element to get your desired point/rotation.

Alternatively (if you don’t want the rotation, or want to calculate it yourself while controlling the rate of traversal) you can create an SVG path and just use getPointAtLength()/getTotalLength() to find where you should be along the path at a given percentage of the total traversal distance. With this you don’t even need an SVG document:

// Moving along an S curve from 0,0 to 250,450
var p = document.createElementNS('http://www.w3.org/2000/svg','path');
p.setAttribute('d','M0,0 C350,20 -200,400 250,450');
var len = p.getTotalLength();
for (var i=0;i<=100;i+=10){
  var pct = i/100;
  var pt = p.getPointAtLength(pct*len);
  console.log( i, pt.x, pt.y );
}

// 0 0 0
// 10 65.54324340820312 10.656576156616211
// 20 117.17988586425781 49.639259338378906
// 30 120.2674789428711 114.92564392089844
// 40 100.49604034423828 178.4400177001953
// 50 78.06965637207031 241.1177520751953
// 60 63.526206970214844 305.9412841796875
// 70 74.59959411621094 370.6294860839844
// 80 122.1227798461914 415.8912658691406
// 90 184.41302490234375 438.8457336425781
// 100 250 450

Now all you have to do is set the .style.top and .style.left of your <div> or <img> appropriately. The only ‘hard’ part is deciding what you want to the curve to look like and defining where to put the handles.

Categories
discuss

event constants for javascript?

In javascript I have code like

document.addEventListener("mousedown", mouseDownHandler);

and occasionally I might fat finger something like

document.addEventListener("mouzedown", mouseDownHandler);

And javascript won’t recognize that I’m a moron and I’ll be confused why my handler isn’t working.

Actionscript3 specifies event constants like so

MouseEvent.MOUSE_DOWN // equiv to the String "mouseDown"

If I fat-finger a variable or constant then JS gets mad at me and I can solve the problem real quick. Does JavaScript have anything similar to to this or do I need to make my own JS pseudo-constants for event types?

Answer

There is no built-in feature to do this for you.

You could create your own list of events:

var EventNames = {
  MOUSE_DOWN : "mousedown",
  MOUSE_UP   : "mouseup",
  CLICK      : "click",
  // etc
};

But that doesn’t protect you from typos because then EventNames.MOUZE_DOWN will just give you undefined (which will likely be accepted by addEventListener() but – obviously – not do what you want).

You could create a series of individual global variables and then the browser should give an error if you make a typo on the “constant” name (and your IDE or lint product may detect typos for you):

var Event_MOUSE_DOWN = "mousedown",
    Event_MOUSE_UP   = "mouseup",
    // etc

But of course members of the “globals are evil” brigade are already starting to froth at the mouth just from having read the above. You could do the above without globals by wrapping all of your code (including those “constants”) in one big immediately-executed anonymous function, or you could instead do something like this:

// YNH: "Your Namespace Here" (insert your own namespacing
//                             code as desired)
var YNH_Events = {
   validEvents : ["mouseup","mousedown","click","etc"],

   bindEvent = function(element, eventType, handler, isCustomEvent) {
      if (!isCustomEvent && -1 === this.validEvents.indexOf(eventType))
         throw "Invalid event type requested: " + eventType;

      if (element.addEventListener)
         element.addEventListener(eventType, handler, false);
      else if (element.attachEvent)
         element.attachEvent("on" + eventType, handler);
      else
         element["on" + eventType] = handler;
   }
}

YNH_Events.bindEvent(someElement, "mousedown", function() { });         // OK
YNH_Events.bindEvent(someElement, "customevent", function() { }, true); // OK
YNH_Events.bindEvent(someElement, "mouzedown", function() { });     // Error!

Of course, the usual caveat about using Array.indexOf() applies, i.e., not supported in older browsers but you can shim it as described by MDN, blah, blah, blah.

Or you could do like jQuery and define your own .mousedown(), .click() etc methods and only attach events through those methods – you’ll definitely get an error if you mistype the method name.

Categories
discuss

How to remove standalone attribute declaration in xml document?

Im am currently creating an xml using Java and then I transform it into a String. The xml declaration is as follows:

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");

For transforming the document into String, I include the following declaration:

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.VERSION, "1.0");
trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
trans.setOutputProperty(OutputKeys.INDENT, "yes");

And then I do the transformation:

StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();

The problem is that in the XML Declaration attributes, the standalone attribute is included and I don’t want that, but I want the version and encoding attributes to appear:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Is there any property where that could be specified?

Answer

From what I’ve read you can do this by calling the below method on Document before creating the DOMSource:

doc.setXmlStandalone(true); //before creating the DOMSource

If you set it false you cannot control it to appear or not. So setXmlStandalone(true) on Document. In transformer if you want an output use OutputKeys with whatever “yes” or “no” you need. If you setXmlStandalone(false) on Document your output will be always standalone="no" no matter what you set (if you set) in Transformer.

Read the thread in this forum

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..