Array of components

Hi,
Is there some way to create an array of components. What I'd
like to be able to do is have an array of 8 panels or datagrids.
Then be able to loop through each of those within the array.
Thanks!

Anyone have any thoughts? It seems one way might be to do a
repeater, although I would prefer to do most of this within the
scripting? Any direction would be great

Similar Messages

  • Using buttons to make an array of components

    Im trying to use a JButton to create an array of components(JButtons)
    and put them in a panel.My code only generates one button not three as planned! The purpose is to allow the user to configure the GUI according to a list of parameters.
    void button1_actionPerformed(ActionEvent e) {
    // array to hold buttons
    JButton button2[] = new JButton[3];
    for (int i=0;i<3 ;i++){ //set up each button
    button2[i] = new JButton();
    button2.setBackground(Color.cyan);
    button2[i].setSize(50,50);
    button2[i].setText(String.valueOf(i));
    panel1.add(button2[i]);
    }//end for
    }///end button1_actionPerformed

    void button1_actionPerformed(ActionEvent e) {
    // array to hold buttons
    JButton button2[] = new JButton[3];
    for (int i=0;i<3 ;i++){ //set up each button
    button2[i] = new JButton();
    button2.setBackground(Color.cyan);
    button2[i].setSize(50,50);
    button2[i].setText(String.valueOf(i));
    panel1.add(button2[i]);
    panel1.validate(); // <<<<<< edited
    }//end for
    }///end button1_actionPerformed
    now it should works!

  • Divide an array into components

    Hello:
    I am developing a LV application that has, in some way, "two parts": One of them is the user interface and its associated block diagram, that receives values from controls and files. Then, this values are used for feeding the inputs of a "Call Library Function" node.
    Well, some of the values I use are components of an array. I thought that I could use a "Split array" block, but I cant connect the "1 component array" with the numerical input of the library node.
    How could I "convert" a "1 component array" into a "numerical value". I actually use a very improper method, I connect the "1 component" array to a "array max & min" block, and I use "max value" output (I could use min too, obviously).
    Another question that is related to this is the follwing: Is there any method in order to split an array into its numerical components? Because I have, for example, a 4 elements array, I wished to divide it (in an easy way, instead of having a "serial association" of 4 "split array" blocks) into 4 numerical values that are used for feeding a function node.
    Well, if you need any aditional info, please dont hesitate in ask for it. Thank you very much for your attention and please sorry for my bad english.
    Yours sincerely.
    Juan Crespo

    Juan,
    Apologies if I misunderstood, but is the 'Index Array' function the answer to both your questions?
    =====================================================
    Fading out. " ... J. Arthur Rank on gong."
    Attachments:
    Index Array Elements.jpg ‏12 KB

  • Find index in an array of components

    I have an array of JButtons. Each JButton has an associated ActionListener. My problem is that when one of the buttons are clicked I need the index of the JButton that is clicked to do work inside the Actionlistener.
    How do I get the index of the JButton being pressed?
    JButton[ ] button = new JButton[300];
    for(int i = 0 ; i < 300 ; i++)
    button[i] = new JButton(("Test " + i));
    button.addActionListener(new ActionListener()
    public actionPerformed(ActionEvent evt)
    /** I need to know what the value of i is when this button is pressed **/

    I would think that you could just use the variable i from the loop, like this:
    JButton buttonArray = new JButton[300];
    JButton button;
    for(int i = 0; i < 300; i++)
      button = new JButton("Test"+i);
      button.addActionListener(new ActionListener() {
        public actionPerformed(ActionEvent e)
          int index = i; // here index is the index of the JButton chosen
    hope this helps!
      buttonArray[i] = button;

  • Declaring array of T[] - possible bug?

    See the following code:
    class A {}
    class B {}
    public class Test {
         public static void main(String[] args) {
              A a = null;
              foo(a);
         public static <T> void foo(T a) {
              T[] t = (T[]) new Object[10];
              Object[] o = t; // correct. Object[] is parent of T[].
              o[0] = new B(); // correct.  Insert B into object[].
              T val = t[0]; // Type error if T is not A!!
              System.out.println(t[0]);
    }T[] t = (T[]) new Object[10]; is the way of declaring an array of T that people in this forum recommend. However, I've found something
    quite strange. As you can see in the code above , T must be A. However, strangely enough, T val = t[0] succeeded. In this code, T is obviously A, and t[0] is also obviously B. However, JDK raises only one warning about T[] t = (T[]) new Object[10];, saying that "cast from Object[] to T[] is actually checking against erased type Object[]."
    Though the tutorial on generics says that codes are type-safe only when there's no warning, assigning instance of B into the variable whose type is A is quite weird.
    Is this a bug or my mistake?
    TIA.

    T[] t = (T[]) new Object[10];My compiler gives a warning here, which makes sense:     [javac] Compiling 236 source files to C:\cygwin\home\jeff\dev\scratch\classes
        [javac] C:\cygwin\home\jeff\dev\scratch\Test.java:14: warning: [unchecked] unchecked cast
        [javac] found   : java.lang.Object[]
        [javac] required: T[]
        [javac]         T[] t = (T[]) new Object[10];
        [javac]                       ^
        [javac] 1 warning
    Object[] o = t; // correct. Object[] is parent of
    of T[].No, it's not. Object is the parent of T.
    [url http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html#40879]JLS 10.8 Class Objects for Arrays: The direct superclass of an array type is Object.
    The conversion works because [url http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#184206]JLS 5.2 Assignment Conversion says:
    Assignment of a value of compile-time reference type S (source) to a variable of compile-time reference type T (target) is checked as follows:
    If S is an array type SC[], that is, an array of components of type SC:
    If T is a class type, then T must be Object, or a compile-time error occurs.
    If T is an interface type, then a compile-time error occurs unless T is the type java.io.Serializable or the type Cloneable, the only interfaces implemented by arrays.
    If T is an array type TC[], that is, an array of components of type TC, then a compile-time error occurs unless one of the following is true:
    TC and SC are the same primitive type.
    TC and SC are both reference types and type SC is assignable to TC, as determined by a recursive application of these compile-time rules for assignability.
    I'm a little disappointed that this doesn't at least produce a warning, but I guess you can't expect generics to catch everything.
    o[0] = new B(); // correct. Insert B into
    to object[].This is why it kind of sucks that the previous statement works.
    T[] t = (T[]) new Object[10]; is the way of declaring
    an array of T that people in this forum recommend.They do? Seems odd, but then, I'm not really on 5.0 yet, so I don't know that much about generics.
    However, I've found something
    quite strange. As you can see in the code above , T
    must be A. However, strangely enough, T val = t[0]
    succeeded. In this code, T is obviously A, and t[0]
    is also obviously B. That may be a bug, or it may just be a limitation of how far generics can go in type checking. Poke through some generics tutorials and white papers, and if you don't find an explanation, submit it to the bug parade.
    Though the tutorial on generics says that codes are
    type-safe only when there's no warning, assigning
    instance of B into the variable whose type is A is
    quite weird.Yeah, but the code that got you there is kind of weird too. Generics provide type safety in a lot of common scenarios, but they can't cover every possibility.
    Is this a bug or my mistake?Not sure. My guess is this is just something that generics are not meant to cover, but it could be a bug.

  • How to fetch components when application loads the components DYNAMICALLY?

    In any of java application or applet, I am able to fetch the components using getComponents() or by getContentPane() methods which returns array of components when the application gets launched.
    But when the components is launched dynamically by the application/applet, I am able to get the only the containers & not the components....
    I also kept my application Tracer to sleep to getComponents() for 5-10 sec to allow dynamic loading of any application,still i am not able to fetch the components.
    Could anyone sort out this.

    A Container class is simply an extension of the Component class, perhaps what you got is exactly what you were looking for (i.e., the application/applet may have created the components via the Container class).
    :o)
    V.V.

  • List to Array with Type

    Hi guys,
    I need to turn a List (an ArrayList specifically) into an array of Components.
    This is because I can't call a function like doSomething(Component ... components) with a collection. It needs to be an array correct?
    So, if it needs to be an array, I can't find a clean way to do it....or maybe I'm just a whiner.
    I can do this with
    theList.toArray(new Component[theList.size()]);or I can do it with
    (Component[])theList.toArray()But I don't like either of those...why should I have to pass an array in the first one and why should I be the one doing the cast in the second one?
    Shouldn't the ArrayList know how to return a correctly typed array?
    I wrote this little static method that I put in a helper class...does anything like this exist in the Collections class as a static method?
    I couldn't find anything like it in Arrays, or Collections etc.
    public static <T> T[] collectionToArray(Collection<T> l){
        Object ret[] = new Object[l.size()];
        int i = 0;
        for(T t : l){
            ret[i++] = t;
        return (T[]) ret;
    }If there is a better way to do this please let me know.
    Thanks,
    ~Eric

    ganeshmb wrote:
    It wasn't done because you either need an array of the proper type passed as a parameter, or a Class<T> passed as a parameter.Why? ArrayList is parametrized, which means it should be able to figure the data type by inspecting its contents, right? The only problem I see is, when its contents are empty, it will have to return null instead of an empty array. This is a different behavior from toArray, but should be acceptabe given the ease of use for clients - they don't have to pass an array instance to get the list back as an array.Wrong. In addition to the empty array behavior, suppose I have an List<Map>. I could have HashMap, ConcurrentHashMap, Properties, etc, all in this list. I still want a Map[] returned. What if my list is filled with HashMap? I still want a Map[] returned. Inspecting the contents is not a workable solution.

  • Set array instance to Interface datatype

    <prelude>This is an odd question with no real significance to me, other than pure interest...</prelude>
    Suppose the following...just for example
    Integer[] arrInteger = new Integer[5];I understand that the following is legal..
    Interface i = arrComp;...provided that the Interface is either Cloneable, or Serializable.
    Why is this legal....Are arrays always serializable as defined in the language spec...
    If arrays are Cloneable, shouldn't they override the method "clone" from the Object class..and how do they do that, there are no classes for arrays....Or maybe they just "do" as a feature of being an array...
    It just seems odd that it is possible to set an array, any array to a Cloneable or Serializable interface.

    I've done what I probably should have done before I posted, I've consulted the Java Language Specification ( http://java.sun.com/docs/books/jls/ )and there I've found my answer..
    From the section Conversion and Promotions....
    Assignment of a value of compile-time reference type S (source) to a variable of compile-time reference type T (target) is checked as follows:
    If S is an array type SC[], that is, any array of components of type SC:
    If T is an interface type, then a compile-time error occurs unless T is
    the type java.io.Serializable or the type Cloneable, the only interfaces implmented by arrays.
    So it looks like arrays implement these interfaces and that is why this assignment is legal. I just didn't realize that.

  • Problem with pro*C performance

    I have a pro*C function that needs around 0.059 seconds to insert a record in a table. I have to improve that.
    This is my function:
    int CSRIRDB_putEvent(char*                         in_CO_MSDN_V,
              char*                         in_CO_IMSI_V,
    char*                         in_CO_GT_V,          
              unsigned int                    in_CO_TIP_EVT_N,
              char*                         in_DS_EVENT_V,
              unsigned int                    in_CO_ERROR_N,
              int                         in_CO_CAUSA_N,
              char*                         in_CO_MAP_VERS_V,
              int                         in_CO_PER_CLT_N,
              char*                         in_CO_MCC_N,
              char*                         in_CO_MNC_N,
         char*                         in_FX_CLT_D)
    int          var_Error = CSRIRDB_OK;
    /*char          var_CadenaSecuencia[15+1];*/
    /*char          var_CadenaFecha[50+1];*/
    short int indicator_SQ_REV_01;
    short int indicator_FX_RCP_EVT_D;
    char          var_Sqlerrmc[5000];
    char           var_msg[512]; /* 512 es la longitud máxima del mensaje oracle incluyendo saltos de línea */
    size_t      var_buf_len, var_msg_len;
    trace_write(TRACE_LEVEL_LOW,"INICIO CSRIRDB_putEvent");
    indicator_SQ_REV_01 = -1;          indicator_FX_RCP_EVT_D = -1;
    EXEC SQL EXECUTE
    DECLARE
    CSRIRDB_OK                    Constant NUMBER(1) := 0;
    CSRIRDB_NON_EXPECTED_ERROR          Constant NUMBER(4) := 4000;
    CSRIRDB_EVT_OK           Constant NUMBER(2) := 14;
    CSRIRDB_EVT_KO           Constant NUMBER(2) := 15;
    CSRIRDB_NEW_CLIENT_EVENT           Constant NUMBER(2) := 16;
    CSRIRDB_SMS_SENT_EVENT           Constant NUMBER(2) := 17;
    /*v_reg_IR_TB_CLTS                    IR_TB_CLTS%ROWTYPE; */
    /*v_Timestamp                    DATE; */
    v_SQ_REV_01                    NUMBER;
    v_FX_RCP_EVT_D                    IR_TB_RCP_EVTS.FX_RCP_EVT_D%TYPE;
    v_CO_MAP_VERS_V                    IR_TB_RCP_EVTS.CO_MAP_VERS_V%TYPE;
    v_DS_EVENT_V                    IR_TB_RCP_EVTS.DS_EVENT_V%TYPE;
    v_CO_PER_CLT_N                    IR_TB_CLTS.CO_PER_CLT_N%TYPE;
    v_CO_MCC_N                    IR_TB_CLTS.CO_MCC_N%TYPE;
    v_CO_MNC_N                    IR_TB_CLTS.CO_MNC_N%TYPE;
    v_FX_RCP_IAS_D                    IR_TB_RCP_EVTS.FX_RCP_IAS_D%TYPE;
    v_ErrCode                         NUMBER;
    v_ErrMsg                         VARCHAR2(5000);
    NON_EXPECTED_ERROR               EXCEPTION;
    BEGIN
    v_CO_PER_CLT_N := :in_CO_PER_CLT_N;     
    if (length(:in_CO_MCC_N)=0) THEN
    v_CO_MCC_N := NULL;
    else
    v_CO_MCC_N := to_number(:in_CO_MCC_N);
    END if;
    if (length(:in_CO_MNC_N)=0) THEN
    v_CO_MNC_N := NULL;
    else
    v_CO_MNC_N := to_number(:in_CO_MNC_N);
    END if;
    if (length(:in_FX_CLT_D)=0) THEN
    v_FX_RCP_IAS_D := NULL;
    else
    v_FX_RCP_IAS_D := to_date(:in_FX_CLT_D,'dd/mm/yyyy hh24:mi:ss');
    END if;
    select decode(:in_CO_MAP_VERS_V,'',NULL,:in_CO_MAP_VERS_V), decode(:in_DS_EVENT_V,'',NULL,:in_DS_EVENT_V)
    into v_CO_MAP_VERS_V, v_DS_EVENT_V
    from dual;
    PA_INSERT.PR_INS_IR_TB_RCP_EVTS(:in_CO_IMSI_V,:in_CO_MSDN_V,v_CO_PER_CLT_N,
                        :in_CO_GT_V,v_CO_MAP_VERS_V,v_CO_MCC_N,v_CO_MNC_N,:in_CO_TIP_EVT_N,:in_CO_ERROR_N,
                        v_DS_EVENT_V,v_SQ_REV_01,v_FX_RCP_EVT_D,v_FX_RCP_IAS_D,:in_CO_CAUSA_N,v_ErrCode,v_ErrMsg);
    if (v_ErrCode<0) THEN
    RAISE NON_EXPECTED_ERROR;
    END if;
    :var_Error := sqlcode;
    :var_Sqlerrmc := sqlerrm;
    EXCEPTION
    WHEN NON_EXPECTED_ERROR THEN
    rollback;
    :var_Error := CSRIRDB_NON_EXPECTED_ERROR;
    :var_Sqlerrmc := v_ErrMsg;
    WHEN OTHERS THEN
    rollback;
    :var_Error := CSRIRDB_NON_EXPECTED_ERROR;
    :var_Sqlerrmc := sqlerrm;
    END;
    END-EXEC;
    trace_write(TRACE_LEVEL_LOW,"FINAL CSRIRDB_putEvent");
    if ((sqlca.sqlcode == 0) && (var_Error == CSRIRDB_OK))
    trace_write(TRACE_LEVEL_HIGH,"Insertado evento OK");
    return CSRIRDB_OK;
    else if (sqlca.sqlcode != 0)
    var_buf_len = sizeof (var_msg);
    sqlglm(var_msg, &var_buf_len, &var_msg_len);
    trace_write(TRACE_LEVEL_ALWAYS, "(%s) (%d)",var_msg,sqlca.sqlcode);
    return CSRIRDB_FATAL_ERROR;
    else /* var_Error != CSRIRDB_OK */
    trace_write(TRACE_LEVEL_HIGH, "(%s)",var_Sqlerrmc);
    return CSRIRDB_NON_EXPECTED_ERROR;
    This is my table:
    CREATE TABLE IR_TB_RCP_EVTS (
    SQ_REV_01 NUMBER (15) NOT NULL,
    CO_IMSI_V VARCHAR2 (15),
    CO_MSDN_V VARCHAR2 (18),
    CO_PER_CLT_N NUMBER (10),
    CO_GT_V VARCHAR2 (15),
    FX_RCP_EVT_D DATE NOT NULL,
    CO_MAP_VERS_V NUMBER (5),
    CO_MCC_N NUMBER (5),
    CO_MNC_N NUMBER (5),
    CO_TIP_EVT_N NUMBER (5) NOT NULL,
    FX_RCP_IAS_D DATE,
    CO_ERROR_N NUMBER (5) NOT NULL,
    CO_CAUSA_N NUMBER (5),
    DS_EVENT_V VARCHAR2 (100) )
    PARTITION BY RANGE (FX_RCP_EVT_D)
    And the procedure PR_INS_IR_TB_RCP_EVTS just inserts.
    What things can I do?

    Fernando,
    There you are, some documentation about array processing:
    To find if you get better performance you can try with an array length of 100.
    Regards,
    Vitor
    Pro*C/C++ Programmer's Guide
    Release 9.2
    2.1.7 Arrays
    Pro*C/C++ lets you define array host variables (called host arrays) and arrays of structures and operate on them with a single SQL statement. Using the array SELECT, FETCH, DELETE, INSERT, and UPDATE statements, you can query and manipulate large volumes of data with ease. You can also use host arrays inside a host variable struct.
    4.8.1 Host Structures and Arrays
    An array is a collection of related data items, called elements, associated with a single variable name. When declared as a host variable, the array is called a host array. Likewise, an indicator variable declared as an array is called an indicator array. An indicator array can be associated with any host array.
    Host arrays can increase performance by letting you manipulate an entire collection of data items with a single SQL statement. With few exceptions, you can use host arrays wherever scalar host variables are allowed. Also, you can associate an indicator array with any host array.
    For a complete discussion of host arrays, see also Chapter 8, " Host Arrays".
    You can use host arrays as components of host structures. In the following example, a structure containing arrays is used to INSERT three new entries into the EMP table:
    struct
    char emp_name[3][10];
    int emp_number[3];
    int dept_number[3];
    } emp_rec;
    strcpy(emp_rec.emp_name[0], "ANQUETIL");
    strcpy(emp_rec.emp_name[1], "MERCKX");
    strcpy(emp_rec.emp_name[2], "HINAULT");
    emp_rec.emp_number[0] = 1964; emp_rec.dept_number[0] = 5;
    emp_rec.emp_number[1] = 1974; emp_rec.dept_number[1] = 5;
    emp_rec.emp_number[2] = 1985; emp_rec.dept_number[2] = 5;
    EXEC SQL INSERT INTO emp (ename, empno, deptno)
    VALUES (:emp_rec);

  • The curious custom panel caper!

    Greetings all, before you instantly dismiss this question as too long/noobish, please read it, it's really quite strange. If a couple of you could at least copy the code I have given and let me know if you get the same results that would be great, as I have access to only one machine to program on at the moment.
    Anyway, back to the story. I have a curious mystery which is somewhat bizzare. I created a very simple program which features a JButton in a frame which is attached to a JFileChooser. Above the button is a custom JPanel which is basically a fancy text box and is supposed to give the filename of the file selected by the JFileChooser. The weird part comes when you click the button... the component (which is already initialized and has had it's value set) seems to have vanished, its still visible, but trying to change it's value or print any of its attributes results in a NPE. Any ideas you can come up with would be of great help. It's probably something really obvious that my tired eyes just can't spot.
    Here is the code... I've stripped it down to the bare minimum to highlight the problem.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Experiment extends JFrame implements ActionListener{
         private File in_file;
         private JFileChooser fc;
         private JButton button;
         private CustomPanel fileField;
         public Experiment(){
              super("Experiment");
              fc = new JFileChooser();
              JPanel box = new JPanel();
              box.setLayout(new BoxLayout(box,BoxLayout.Y_AXIS));
              box.setBorder(BorderFactory.createTitledBorder(
                               BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
                               "Form Details"));
              CustomPanel fileLabel = new CustomPanel(CustomPanel.LABEL,"File",250,"file","file");
              fileLabel.setObject("no file selected");
              box.add(fileLabel);
              button = new JButton("Select File");
              button.addActionListener(this);
              button.setActionCommand("select");
              box.add(button);
              getContentPane().add(box, BorderLayout.NORTH);
              setSize(new Dimension(300,120));
              setResizable(false);
              /* this println is successful */
              System.out.println("fileLabel = "+fileLabel.getText());
         public void actionPerformed(ActionEvent e){
              /* this one is unsuccessful! why?! */
              System.out.println("fileField = "+fileField.getText());
              String command = e.getActionCommand();
              if(command.equals("select")){
                   selectTemplate();
         public void selectTemplate(){
              int returnVal = fc.showDialog(this, "Select");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                in_file = fc.getSelectedFile();
                   fileField.setObject(in_file.getName());
         public static void main(String [] args) throws IOException{
              Experiment s = new Experiment();
              s.show();
    }You will also require the code for the CustomPanel
    import java.io.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    public class CustomPanel extends JPanel {
        public static final int TEXT=0;
        public static final int LABEL=1;
        private JPanel spacer;
        private JLabel label,label2;
        private JTextField textField;
        private DisabledCustomPanel disabledField;
        private String entity,labelTxt,toolTip;
        private int type,labelWidth,fieldWidth,maxSize=1024;
        private boolean notNull = false;
         * Creates a new CustomPanel object
         * @param type the type of component to be generated
          * @param labelTxt the text for the label
          * @param labelWidth the width of the label
          * @param fieldWidth the width of the editable field
          * @param entity the entity that this component corresponds to
          * @param toolTip The tool tip text for this component
        public CustomPanel(int type,String labelTxt,int labelWidth,int fieldWidth,String entity,String toolTip){
              this.type=type;
              this.labelTxt=labelTxt;
              this.entity=entity;
              this.toolTip=toolTip;
              this.labelWidth=labelWidth;
              this.fieldWidth=fieldWidth;
              init();
         * Creates a new CustomPanel object
         * @param type the type of component to be generated
          * @param labelTxt the text for the label
          * @param width the width of the entire component (label/field are balanced 3/7)
          * @param entity the entity that this component corresponds to
          * @param toolTip the tool tip text for this component
        public CustomPanel(int type,String labelTxt,int width,String entity,String toolTip){
              this.type=type;
              this.labelTxt=labelTxt;
              this.entity=entity;
              this.toolTip=toolTip;
              labelWidth=(int)((float)width*0.3);
              fieldWidth=(int)((float)width*0.7);
              init();
        private void init() {
              label=new JLabel(labelTxt,SwingConstants.RIGHT);
              setLayout(new FlowLayout(FlowLayout.LEFT,1,3));
              add(label);
              spacer=new JPanel();
              spacer.setPreferredSize(new Dimension(7,7));
              add(spacer);
              disabledField=new DisabledCustomPanel();
              add(disabledField);
              label.setToolTipText(toolTip);
              disabledField.setToolTipText(toolTip);
              switch(type) {
                   case TEXT:
                       textField=new JTextField();
                       add(textField);
                       textField.setPreferredSize(new Dimension(fieldWidth,25));
                       break;
                   case LABEL:
                       label2=new JLabel("");
                       add(label2);
                       break;
              label.setPreferredSize(new Dimension(labelWidth,25));
              disabledField.setPreferredSize(new Dimension(fieldWidth,25));
              setPreferredSize(new Dimension(labelWidth+fieldWidth,30));
              getActiveComponent().setToolTipText(toolTip);
              setEnabled(false);
         * Returns the contents of the component as a string.
         * @return the String representation of the value held by this component.
        public String getText() {
              Object tmpObj;
              switch(type) {
                   case TEXT:
                       return textField.getText().trim();
                   case LABEL:
                       return label2.getText().trim();
              return "";
         * Sets the contents of the component.
          * @param obj the object to set.
        public void setObject(Object obj) {
              if (obj == null) {
                   clear();
                   return;
              String txt=obj.toString();
              switch(type) {
                   case TEXT:
                       textField.setText(txt);
                       break;
                   case LABEL:
                       label2.setText(txt);
                       break;
              updateDisabled();
         * Updates the field of the component displayed when it is uneditable.
        public void updateDisabled(){
              String txt=getText();
              switch(type){
                   case TEXT: case LABEL:
                       disabledField.setText(txt);
                       break;
         * Clears the component's contents.
        public void clear() {
              disabledField.setText("");
              switch(type){
                   case TEXT:
                       textField.setText("");break;
                   case LABEL:
                       label2.setText("");break;
         * Gets the string you would need to use with an UPDATE statement to
         * represent this component.
         * @return a String consisting of the encapsulated field name and value of
         *         this component in the form <code>field='value'</code> for use
         *         with SQL UPDATE statements.
        public String getUpdateText() {
              switch(type) {
                   case LABEL: return "";
              return entity+"='"+formatSQL(getText())+"'";
         * Gets the string you would need to use with an INSERT statement to
         * represent this component.
         * @return a String consisting of the encapsulated value of this component
         *         in the form <code>'value'</code> for use with SQL INSERT
         *         statements.
        public String getInsertText(){
             return "'"+formatSQL(getText())+"'";
         * Gets the type of this CustomPanel.
         * @return the type of this CustomPanel.
        public int getType() {
              return type;
         * Gets the entity currently associated with this CustomPanel.
         * @return the entity currently associated with this CustomPanel.
        public String getEntity() {
              return entity;
         * Creates part of an UPDATE statement given an array of CustomPanel objects.
          * @param v The array of CustomPanel objects to join.
          * @return a textual representation of the set of CustomPanels of the form
          *         <code>field1='value1', field2='value2'</code> used for UPDATE
          *         statements.
        public static String joinForUpdate(CustomPanel [] v) {
              String vStr="";
              int i;
              for (i=0;i<v.length;i++) {
                  if (vStr.length() > 0 && v.getType() != LABEL) vStr+=", ";
              vStr+=v[i].getUpdateText();
              return vStr;
    * Creates part of an INSERT statement given an array of CustomPanel objects.
         * @param v The array of CustomPanel objects to join.
         * @return a textual representation of the set of CustomPanels of the form
         * <code>'value1', 'value2'</code> used for INSERT statements.
    public static String joinForInsert(CustomPanel [] v){
         String vStr="";
         int i;
         for (i=0;i<v.length;i++) {
              if (vStr.length() >0 && v[i].getType() !=LABEL) vStr+=", ";
              vStr+=v[i].getInsertText();
         return vStr;
    * Fills in multiple components at once using data from an SQLResult
    * object. NB - only the first row from the SQLResult is used.
         * @param v The array of CustomPanel objects
         * @param r The SQLResult containing the destination data
         * @see SQLResult
    public static void fill(CustomPanel [] v,SQLResult r) {
              Object tmpObj;
              int i,col;
              for (i=0;i<v.length;i++) {
              col=r.getNamedColumn(v[i].getEntity());
              if (col != -1) {
                        tmpObj=r.getValueAt(0,col);
                   if (tmpObj != null) v[i].setObject(tmpObj);
    * Sets whether this component may be edited or not.
    * @param enabled whether or not you want the component enabled or not.
    public void setEnabled(boolean enabled) {
              if (!enabled) updateDisabled();
              getActiveComponent().setVisible(enabled);
              disabledField.setVisible(!enabled);
    * Gets the JComponent used by the this CustomPanel to hold data.
    * NB - if you change the contents of the component, you will have to
    * call updateDisabled().
    * @return the JComponent used by this CustomPanel to hold data.
    public JComponent getActiveComponent() {
              switch(type) {
              case TEXT:
              return textField;
              case LABEL:
              return label2;
              return null;
    * Registers whether this component may be allowed to be NULL (empty).
    public void setNotNull(boolean notNull) {
              this.notNull=notNull;
    * Registers the maximum number of characters allowed by the component.
    * @param maxSize the maximum number of characters allowed by the component.
    public void setMaxSize(int maxSize) {
              this.maxSize=maxSize;
    * Verifies the integrity constraints of the component.
         * @param usePopup whether to display a popup if there's a problem or not.
         * @return <code>false</code> if the component has a problem,
         * <code>true</code> otherwise.
    public boolean verify(boolean usePopup) {
              Object tmpObj;
              switch(type) {
                   case TEXT:
                   if (notNull && textField.getText().length()==0) {
                        if (usePopup) popup("Please complete the '"+labelTxt+"' field.");
                        return false;
                   if (textField.getText().length() > maxSize) {
                        if (usePopup) popup("'"+labelTxt+"' may only contain up to "+
                                  maxSize+" characters.");
                        return false;
                   break;
              return true;
    * Verifies an entire array of components, stopping and popping up an
    * error if there's a problem.
         * @param v the target array of CustomPanels to check for validity.
         * @return <code>false</code> if there's a problem, <code>true</code>
         * otherwise.
    public static boolean sanityCheck(CustomPanel [] v) {
              int i;
              for (i=0;i<v.length;i++)
              if (!v[i].verify(true)) return false;
              return true;
         * Conveniance method to popup JOptionDialog targeted at this CustomPanel.
         * @param message the message to popup.
         private void popup(String message) {
              JOptionPane.showMessageDialog((JPanel)this,message,"Warning",JOptionPane.WARNING_MESSAGE);
         * Method to format Strings for SQL queries and statements, uses character
         * stuffing to protect special characters.
         * @param txt the String to format.
         * @return the formatted String.
         private static String formatSQL(String txt) {
              String out="";
              String chr;
              int i;
              for (i=0;i<txt.length();i++) {
              chr=""+txt.charAt(i);
              if (chr.equals("'")) chr="''";
              out+=chr;
              return out;
    * An easily-readable, un-editable field of text. Used by CustomPanel, but may
    * be used alone if necessary.
    * @see CustomPanel
    public class DisabledCustomPanel extends JPanel{
    private JLabel label;
    * Creates a new DisabledCustomPanel
    public DisabledCustomPanel() {
              super(new GridLayout());
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
              label=new JLabel();
              label.setFont(new Font("dialog",Font.PLAIN,12));
              add(label);
              setBorder(BorderFactory.createLineBorder(Color.GRAY));
    * Sets the text shown by this component.
         * @param txt the text to be shown.
    public void setText(String txt) {
              label.setText(" "+txt);
    * Sets the tool tip text for this component.
         * @param toolTip the tool tip text for this component.
    public void setToolTipText(String toolTip) {
              label.setToolTipText(toolTip);

    You are referencing an uninitalized component.
    I changed the code below to use the class member var fileField
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Experiment extends JFrame implements ActionListener
        private File in_file;
        private JFileChooser fc;
        private JButton button;
        private CustomPanel fileField;
        public Experiment()
            super("Experiment");
              setDefaultCloseOperation( EXIT_ON_CLOSE );
            fc = new JFileChooser();
            JPanel box = new JPanel();
            box.setLayout(new BoxLayout(box,BoxLayout.Y_AXIS));
            box.setBorder(BorderFactory.createTitledBorder(
                                                          BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
                                                          "Form Details"));
            //This was a local var that you were using.
           //CustomPanel fileLabel = new CustomPanel(CustomPanel.LABEL,"File",250,"file","file");          
             //You needed to initalize the member var.
            fileField = new CustomPanel(CustomPanel.LABEL,"File",250,"file","file");
            fileField.setObject("no file selected");
            box.add(fileField);
            button = new JButton("Select File");
            button.addActionListener(this);
            button.setActionCommand("select");
            box.add(button);
            getContentPane().add(box, BorderLayout.NORTH);
            setSize(new Dimension(300,120));
            setResizable(false);
            /* this println is successful */
            System.out.println("fileLabel = "+fileField.getText());
        public void actionPerformed(ActionEvent e)
            /* this one is unsuccessful! why?! */
            System.out.println("fileField = "+fileField.getText());
            String command = e.getActionCommand();
            if( command.equals("select") )
                selectTemplate();
        public void selectTemplate()
            int returnVal = fc.showDialog(this, "Select");
            if( returnVal == JFileChooser.APPROVE_OPTION )
                in_file = fc.getSelectedFile();
                fileField.setObject(in_file.getName());
        public static void main(String [] args) throws IOException{
            Experiment s = new Experiment();
            s.show();

  • What is Reflection in a nutshell?

    Is it simply how the JVM can determine at runtime what methods a class has or what ?

    That's a part of it. In general it's about finding out all kinds of information about classes and objects at runtime, not just methods.
    http://java.sun.com/docs/books/tutorial/reflect/
    Starts off by saying:
    The reflection API represents, or reflects, the classes, interfaces, and objects in the current Java Virtual Machine. You'll want to use the reflection API if you are writing development tools such as debuggers, class browsers, and GUI builders. With the reflection API you can:
    Determine the class of an object.
    Get information about a class's modifiers, fields, methods, constructors, and superclasses.
    Find out what constants and method declarations belong to an interface.
    Create an instance of a class whose name is not known until runtime.
    Get and set the value of an object's field, even if the field name is unknown to your program until runtime.
    Invoke a method on an object, even if the method is not known until runtime.
    Create a new array, whose size and component type are not known until runtime, and then modify the array's components.

  • Navigating between different FocusTraversalPolicy

    Ok, I've struggled with this for a bit. I can't quite figure out where I've gone wrong.
    I have a window with some fields in the top of the window, and a JTabbedPane in the bottom. The tabbed pane includes several tabs implemented as separate panels. Each of these panels has a custom focus policy, which allows us to specify the exact order and components for tabbing. The custom policy starts like this:
    public class MyTraversalPolicy extends FocusTraversalPolicy {
        private List componentList;
        public MyTraversalPolicy(Component[] components) {
            componentList = Arrays.asList(components);       
        }When the panel is created, we pass in an array of components in the proper tabbing order, and setFocusCycleRoot(true).
    The window which contains this panel has a different tabbing policy (currently default). Where I'm hitting a problem is at the beginning and the end of my custom tabbing policy. I want to navigate to the appropriate location in the containing window, but can't seem to accomplish this.
    My most recent attempt was to cycle through parent components until I found one with a focus policy, and try to use that to find the next component. It didn't work.
               Container c = focusCycleRoot.getParent();
                while (f == null) {
                    f = c.getFocusTraversalPolicy();
                    if (c.getParent() == null) break;
                    c = c.getParent();
                if (f != null) { --do something here;}Is there an easy way to link focus policies together which I am missing?
    Thanks,
    -Dave

    Thanks Frank. It worked. I have one more issue. I do have two pages http://localhost:7101/faces/test1 and http://localhost:7101/faces/test2 . test2 is a create form page. On submission of this form the page is frowarding to page1 using the action property. When I am accessing the page2 the url is : test2?_afrLoop=188792691646005&_afrWindowMode=0&_adf.ctrl-state=19nrptpqfx_189. On submission of this page the resulting page1 url is :test2?_adf.ctrl-state=19nrptpqfx_189.Is it possible to redirect to the url http://localhost:7101/faces/test1 after submission ?With out the ?_afr.ctr-state parameters .. Like jsp's send.redirect method rather that jsp: forward kind of action?
    Thanks
    Sunees

  • How to Hide a Tab in a jTabbedPane

    Hello, I am trying to toggle the Visibility of a tab in a jTabbedPane... I have tried every permutation of these that I could think of:
    myTab1.Visible(False);
    myTab1.Hide();
    myTab1.updateUI();
    myTabControl.doLayout();
    myTabControl.updateUI();
    myTabControl.repaint();
    myTabControl.Layout();What am i missing?
    Please help.

    Its not complicated
    Object myTabls[]=new Object[tabbedPane.getTabCount()];
    this will create an array.
    now
    for (int a=0;a<tabbedPane.getTabCount();a++)
    myTabs[a]=tabbedPane.getComponentAt(a);
    with an array of Components and their placement (index)
    you can do what you want.
    I think Java Merlin (1.4) has a setVisible for a tab, and my guess is that they have implemented that this way.
    You can do it either way.

  • How do you free memory when applet ends?

    I have an applet that uses 4 jframes. Any of the frames are set to call both stop() and destroy() whenever user clicks "Exit" or "X" in upper right corner of a frame.
    The applet destroy() method does the following:
    myAOS32001Frame = null;
    myAOS32002Frame = null;
    myAOS32003Frame = null;
    myAOS32004Frame = null;
    myMemoryChangeThread.stop();
    try {
    URL endedURL = new URL(this.getCodeBase(), "AOS320acEnded.html");
    this.getAppletContext().showDocument(endedURL);
    } // try
    catch (MalformedURLException urlexc) {
    urlexc.printStackTrace();
    } // catch
    This doesn't free up any memory at all. Only when the user closes the browser altogether does the memory free up.
    Do I have to set EVERY object (those within frames) to null? How do I set the main applet object (the JApplet class instance) to null (not just its child frames)? Should the garbage collector be run one last time? In what order should all these things occur?
    If every object needs to be set to null, anybody have a nice tidbit of code that loops through array of components (and properties) or something and sets them to null?
    Thanks.

    Thank you both for the tips. They were helpful.
    Now my mission is to make the applet as small as possible. It appears the base JVM occupies about 18MB of memory initially, and then my applet uses 12MB more (at times), and the JVM "reserves" about 10MB more.
    The only part under my control is the 12MB, it appears, and I'd be interested in general tips to make that as small as possible (maybe by using certain variable types instead of ones currently used, etc.). But I'll ask that in a different thread.

  • Cast to a user class

    Hi.
    Suposse that I have got a class "MyClass" and then i add an object of "MyClass" into a container. If i retrieve all the component of the container with the method container.getComponents() i cant cast the component that i am stored in the array into "MyClass". How can i do it?? Do you know a way to do it??
    Thank you.

    MyClass must extend Component to have any chance at working. Even if MyClass extends Component, I believe you can not cast an array of one type to an array of another, even if the elements of the array have a relationship that allows the cast. For example...
    Component[] comps = new Component[2];
    comps[0]=new TextField();
    comps[1]=new TextField();
    TextField[] obs = (TextField[]) comps;
    Even though a TextField is a Component, and the elements of the array are TextFields, you get a class cast exception if you run the above code. The getComponents() method returns an array of Components so I believe you will have to cast each element.

Maybe you are looking for

  • H.264 camera type

    Flash works with all USB web cameras - but what are the limitations (if any) on using a s-video or RGB connector on a graphics card so a camera with enough quality for H.264 streaming can be used? Does Flash recognise them? As the encoding will be gr

  • Order Split

    Hi, I would like to know if thera any way to do an split order after the order had been schedule. I mean after the status of the operation is mark as a PLAN. This status turn on after the order had been allocated using the transaction CM21. I really

  • Can recortsets be used as includes

    i have a few recordsets in one page and the page is becoming sluggish, is it possible to set them on a new page and have them as includes or do they need to be on the same page thanks

  • トラブル「¥pre¥Backend¥Src¥Time¥Time.cpp-389」

    DVD書き込みの際,下記メッセージ 「¥pre¥Backend¥Src¥Time¥Time.cpp-389」が出てしまい,書き込みが一時停止される.その後,「続行」を選択するとDVD書き込みが再開され,DVDは完成す るが,キャプチャー画面(シーン画面)のサムネイルが,動く設定で書き込んだにもかかわらず,動かない.と,いうトラブルです.それ以外は,完成したDVDは,観られるのですが.宜しくお願い いたします.

  • Get XML before sending to End Point

    Hi All, Can anyone give me an idea of how to get the actual XML in requestEnv. I want to save the XML before I send it to the web service end point so I can know exactly what I have sent for debugging reasons. I have done a good bit of googling on th