How to un:instanceOf

I need to use the java instanceof in one of my jsp, but i'd like to use it by tab library.
I tried to use the unstandard taglib of jakarta but it gets me a strange (in my opinion) error.
I used it in the fllowing way:
<un:instanceOf type="Class value="${instance}">
do something
</un:instanceOf>
The error I got is: "According to TLD, tag un:instanceOf must be empty, but is not"
so.. I don't get how I should use it.. anyone could help me?
thanks!!

I'm afraid the real code isn't helpful... anyway:
<!-- centraline -->
<c:forEach items="${partizione.puntiAutostradali}" var="puntoAutostradale">
     <un:instanceOf type="ss.aspi.beans.meteo.centraline.grafica.PuntoRiferimentoBean" value="puntoAutostradale" var="isPuntoRif"/>
     <un:instanceOf type="ss.aspi.beans.meteo.centraline.grafica.SingolaCentralinaBean" value="puntoAutostradale" var="isCentralina"/>
     <tr><!-- centralina -->
          <td class="kilometrica"><c:out value="${puntoAutostradale.kilometricaRel}"/></td>
          <td class="tracciato"></td>
          <td class="tracciatoRiga"></td>
          <td class="tracciato"></td>
          <td class="centralinaName" axis="hidable_<c:out value="${partizione.codice}"/>"><c:out value="${puntoAutostradale.descrizione}"/></td>
          <td class="campoEl" axis="hidable_<c:out value="${partizione.codice}"/>">
               <c:choose>
                    <c:when test="${isPuntoRif}">PuntoRif</c:when>
                    <c:when test="${isCentralina}">Centralina</c:when>
                    <c:otherwise>ERRORE</c:otherwise>
               </c:choose>
          </td>
          <td class="campoEl" axis="hidable_<c:out value="${partizione.codice}"/>">Es.</td>
          <td class="campoElMed" axis="hidable_<c:out value="${partizione.codice}"/>">Es.</td>
          <td class="campoEl" axis="hidable_<c:out value="${partizione.codice}"/>">Es.</td>
          <td class="campoEl" axis="hidable_<c:out value="${partizione.codice}"/>">Es.</td>
          <td class="campoEl" axis="hidable_<c:out value="${partizione.codice}"/>">Es.</td>
     </tr><!-- fine centralina -->               
     <tr><!-- separatore -->
          <td class="kilometrica"></td>
          <td class="tracciato"></td>
          <td class="tracciatoRiga"></td>
          <td class="tracciato"></td>
          <td class="centralinaTotElementsLine" colspan="7" axis="hidable_<c:out value="${partizione.codice}"/>"></td>
     </tr><!-- fine separatore -->
</c:forEach>
<!-- fine centraline -->

Similar Messages

  • How fast is instanceof?

    How expensive is an instanceof operation? Is it in the order of simple arithmetic, or of reflection? Does it vary much?

    How expensive is an instanceof operation? Is it in
    the order of simple arithmetic, or of reflection?
    Does it vary much?Between the two, and yes. It's rarely going to be as slow as reflection, but when you get a "hit" it's practically as fast as arithmetic.
    So performance is rarely a reason to avoid "sanity tests" in code (remember, instanceof is essentially a check for != null as well as the type of the object).
    Try the following code snippet:
    import java.util.*;
    public class iof
       public static void main(String[] argv)
          int c = 1000000;
          List content = new ArrayList(c);
          for(int i = 0; i < c; i++ )
             content.add(new String("" + i));
          boolean ignoreState = false;
          Iterator i;
          long start = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
          // Instance of (miss)
             ignoreState = (o instanceof List);
          long middle1 = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
          // Instance of (hit)
             ignoreState = (o instanceof String);
          long middle2 = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
          // Instance of (arithmetic)
             ignoreState = ((2 + 2) > 3);
          long middle3 = new Date().getTime();
          i = content.iterator();
          while(i.hasNext())
             Object o = i.next();
             ignoreState = ( o.getClass().getName().equals(STRINGNAME) );
          long end = new Date().getTime();
          System.out.println("Instanceof (Miss) : " + (middle1 - start) + "ms");
          System.out.println("Instanceof (Hit)  : " + (middle2 - middle1) + "ms");
          System.out.println("Arithmetic        : " + (middle3 - middle2) + "ms");
          System.out.println("Reflection        : " + (end - middle3) + "ms");
       private static String STRINGNAME = "java.lang.String";
    }

  • Allow only String to List

    Hello,
    I have a ArrayList.
    ArrayList as = new ArrayList();Now i want to allow only string to be added in this arraylist how can i achieve this? Don't want to use generic.
    Please guide.

    Ankur Raiyani wrote:
    i have been asked to do not use generic.
    In given example where you have seen generics. It is clearly said if you don't want to use generics then use instanceof keyword.
    I want such a way that List only allows me to add String if i add other object then it should throw an error.Exactly , i've gave an idea how to use instanceof and allow only string objects in arraylist.
    If not clear, please go through the below program:
    import java.util.*;
    import java.lang.*;
    class ArrayListForOnlyString
         public static void main(String st[])
              List stringArrayList = new ArrayList(){
                   public ArrayList ar = new ArrayList();
                   public boolean add(Object ob) throws UnsupportedOperationException
                        if(ob instanceof String)
                             ar.add(ob);
                             return true;
                        else
                        throw new UnsupportedOperationException("Only String Object are accepted");
                   public void add(int index, Object ob)
                        if(ob instanceof String)
                             ar.add(index,ob);
                        else                    
                        throw new UnsupportedOperationException("Only String Object are accepted");
                   public Object[] toArray()
                        return ar.toArray();
                   public String toString()
                        return ar.toString();
              try
              stringArrayList.add(new String("10"));
              stringArrayList.add(1,new String("10"));
                    // Uncomment the below line and run, it 'll give error , as you are trying to add Integer Object to array list.
              //stringArrayList.add(new Integer("10"));
              System.out.println("The objects of arrayList are : "+stringArrayList);
             }catch(Exception e)
                        e.printStackTrace();
    }Edited by: 833545 on Aug 31, 2011 3:53 PM

  • How to determine the type of the jobject... similar to instanceof

    hi,
    I would like to know how to determine the jobject reference of an instance is of which class.
    this is something similar to instanceof we use in java.
    is there any thing like 'instanceof' in JNI. if there how to use it?
    i got this as objective question for which answers were(i do not remember exactly)
    1.instanceof
    2.assignedto
    i could nt het much help in googling.
    thanks in advance

    Hi
    The JNI provides a native version to the java instanceof operator, this function takes two arguments
    an object refrence and a class refrence and reports JNI_TRUE.
    jclass myclass = env->FindClass("your class name");
    if(env->IsInstanceOf(obj,myclass) == JNI_TRUE)
    // obj is of type myclass
    }Regards
    pradish

  • How do I manage dynamic narrowing casts without instanceof?

    Hi all,
    I need to extract arbitrary Objects from a given Collection and cast them to their original types. The problem is: checking with instanceof won't work for me, because the number of possible types is practically unlimited. Can anybody help?
    Thanks in advance,
    Wolfgang

    I don't think you have to do the cast in the set method. The following code works for me:
    [Main is a simple class with attributes <String a>, <int b> and <Main c>, and has getters for them]
    Note that the code is not nice, it's just a quick-n-dirty test case I wrote in a few minutes.
    Note also that I use Objects in the set method, rather then a String, an Integer and a Main.
          Class mainClass = Class.forName("dynamicinstantiation.Main");
          Constructor ctr = mainClass.getConstructor(new Class[0]);
          // object of class main, not known to the client
          Object main = ctr.newInstance(new Object[0]);
          // fieldvalues to set
          Object a = "String";
          Object b = new Integer(100);
          Object c = new Main();
          // get fields
          Field fldA = main.getClass().getDeclaredField("a");
          Field fldB = main.getClass().getDeclaredField("b");
          Field fldC = main.getClass().getDeclaredField("c");
          fldA.set(main, a);
          fldB.set(main, b);
          fldC.set(main, c);
          // Cast main to Main class, so we;re able to access it's methods
          Main m = (Main)main;
          System.out.println(m.getA());
          System.out.println(m.getB());
          System.out.println(m.getC().getA());
          System.out.println(m.getC().getB());

  • !instanceof - how can i get this logic to work...because it doesnt

    So I'm working with S Linked Lists and theres an add(E object) method that we are creating.
    So its supposed to first check-well at least at some point in the method- that the object being passed in is of the same type as my SLL. If its not im supposed to throw a new ClassCastException.
    I tried this at the beginning of the method:
    public void add(E obj) throws ClassCastException
             if(obj !instanceof Doctor) throw new ClassCastException();
             Doctor d = (Doctor)obj;
             int index = 0;
             MySLLNode<E> item = head;
             for(int i = 0; i<size(); i++) {
                  if (d.compareTo(item.getData()) < 0) {
                       super.add(index,obj);
                       size++;
                       break;
                  if (d.compareTo(item.getData()) == 0) {
                       super.add(index+1,obj);
                       size++;
                       break;
                  else {
                       index++;
                       item = item.next;
             addLast(obj);
             size++;
        }.....but im getting a couple of errors
    ./MySortedSLL.java:42: ')' expected
             if(obj !instanceof Doctor) throw new ClassCastException();
                   ^
    ./MySortedSLL.java:42: illegal start of expression
             if(obj !instanceof Doctor) throw new ClassCastException();
                     ^
    ./MySortedSLL.java:42: ';' expected
             if(obj !instanceof Doctor) throw new ClassCastException();
                                      ^So is there a better way to check that the object being passed in (which wants to be added to my SLL) is of compatable type...being that it is of type Doctor?
    Thanks in advance....

    Rather than
          if (f !instanceof Fubar) {
             System.out.println("Yeah!");
          }try
          if (!(f instanceof Fubar)) {
             System.out.println("Rah!");
          }

  • Overloading - how do I avoid instanceof?

    I am looking for a way to chose between overloaded methods without using specific casts.
    The following code tries to explain my problem:
    public class Overloading {
         public static void main(String[] args){
              new Overloading();
         public Overloading(){
              Animal macavity = new Cat();
              classify(macavity); // macavity is not classified as a cat
              // this is what I want to avoid having to do
              if(macavity instanceof Cat)
                   classify((Cat)macavity);
         private void classify(Animal animal){
              System.out.println("Just an animal.");
         private void classify(Cat cat){
              System.out.println("A cat!");
         class Animal{}     
         class Cat extends Animal{}
    }In the project I'm working has sanctioned that "Animals" cannot be allowed to classify themselves; they must be classified "from the outside" (not my rules).
    In the code I use instanceof to force use of the correct overload, but since there might be many animals this checking quickly becomes cumbersome!
    Is there any way I can cast an animal into its instantiation type without using instanceof?

    There's not a whole lot you can do as Java is not a dynamically bound (ie. at runtime) language. Java always uses the variable type at compile-time to decide which method is being called. 2 suggestions:
    1). You use reflection to be terribly clever at runtime and decide which method should be called.eg.
        Method m = Overloading.class.getDeclaredMethod("classify", macavity.getClass());
        m.setAccessible(true);
        m.invoke(macavity);This is almost certainly a very bad idea.
    2). Use some kind of handler-chain to classify and pass the animal along the chain until it is handled. You don't avoid the instanceof mess, but at least you don't have a huge if-else block.
        public class ClassifierChain
            public static interface Classifier {
                /** Return true if the implementation can classify the Animal */
                boolean classify(Animal a);
            public void classify(List<ClassifierChain.Classifier> classifiers, Animal a) {
                for (ClassifierChain.Classifier classifier : classifiers) {
                    if (classifier.classify(a)) break;
        public class CatClassifier implements ClassifierChain.Classifier {
            public boolean classify(Animal a) {
                if (a instanceof Cat) {
                    // ... do something with a cat
                   return true;
                return false;
        }Rubbish design, but you get the idea. Having said this, the previous post makes a lot of sense; in most cases it makes sense to keep your type-specific code bound closely to the type (ie. as a method on it). Obviously there are plenty of examples where this is a bad idea (eg. coupling UI-code to domain object classes).

  • How do I do a Sequence type check? (i.e. instanceof Sequence ?)

    This should be obvious as well. How do I test of a variable/object is of type sequence?

    Jeremy_Chone,
    use the following function to check. This will do the job.
    import java.lang.*;
    var weekDays = ["Mon","Tue","Wed","Thur","Fri",33,d ];
    var dt = [3,23,23,5, "#24", "324"];
    var dd:Integer= 0;
    function isSequence(sequence):Boolean
    try
    var ii = sequence as Object[]; // Sequence is synonmous with Object array.
    return true;
    catch (_ex:ClassCastException)
    return false;
    System.out.println(isSequence(dt));

  • How do i update an existing XML File?

    Hello, I have the following xml file gps.xml:<?xml version="1.0"?>
    <!DOCTYPE gps SYSTEM "gps.dtd">
    <gps>
       <latitude>43.00000</latitude>
       <longitude>-83.00000</longitude>
    </gps> I already have methods written to get the values. But how can I change these values and update the file to reflect these changes?
    thanks for your help!

    Hi, I already have this following code. I would just like to add a method to it to update the existing XML file with different lat/lon coordinates. Could you please help me out with it? thanks
    import java.io.*;
    import java.io.PrintWriter;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    public class Gps implements java.io.Serializable {
        private double latitude_;
        private double longitude_;
        public Gps(Document doc) {
            setup(doc.getDocumentElement());
        public Gps(String uri) throws IOException, SAXException, ParserConfigurationException {
            setup(uri);
        public void setup(Document doc) {
            setup(doc.getDocumentElement());
        public void makeElement(Node parent) {
            Document doc;
            if (parent instanceof Document) {
                doc = (Document)parent;
            } else {
                doc = parent.getOwnerDocument();
            Element element = doc.createElement("gps");
            int size;
            URelaxer.setElementPropertyByDouble(element, "latitude", this.latitude_);
            URelaxer.setElementPropertyByDouble(element, "longitude", this.longitude_);
            parent.appendChild(element);
         public Document makeDocument() throws ParserConfigurationException {
            Document doc = UJAXP.makeDocument();
            makeElement(doc);
            return (doc);
        public final double getLatitude() {
            return (latitude_);
        public final void setLatitude(double latitude) {
            this.latitude_ = latitude;
        public final double getLongitude() {
            return (longitude_);
        public final void setLongitude(double longitude) {
            this.longitude_ = longitude;
       public final void updateXmlFile(double latitude, double longitude) {
         // something???
        public final void updateXmlFile(double latitude, double longitude) {
            this.latitude_ = latitude;
            this.longitude_ = longitude;
        public String makeTextDocument() {
            StringBuffer buffer = new StringBuffer();
            makeTextElement(buffer);
            return (new String(buffer));
        public void makeTextElement(StringBuffer buffer) {
            int size;
            buffer.append("<gps");
            buffer.append(">");
            buffer.append("<latitude>");
            buffer.append(Double.toString(getLatitude()));
            buffer.append("</latitude>");
            buffer.append("<longitude>");
            buffer.append(Double.toString(getLongitude()));
            buffer.append("</longitude>");
            buffer.append("</gps>");
        public String toString() {
            try {
                return (makeTextDocument());
            } catch (Exception e) {
                return (super.toString());
    }

  • How to enter numbers in Arabic font in the fields

    Hi Everyone,
    I installed Adobe Reader 10.0.1 multi-Language and I am able to enter Arabic alphabet in the fields, but when I enter numbers in the fileds, it is English. I don't have this issue in MS-Word. i.e., both letters and numbers depend on my keyboard setting and is English or Arabic respectively. The numbers setting in windows in "depend on context" and I think is fine. Do you know how I can fix this issue? Is there any setting in Adobe that overwrights the Windows setting for numbers?
    Thanks a lot

    I won't say I am very clear about this topic. But I will give an example, which seems to show that number (in the double type) is logically of the form -000.00 while locale spacific String object can be both of the forms "000.00-" and "-000.00"
    // you can show the string below (formatted) on a JLabel with the following
    //<JLabel_instance>.setFont(new Font("Lucida Sans", Font.PLAIN, 22));
    NumberFormat nf = NumberFormat.getInstance(new java.util.Locale("ar","EG"));
    //NumberFormat nf = NumberFormat.getInstance(new java.util.Locale("fr","Fr"));   // compare
    DecimalFormat df=null;
    DecimalFormatSymbols dfs= null;
      if (nf instanceof DecimalFormat) {
          df = (DecimalFormat)nf;
          dfs = df.getDecimalFormatSymbols();
          dfs.setZeroDigit('\u0660');// set the beginning of the range to Arabic digits.. this can be commented out
          df.setDecimalFormatSymbols(dfs);
      String formatted = nf.format(-1234567.89);

  • How to enter numbers in Arabic?

    Hi All,
    How to write numbers in arabic?
    (how will you in normal papers....assume 123 to be in the arabic numerals here).
    Should it be:
    | -123|
    (or)
    | 123-|
    Thanks,
    Jana

    I won't say I am very clear about this topic. But I will give an example, which seems to show that number (in the double type) is logically of the form -000.00 while locale spacific String object can be both of the forms "000.00-" and "-000.00"
    // you can show the string below (formatted) on a JLabel with the following
    //<JLabel_instance>.setFont(new Font("Lucida Sans", Font.PLAIN, 22));
    NumberFormat nf = NumberFormat.getInstance(new java.util.Locale("ar","EG"));
    //NumberFormat nf = NumberFormat.getInstance(new java.util.Locale("fr","Fr"));   // compare
    DecimalFormat df=null;
    DecimalFormatSymbols dfs= null;
      if (nf instanceof DecimalFormat) {
          df = (DecimalFormat)nf;
          dfs = df.getDecimalFormatSymbols();
          dfs.setZeroDigit('\u0660');// set the beginning of the range to Arabic digits.. this can be commented out
          df.setDecimalFormatSymbols(dfs);
      String formatted = nf.format(-1234567.89);

  • How to write numbers in Arabic?

    Hi All,
    How to write numbers in arabic?
    (how will you in normal papers....assume 123 to be in the arabic numerals here).
    Should it be:
    | -123|
    (or)
    | 123-|
    Thanks,
    Jana

    Try the following.
    DecimalFormat formatter_ar=null;
    Numberformat form = NumberFormat.getNumberInstance(new Locale("ar","EG"));
    if(form instanceof DecimalFormat) formatter_ar = (DecimalFormat)form;
    String str = formatter_ar.format(-123.45);
    System.out.println(str);

  • Does anyone know how to...?

    Hi all,
    could someone explain how to set the background color of a cell in a JTable. I have read the tutoral and seen other wesites full of examples but i dont know how to incorpaorate a cell renderer into my table shown below.
    could someone show me. i would appreciate any help.
    import javax.swing.JTable;import javax.swing.table.AbstractTableModel;import javax.swing.JScrollPane;import javax.swing.JPanel;import javax.swing.SwingUtilities;import javax.swing.JOptionPane;import java.awt.*;import java.awt.event.*;public class AnimationPanel extends JPanel {     private boolean DEBUG = true;     JTable animationTable;     private Color highLiteColour;     public AnimationPanel() {          MyAnimationTable myTable = new MyAnimationTable();          animationTable = new JTable(myTable);          highLiteColour=Color.green;          //some useful tools          //*****************************************************          animationTable.setFont (new Font("Arial", Font.PLAIN, 18));          animationTable.setForeground(Color.black);          animationTable.setShowVerticalLines( false );          animationTable.setShowHorizontalLines( false );          animationTable.setCellSelectionEnabled(false);          //animationTable.setRowHeight(int row, int height);          animationTable.setBackground(highLiteColour, 4, 4);          // set Font          //mytable.setFont(font);          // set row height          //mytable.setRowHeight(20);          // set column width          //mytable.getColumnModel().getColumn( <column number> ).setPreferredWidth(<int>);         // preventing user from moving column around        //mytable.getTableHeader().setReorderingAllowed(allowColumnMoved);          //animationTable.setOpaque( false );          //headerLabel.setBackground(Color.yellow);          /*  public Color getForeground(int row, int column);            public void setForeground(Color color, int row, int column);            public void setForeground(Color color, int[] rows, int[] columns);            public Color getBackground(int row, int column);            public void setBackground(Color color, int row, int column);            public void setBackground(Color color, int[] rows, int[] columns);*/          //**********************************************          //table.setPreferredScrollableViewportSize(new Dimension(500, 70));          //Create the scroll pane and add the table to it.          //JScrollPane scrollPane = new JScrollPane(table);          //Add the scroll pane to this window.          //getContentPane().add(scrollPane, BorderLayout.CENTER);          //animationTable = new JTable(data, columnNames);          JScrollPane scrollPane = new JScrollPane(animationTable);          animationTable.setPreferredScrollableViewportSize(new Dimension(400, 210));          add(scrollPane);          /*addWindowListener(new WindowAdapter() {               public void windowClosing(WindowEvent e) {                    System.exit(0);               }          });*/     }     class MyAnimationTable extends AbstractTableModel {          Object[][] data = {          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {"Carry: "," "," ", " ", " ", " ", " ", " ", " ", " "},          {"X: "," ","0", "0", "0", "0", "0", "0", "0", "0"},          {"Y: "," ","0", "0", "0", "0", "0", "0", "0", "0"},          {"Sum: "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " ", " ", " ", " ", " ", " ", " "},          {" "," "," ", " "," ", " ", " ", " ", " ", " "}          };          String[] columnNames = {" ", " ", "-128", "64 ", "32 ", "16",          "8", "4", "2", "U"};          public int getColumnCount() {               return columnNames.length;          }          public int getRowCount() {               return data.length;          }          public String getColumnName(int col) {               return columnNames[col];          }          public Object getValueAt(int row, int col) {               return data[row][col];          }          /*           * JTable uses this method to determine the default renderer/           * editor for each cell.  If we didn't implement this method,           * then the last column would contain text ("true"/"false"),           * rather than a check box.           */          public Class getColumnClass(int c) {               return getValueAt(0, c).getClass();          }          /*           * Don't need to implement this method unless your table's           * editable.           */          public boolean isCellEditable(int row, int col) {               //Note that the data/cell address is constant,               //no matter where the cell appears onscreen.                    return false;          }          /*           * Don't need to implement this method unless your table's           * data can change.           */           //anim.animationTable.setValueAt(" ",5,i);          public void setValueAt(Object value, int row, int col) {               /*if (DEBUG) {                    System.out.println("Setting value at " + row + "," + col                                           + " to " + value                                           + " (an instance of "                                           + value.getClass() + ")");               }*/               data[row][col] = value;               fireTableCellUpdated(row, col);               //if (data[0][col] instanceof Integer                //       && !(value instanceof Integer)) {                    //With JFC/Swing 1.1 and JDK 1.2, we need to create                    //an Integer from the value; otherwise, the column                    //switches to contain Strings.  Starting with v 1.3,                    //the table automatically converts value to an Integer,                    //so you only need the code in the 'else' part of this                    //'if' block.                    //XXX: See TableEditDemo.java for a better solution!!!                    /*try {                         data[row][col] = new Integer(value.toString());                         fireTableCellUpdated(row, col);                    } catch (NumberFormatException e) {                         JOptionPane.showMessageDialog(AnimationPanel.this,                              "The \"" + getColumnName(col)                              + "\" column accepts only integer values.");                    }*/             // } else {                    data[row][col] = value;                    fireTableCellUpdated(row, col);             // }               /*if (DEBUG) {                    System.out.println("New value of data:");                    //printDebugData();               }*/        }     }}

    still havent found a descent answer to this question,
    begining to think that no-one actually knows.What did you expect? You have posted probably the most
    unreadable message I have seen for a long time on this forum.
    Do yourself a favor and read the following: http://forum.java.sun.com/thread.jsp?forum=31&thread=271751
    Also, read this: http://forum.java.sun.com/features.jsp

  • How to make a JPanel transparent? Not able to do it with setOpaque(false)

    Hi all,
    I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
    import javax.media.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.lang.Math;
    import javax.media.control.FramePositioningControl;
    import javax.media.protocol.*;
    import javax.swing.*;
    class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
         Player player;
         Component vc, cc;
         boolean first = true, loop = false;
         String currentDirectory;
         int mediatime;
         BufferedWriter out;
         FileWriter fos;
         String filename = "";
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         JButton bn = new JButton("DrawLine");
         MPEGPlayer2 (String title)
              super (title);
              addWindowListener(new WindowAdapter ()
                   public void windowClosing (WindowEvent e)
                            dispose ();
                            public void windowClosed (WindowEvent e)
                         if (player != null)
                         player.close ();
                         System.exit (0);
              Menu m = new Menu ("File");
              MenuItem mi = new MenuItem ("Open...");
              mi.addActionListener (this);
              m.add (mi);
              m.addSeparator ();
              CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
              cbmi.addItemListener (this);
              m.add (cbmi);
              m.addSeparator ();
              mi = new MenuItem ("Exit");
              mi.addActionListener (this);
              m.add (mi);
              MenuBar mb = new MenuBar ();
              mb.add (m);
              setMenuBar (mb);
              setSize (500, 500);
              setVisible (true);
         public void actionPerformed (ActionEvent ae)
                        FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
                        fd.setDirectory (currentDirectory);
                        fd.show ();
                        if (fd.getFile () == null)
                        return;
                        currentDirectory = fd.getDirectory ();
                        try
                             player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
                             filename = fd.getFile();
                        catch (Exception exe)
                             System.out.println(exe);
                        if (player == null)
                             System.out.println ("Trouble creating a player.");
                             return;
                        setTitle (fd.getFile ());
                        player.addControllerListener (this);
                        player.prefetch ();
         }// end of action performed
         public void controllerUpdate (ControllerEvent e)
              if (e instanceof EndOfMediaEvent)
                   if (loop)
                        player.setMediaTime (new Time (0));
                        player.start ();
                   return;
              if (e instanceof PrefetchCompleteEvent)
                   player.start ();
                   return;
              if (e instanceof RealizeCompleteEvent)
                   vc = player.getVisualComponent ();
                   if (vc != null)
                        add (vc);
                   cc = player.getControlPanelComponent ();
                   if (cc != null)
                        add (cc, BorderLayout.SOUTH);
                   add(new MyPanel());
                   pack ();
         public void itemStateChanged(ItemEvent ee)
         public static void main (String [] args)
              MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
              System.out.println("111111");
    class MyPanel extends JPanel
         int i=0,j;
         public int xc[]= new int[100];
         public int yc[]= new int[100];
         int a,b,c,d;
         public MyPanel()
              setOpaque(false);
              setBorder(BorderFactory.createLineBorder(Color.black));
              JButton bn = new JButton("DrawLine");
              this.add(bn);
              bn.addActionListener(actionListener);
              setBackground(Color.CYAN);
              addMouseListener(new MouseAdapter()
                             public void mouseClicked(MouseEvent e)
                   saveCoordinates(e.getX(),e.getY());
         ActionListener actionListener = new ActionListener()
              public void actionPerformed(ActionEvent aae)
                        repaint();
         public void saveCoordinates(int x, int y)
                    System.out.println("x-coordinate="+x);
                    System.out.println("y-coordinate="+y);
                    xc=x;
              yc[i]=y;
              System.out.println("i="+i);
              i=i+1;
         public Dimension getPreferredSize()
    return new Dimension(500,500);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
              Graphics2D g2D = (Graphics2D)g;
              //g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
              g2D.setColor(Color.GREEN);
              for (j=0;j<i;j=j+2)
                   g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);

    camickr wrote:
    "How to Use Layered Panes"
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
    Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top!

  • How to open a JPanel

    Hi
    I have created a JPanel in JDeveloper 10.1.3. It has a main method with (see below) but when opened from my application I must use something else than JUTestFrame but what? How should the JPanel be opened the right way?
    public static void main(String [] args) {
    try {
    UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    } catch (ClassNotFoundException cnfe) {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception exemp) {
    exemp.printStackTrace();
    } catch (Exception exemp) {
    exemp.printStackTrace();
    CurrencyRateEdit panel = new CurrencyRateEdit();
    panel.setBindingContext(JUTestFrame.startTestFrame("mypackage.DataBindings.cpx", "null", panel, panel.getPanelBinding(), new Dimension(400,300)));
    panel.revalidate();
    }

    Thanks for the input, unfortunately using the JFrame provided by the JDev wizard is what we are trying to avoid. We do not want a JFrame of any kind.
    I have it working now with a JPanel as the top level container for the ADF plumbing. This allows me to place the ADF bindings virtually anywhere without any type of boarders. Here is how I did it. (by the way I am still testing out Erik's recommendation)
    1) create a default application with an empty runable panel. (the main() can be moved out later but makes it easy for testing) The code here assumes you are using all the default naming in the wizard. If not you will have to make the appropriate changes.
    2) Just under the class definition create an instance of a class named "appPanel". This class will be defined below and is a gutted/modified version of JUTestFrame which extends JPanel instead of JFrame. It should look something like this:
    public class Panel1 extends JPanel implements JUPanel {       
    public appPanel canvas = new appPanel();
    3) In the main() function change
    panel.setBindingContext(JUTestFrame.startTestFrame( ...
    to:
    panel.setBindingContext(panel.canvas.startTestFrame( ... //canvas is the name I chose in step 2.
    4) If, in this test app, you don't already have a container (JForm or other) for the ADF JPanel you can create one for testing like this:
    At the bottom of the main() function put :
    JFrame xx = new JFrame();
    xx.add(panel);
    xx.setVisible(true);
    5) Create the class file appPanel (menu: new >simple file > Java Class. and replace all of the contents with: (excuse the formatting. I don't know why they don't make developer forums more code friendly)
    package mypackage;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.beans.PropertyVetoException;
    import javax.swing.JPanel;
    import javax.swing.JInternalFrame;
    import javax.swing.JScrollPane;
    import java.util.HashMap;
    import oracle.jbo.uicli.UIMessageBundle;
    import oracle.jbo.uicli.jui.JUPanelBinding;
    import oracle.jbo.uicli.jui.JUEnvInfoProvider;
    import oracle.jbo.uicli.controls.JUErrorHandlerDlg;
    import oracle.jbo.uicli.controls.JClientPanel;
    import oracle.jbo.uicli.binding.JUApplication;
    import oracle.jbo.uicli.mom.JUMetaObjectManager;
    import oracle.adf.model.BindingContext;
    import oracle.adf.model.DataControlFactory;
    import oracle.adf.model.binding.DCDataControl;
    import oracle.jbo.uicli.controls.*;
    public class appPanel extends JPanel
    private JUPanelBinding panelBinding = null;
    private DCDataControl dataControl;
    private BindingContext mCtx;
    appPanel frame;
    public appPanel() {
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public BindingContext startTestFrame(String cpxName, String dcName, JPanel panel, JUPanelBinding panelBinding, Dimension size)
    if (!(panel instanceof JUPanel))
    System.err.println(UIMessageBundle.getResString(UIMessageBundle.STR_TUI_ERROR_JCLIENTPANEL));
    return null;
    frame = new appPanel(cpxName, dcName, panelBinding, panel);
    frame.adjustFrameSize(size);
    return frame.getBindingContext();
    public appPanel(JUPanelBinding designTimePanelBinding, JPanel panel)
    this.setLayout(new GridLayout());
    JScrollPane scPane = new JScrollPane(panel);
    this.add(scPane);
    JUMetaObjectManager.setBaseErrorHandler(new JUErrorHandlerDlg());
    //mom will pass properties in case it's null
    JUApplication app = JUMetaObjectManager.createApplicationObject(designTimePanelBinding.getApplicationName(), null, new JUEnvInfoProvider());
    panelBinding = new JUPanelBinding(designTimePanelBinding.getApplicationName(), panel);
    panelBinding.setApplication(app);
    ((JClientPanel)panel).setPanelBinding(panelBinding);
    panelBinding.execute();
    dataControl = app;
    public appPanel(String cpxName, String dcName, JUPanelBinding panelBinding, JPanel panel)
    this.setLayout(new GridLayout());
    JScrollPane scPane = new JScrollPane(panel);
    this.add(scPane);
    createBindingCtxAndSetUpMenu(cpxName, dcName, panelBinding);
    private void createBindingCtxAndSetUpMenu(String cpxName, String dcName, JUPanelBinding panelBinding)
    JUMetaObjectManager.setBaseErrorHandler(new JUErrorHandlerDlg());
    JUMetaObjectManager.getJUMom().setJClientDefFactory(null);
    mCtx = new BindingContext();
    HashMap map = new HashMap(4);
    map.put(DataControlFactory.APP_PARAMS_BINDING_CONTEXT, mCtx);
    JUMetaObjectManager.loadCpx(cpxName, map);
    DCDataControl app = (DCDataControl)mCtx.get(dcName);
    if (app != null)
    dataControl = app;
    app.setClientApp(DCDataControl.JCLIENT);
    else
    mCtx.setClientAppType(DCDataControl.JCLIENT);
    panelBinding = panelBinding.setup(mCtx, null);
    public DCDataControl getDataControl()
    return dataControl;
    public BindingContext getBindingContext()
    return mCtx;
    void adjustFrameSize(Dimension size)
    setSize(size);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    if (size.height > screenSize.height)
    size.height = screenSize.height;
    if (size.width > screenSize.width)
    size.width = screenSize.width;
    setLocation((screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2);
    setVisible(true);
    private static final char MNEMONICINDICATOR = '&';
    public static final int MNEMONIC_INDEX_NONE = -1;
    * Returns the key code for the mnemonic in the string. Returns
    * VK_UNDEFINED if the string does not contain a mnemonic.
    public int getMnemonicKeyCode(String string)
    if (string == null)
    return KeyEvent.VK_UNDEFINED;
    // Minus one, because a trailing ampersand doesn't count
    int lengthMinusOne = string.length() - 1;
    int i = 0; // Index in the source sting
    while (i < lengthMinusOne)
    int index = string.indexOf(_MNEMONIC_INDICATOR, i);
    // Are we at the end of the string?
    if ((index == -1) || (index >= lengthMinusOne))
    break;
    char ch = string.charAt(index + 1);
    // if this isn't a double ampersand, return
    if (ch != MNEMONICINDICATOR)
    // VK_* constants are all for upper case characters
    return(int) Character.toUpperCase(ch);
    // Skip over the double ampersand
    i = index + 2;
    return KeyEvent.VK_UNDEFINED;
    * Removes non-displayable inline mnemonic characters.
    * In order to specify a mnemonic character in a translatable string
    * (eg. in a resource file), a special character is used to indicate which
    * character in the string should be treated as the mnemonic. This method
    * assumes that an ampersand ('&') character is used as the mnemonic
    * indicator, and removes (single) ampersands from the input string. A
    * double ampersand sequence is used to indicate that an ampersand should
    * actually appear in the output stream, in which case one of the ampersands
    * is removed.
    * Clients should call this method after calling
    * StringUtils.getMnemonicIndex() and before displaying the string. The
    * returned string should be used in place of the input string when
    * displaying the string to the end user. The returned string may be the
    * same as the input string if no mnemonic indicator characters are found,
    * but this is not guaranteed.
    * @see #getMnemonicIndex
    public String stripMnemonic(String string)
    if (string == null)
    return null;
    int length = string.length();
    // Single character (or empty) strings can't have a mnemonic
    if (length <= 1)
    return string;
    StringBuffer buffer = null;
    int i = 0;
    while (i < length)
    int index = string.indexOf(_MNEMONIC_INDICATOR, i);
    // We've reached the append. Append the rest of the
    // string to the buffer, if one exists, then exit
    if ((index < 0) || (index >= length - 1))
    if (buffer != null)
    buffer.append(string.substring(i));
    break;
    if (buffer == null)
    // If the string starts with an ampersand, but not a double
    // ampersand, then we just want to return
    // stripMnemonic(string.substring(1)). This is basically
    // what we do here, only I've optimized the tail recursion away.
    if ((index == 0) && (string.charAt(1) != MNEMONICINDICATOR))
    string = string.substring(1);
    length--;
    continue;
    else
    // Allocate the buffer. We can reserve only space
    // (length - 1), because, by now, we know there's at least
    // 1 ampersand
    buffer = new StringBuffer(length - 1);
    // Append the bits of the string before the ampersand
    buffer.append(string.substring(i, index));
    // And append the character after the ampersand
    buffer.append(string.charAt(index + 1));
    // And skip to after that character
    i = index + 2;
    // If we never allocated a buffer, then there's no mnemonic
    // at all, and we can just return the whole string
    if (buffer == null)
    return string;
    return new String(buffer);
    private void jbInit() throws Exception {
    And now you have an ADF implementation that exists purely in a JPanel to be placed anywhere.
    Again I am still testing Erik's recomendation which may prove to be a better implementation; but I wanted to share what I have working.
    I hope this helps someone out. Good luck.
    SMartel

Maybe you are looking for

  • Can we stop a collection evaluation once it is started?

    Hi Guys,  Is there an option to cancel the collection evaluation once that is started? Thanks,  Delphin. Kindly mark as answer/Vote as helpful if a reply from anybody helped you in this forum. Delphin

  • Receiving mms texts with AT&T what a pain to get in the account!

    Ok when I get an mms I gotta go to that link and put in the message I'd and a pass word. No matter how many tes I type and retype it t won't log In. Is there an easier way? Why does the message I'd and pass gott be different every time I ger a mms?

  • Sales order delivered and invoiced but purchase req still open?

    Hi all I have a process where a sales order triggers the creation of a third party purchase requisition.  A PO was created and then deleted because the sales order was filled from a different purchase order where too much had been ordered.  The sales

  • Bento  in Snow Leopard

    Since upgrading to Snow Leopard, my Bento 1 will not open and all the files have disappeared. Even reinstalling the application from Time Machine does the same thing. Any suggestions? Neville

  • Could You help Please (updating JTable Content)

    Sorry for posting again... I really need help... can't update the content of JTable instead it keep adding the columns to the table. How can I remove before add?? I tried couple of things but didn't work... Please help... bellow is the code i posted