Return of the variables

In a block PLSQL, where I attribute values for two variables (select columns into variables), if the clause where I will not be satisfied and not to return no line for this select, that values are attributed for the variables (of the clause into)?
I ask this exactly because in one of my functions, the return is being = NULL, being attributed a value for the return variable, then in the first line of script.

It follows below my function:
CREATE OR REPLACE FUNCTION dbf_ssp_tramitado(a_entidade_for NUMBER,a_solicitacao NUMBER,a_tipo VARCHAR2,a_usuario VARCHAR2)
RETURN VARCHAR2
IS
w_tramitado VARCHAR2(1);
w_entidade_tram NUMBER(10);
w_entidade_aux NUMBER(10);
w_usuario_req VARCHAR2(16);
w_tipo     VARCHAR2(1);
BEGIN
w_tramitado:='S';
w_entidade_aux:=NULL;
IF a_tipo = 'R' THEN
SELECT i_entidades_req,i_usuarios_req INTO w_entidade_aux,w_usuario_req
FROM bethadba.ssp_solicitacoes_suporte
WHERE i_entidades_for = a_entidade_for AND
i_solicitacoes = a_solicitacao;
ELSE
SELECT i_entidades_for,i_usuarios_req INTO w_entidade_aux,w_usuario_req
FROM bethadba.ssp_solicitacoes_suporte
WHERE i_entidades_for = a_entidade_for AND
i_solicitacoes = a_solicitacao;
END IF;
w_entidade_tram := NULL;
w_tipo := NULL;
SELECT i_entidades_tram, tipo INTO w_entidade_tram, w_tipo
FROM bethadba.ssp_tramites_solicitacoes, bethadba.ssp_status
WHERE ssp_tramites_solicitacoes.i_entidades_for=ssp_status.i_entidades
AND ssp_tramites_solicitacoes.i_status=ssp_status.i_status
AND i_entidades_for = a_entidade_for
AND i_solicitacoes = a_solicitacao
AND upper(ssp_tramites_solicitacoes.visibilidade) IN('A',upper(a_tipo))
AND ROWNUM < 2
ORDER BY i_tramites DESC;
IF 'X' = NVL(w_tipo, '') THEN w_tramitado := 'X';
ELSIF w_entidade_tram IS NOT NULL THEN
IF w_entidade_tram = NVL(w_entidade_aux,-1) THEN w_tramitado:='N';
END IF;
ELSIF a_tipo = 'R' THEN
IF w_usuario_req = a_usuario THEN w_tramitado:='N';
END IF;
END IF;
RETURN w_tramitado;
END;
In some cases, the command
SELECT i_entidades_tram, tipo INTO w_entidade_tram, w_tipo
FROM bethadba.ssp_tramites_solicitacoes, bethadba.ssp_status
WHERE ssp_tramites_solicitacoes.i_entidades_for=ssp_status.i_entidades
AND ssp_tramites_solicitacoes.i_status=ssp_status.i_status
AND i_entidades_for = a_entidade_for
AND i_solicitacoes = a_solicitacao
AND upper(ssp_tramites_solicitacoes.visibilidade) IN('A',upper(a_tipo))
AND ROWNUM < 2
ORDER BY i_tramites DESC;
does not return no line, and seems that no value for the variables is not attributed, and seems that more is not executed nothing of this point in ahead.

Similar Messages

  • I can't over give my variable to the return in the get Method!

    Hello Java Cracks
    At the moment I am working with JDOM. I am able to get access to the XML File with JDOM, but when I want to send, the value of a variable, which I get from the XML File it is not possible. When I try to send the variable to the get Method (getDtdVersion), the value I over give is always �null�. Please help me, and say what the problem is?
    I also post you the second class, where I want to use the variable I over give.
    Here is my code:
    Class 1, I take the String from this class. See the arrow
    package FahrplanXML;
    import java.io.File;
    import java.io.IOException;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import org.jdom.Attribute;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    import org.xml.sax.InputSource;
    public class FileAuswahl {
    private File filenames;
    private String scheduledtdversion;
    public void ablauf() throws JDOMException, IOException {
    FileAuswaehlen();
    saxwer();
    grundoberflaeche xmloberflaeche = new grundoberflaeche();
    xmloberflaeche.grundoberflaechen();
    public void FileAuswaehlen() {
    JFileChooser datei = new JFileChooser();
    datei.setFileFilter(new FileFilter()
    @Override public boolean accept (File f)
    return f.isDirectory() ||
    f.getName().toLowerCase().endsWith(".xml");
    @Override public String getDescription()
    return "XML-Files";
    int state = datei.showOpenDialog(null);
    if (state == JFileChooser.APPROVE_OPTION )
    filenames = datei.getSelectedFile();
    System.out.println (filenames);
    if (filenames != null)
    try {
    System.out.print(filenames);
    saxwer();
    } catch (JDOMException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    else
    System.out.println("Kein File ausgew�hlt");
    else
    System.out.println("Auswahl abgebrochen");
    System.exit(0);
    //Ausgew�hlter Dateiname an saxwer �bergeben
    public File getNames() {
    System.out.println (filenames);
    return this.filenames;
    public void saxwer() throws JDOMException, IOException {
    //FileAuswahl filename = new FileAuswahl();
    File files = getNames();
    System.out.println (files);
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(files);
    Element schedulemessage = doc.getRootElement();
    //Root Element auslesen
    String sch_msg_dtdversion = schedulemessage.getAttributeValue ("DtdVersion"); // <---
    scheduledtdversion = sch_msg_dtdversion;
    new grundoberflaeche().grundoberflaechen();
    public String getDtdVersion() {
    System.out.println (scheduledtdversion);
    return this.scheduledtdversion;
    Now, you will see the class in which I pass the String. See also arrow...
    package FahrplanXML;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.text.Caret;
    import org.jdom.Attribute;
    import org.jdom.JDOMException;
    public class grundoberflaeche {
    // Layout f�r Laender vorbereiten
    static void addComponent (Container cont,
    GridBagLayout diversemoegl,
    Component laenderdetails,
    int x, int y,
    int width, int height,
    double weightx, double weighty )
    GridBagConstraints grundoberflaechen = new GridBagConstraints();
    grundoberflaechen.fill = GridBagConstraints.BOTH;
    grundoberflaechen.gridx = x; grundoberflaechen.gridy = y;
    grundoberflaechen.gridwidth = width; grundoberflaechen.gridheight = height;
    grundoberflaechen.weightx = weightx; grundoberflaechen.weighty = weighty;
    diversemoegl.setConstraints(laenderdetails, grundoberflaechen);
    cont.add(laenderdetails);
    //Ausw�hlen des XML Files
    public void XMLAuswaehlen() {
    JFrame xmlauswahl = new JFrame("Fahrplan ausw�hlen");
    xmlauswahl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container laenderdetails = xmlauswahl.getContentPane();
    GridBagLayout diversemoegl = new GridBagLayout();
    laenderdetails.setLayout(diversemoegl);
    JButton dateiauswahl = new JButton ("Datei ausw�hlen");
    addComponent(laenderdetails,diversemoegl,dateiauswahl,1,1,1,1,1,1);
    ActionListener ersterdateiauswaehler = new ActionListener()
    public void actionPerformed( ActionEvent e)
    try {
    new FileAuswahl().ablauf();
    } catch (JDOMException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    dateiauswahl.addActionListener(ersterdateiauswaehler);
    xmlauswahl.setSize(150,70);
    xmlauswahl.setVisible(true);
    //Layout machen
    public void grundoberflaechen() {
    JFrame fahrplan = new JFrame("Fahrplanauswahldetails");
    fahrplan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container laenderdetails = fahrplan.getContentPane();
    GridBagLayout diversemoegl = new GridBagLayout();
    laenderdetails.setLayout(diversemoegl);
    //Klassenobjekt aufbauen
    FileAuswahl fileauswahl = new FileAuswahl();
    // Labelsbauen und einbauen in den Fahrpl�nen
    String dtdversion = fileauswahl.getDtdVersion(); // <---
    System.out.println(dtdversion);
    JTextField DtdVersion = new JTextField(1);
    DtdVersion.setText(dtdversion);
    JTextField fahrplanzeit = new JTextField(1);
    fahrplanzeit.setText("123");
    JTextField fahrplanzeita = new JTextField(1);
    fahrplanzeita.setText("piips");
    //JButton oesterreich = new JButton("�sterreich");
    //JButton italien = new JButton("Italien");
    //JButton frankreich = new JButton("Frankreich");
    //JButton spanien = new JButton("Spanien");
    addComponent(laenderdetails,diversemoegl,new JLabel("Fahrplandetails"),0,0,1,1,0,0);
    addComponent(laenderdetails,diversemoegl,DtdVersion,1,0,1,1,0,0);
    addComponent(laenderdetails,diversemoegl,fahrplanzeit,2,0,1,1,0,0);
    addComponent(laenderdetails,diversemoegl,fahrplanzeita,3,0,1,1,0,0);
    // Action Listener f�r Dateiauswahl
    // Action Listener f�r das Speichern der Datei
    //addComponent(laenderdetails,diversemoegl,frankreich,2,1,1,1,0,0);
    //addComponent(laenderdetails,diversemoegl,spanien,3,1,1,1,0,0);
    fahrplan.setSize(600,750);
    fahrplan.setVisible(true);
    Thank you very much for your help....
    Your Java Learner

    I suspect you are setting the scheduledtdversion member in one instance of your FileAuswahl class, but are creating yet another instance of that class and printing the member of that instance, which is null. I notice you are creating a new FileAuswahl instance each time something happens, rather than reusing the same instance.
    FileAuswahl fileauswahl = new FileAuswahl();Ok, new object here. Not the same one that you previously set the scheduledtdversion member in
    String dtdversion = fileauswahl.getDtdVersion();It's null of course, for the reason above.

  • Variable to hold the number of records returned by the SQL Query.

    Hi folks,
    Is there any way to hold the number of records that could be returned by the SQL query we use to make a report?
    If so, please do come up with the answer.
    Cheers,
    PCZ.

    Hi there,
    Well, there is no actual business requirement.
    It is just the curiosity of mine.
    I would like to handle
    1) the number of records our report query returns or
    2) the query itself
    to write a better pl/sql code in any trigger/program unit, if any business logic beckons in future.
    Cheers,
    PCZ.

  • Use of Return and Notify_url variables offered by PayPal

    I have been integrating PayPal into my application (ASP NET MVC) where I made some analysis about PayPal (went through their documentation about the integration). Created a PayPal sandbox account and can transfer the amount.What I want to know is about the `return` and `notify_url` variables. I have enabled `auto return` in my account and also enabled `PDT`. My form variable is like this:<input type="hidden" name="notify_url" value="http://localhost:xxx/xx/Notify">
    <input type="hidden" name="return" value="http://localhost:xx/xx/Return">As I have surfed in net, what they state about `Return` and `notify_url` is:> The "return" URL to which PayPal redirects buyers’ browser after they complete their payments. For example, specify a URL on your site that displays a “Thank you for your payment” page. Default is nothing is specified – PayPal redirects the browser to a PayPal webpage. Note, you must have "Auto Return" enabled in your Account Profile settings in order for this variable to work.
    >PayPal returns data back to your site via what they call IPN. Its really just a callback to a URL you specify. You can set this URL via the variable `notify_url` you can send to PayPal.From the above quotes what I understand is that PayPal will post `IPN` variables to `notify action` once the payment done before auto redirecting to the page I set (I mean customer may go the application page or they may close the session).But only return action alone hitting not the `Notify_url`.Correct me if I misunderstood the concept and let me know if it was still Unclear.

    Yes, it's not present in the code I have posted but I have tried this as well.
    It didn't work, as expected, because soap/axis is on top of http and not https and because my proxy uses http as well (or at least that's what I have learned so far).
    In fact, I have tried all combinations between http.\*, https.\*, and Authenticator without success.
    I think the problem is more soap/axis related. The solution for axis2 seems somewhat 'trivial' (and well explained over the web) while it's not for axis1.
    Regards
    Rob
    Edited by: RobR on Nov 29, 2007 4:37 AM
    Edited by: RobR on Nov 29, 2007 9:56 AM

  • How to clear the variable value in session store?

    I'll try to build form for search. There are LOV and
    search button on form. When user don't select anything then push
    search button, I'd like the report to show query everything. I
    mean the report will show like condition where id like '%'.
    And I send variable between form to report by using session
    store.
    I select nothing in LOV but value that return by LOV is
    not null. It's in stead of old value of LOV.
    Please tell me.. How to clear the variable value in
    session store? I'd like to set it to null. If you have greater
    way to do like this, please tell me.
    Thank you.

    Please suggest on this..
    Thanks.

  • Read from sql task and send to data flow task - [OLE DB Source [1]] Error: A rowset based on the SQL command was not returned by the OLE DB provider.

    I have created a execut sql task -
    In that, i have a created a 'empidvar' variable of string type and put sqlstatement = 'select distinct empid from emp'
    Resultset=resultname=0 and variablename=empidvar
    I have added data flow task of ole db type and I put this sql statement under sql command - exec emp_sp @empidvar=?
    I am getting an error.
    [OLE DB Source [1]] Error: A rowset based on the SQL command was not returned by the OLE DB provider.
    [SSIS.Pipeline] Error: component "OLE DB Source" (1) failed the pre-execute phase and returned error code 0xC02092B4.

    shouldnt setting be Result
    Set=Full Resultset as your query returns a resultset? also i think variable to be mapped should be of object type.
    Then for data flow task also you need to put it inside a ForEachLoop based on ADO.NET recordset and map your earlier variable inside it so as to iterate for every value the sql task returns.
    Also if using SP in oledb source make sure you read this
    http://consultingblogs.emc.com/jamiethomson/archive/2006/12/20/SSIS_3A00_-Using-stored-procedures-inside-an-OLE-DB-Source-component.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Return only the columns with different values.

    Hi all,
    I am trying to solve a seemingly trivial problem but can't seem to get any straight answer anywhere in any forum. Consider a single table with 5 columns and only two rows:
    row_id           first_name         last_name        age            gender
    1                    John                  doe               27             M
    1                    Jane                  doe               27              F  Assume there is no primary key or any other constraint. Also assume that there are only and only two rows in this table. So I basically need a query that, in the above set of rows, would return first_name and gender, as they are the only differing columns in the two rows, and also their values. Even if i can somehow get the column names that are differing that would be enough as I can easily access the values later on. Also it is important to remember that I may not know the column names of all the columns, so basically I somehow must utilize user_tab_columns in the process.
    Any help appreciated.
    Edited by: 894302 on May 1, 2013 10:35 AM

    Hi,
    894302 wrote:
    There is nothing wrong with it. Here you have added all the columns in the decode statement as you already know all the column names. What if there is a table whose column names are unknown i.e I can pass the table as a parameter to a procedure and I would need to loop through all the columns and then perform this operation.Table- and column names must be hard-coded into the query. If you want to figure out what the columns are at run time, given only hte table name, then you need dynamic SQL.
    All the column names are in the data dictionary view all_tab_columns. You can easily loop through them to build exactly as many lines like
    DECODE (a.row_id,     b.row_id,     NULL, 'row_id,')     ||as you need in the SELECT clause. The FROM clause is dynamic, too: it has the variable table name in 2 places.
    But i am not sure if it worth the effort to do it on the database side. Probably easier to do it on the middle tier such as .NET, which where the business logic is implemented in my company.I don't know much about .NET, so I can't compare them
    It's not very hard to do in PL/SQL (as dynamic SQL goes).
    Edited by: Frank Kulash on May 1, 2013 4:39 PM
    Here's a function that does the dynamic SQL:
    CREATE OR REPLACE FUNCTION  different_columns
    (  in_table_name  IN  VARCHAR2
    ,  in_owner_name  IN  VARCHAR2     DEFAULT USER
    RETURN VARCHAR2
    IS
        return_str     VARCHAR2 (4000);
        sql_str     VARCHAR2 (1000);
    BEGIN
        sql_str := 'SELECT  RTRIM ( ';
        FOR  c  IN ( SELECT    column_name
                          ,        ROW_NUMBER () OVER (ORDER BY  column_id  DESC)  AS r_n
                          FROM        all_tab_columns
               WHERE        owner     = in_owner_name
               AND        table_name     = in_table_name
               ORDER BY  column_id
        LOOP
            sql_str := sql_str || '                DECODE (a.'
                         || c.column_name
                      || ', b.'
                      || c.column_name
                      || ', NULL, '''
                      || c.column_name
                      || ', '')';
         IF  c.r_n > 1
         THEN
             sql_str := sql_str || ' ||';
         END IF;
         sql_str := sql_str || CHR (10);
        END LOOP;
        sql_str := sql_str || '              , '', '''     || CHR (10)
                                || '              )'          || CHR (10)
                     || 'FROM  "' || in_owner_name
                     || '"."' || in_table_name
                     || '" a'                    || CHR (10)
                     || 'JOIN  "' || in_owner_name
                     || '"."' || in_table_name
                     || '" b ON a.ROWID < b.ROWID';
        -- dbms_output.put_line (sql_str);     -- for debugging
        EXECUTE IMMEDIATE   sql_str  INTO  return_str;
        RETURN  return_str;
    END  different_columns;
    SHOW ERRORSYou can call it in SQL like this:
    SELECT     different_columns ('RHIT_TABLE_X')  AS dc
    FROM     dual
    ;Using PL/SQL, we might not need RTRIM, at least not in the query. I'll leave that as an exercise.

  • Need to know the size of the variable declared as Xstring

    Hi All,
    I have got all the files from the applications server(for a given path) and have zipped all in to one file. But now need to find the size of it and throw a error message if it is less than a byte.
    Variable whick holds all the zipped data is " zip_content ". it is declared as " data: zip_content type xstring ".
    Not sure how to get the size of the variable " zip_content ".  
    When checked around found FM : EPS_GET_FILE_ATTRIBUTES but this requires File name or path. In my case I have only the
    variable.
    Thanks in Advance
    Regards
    Jithu

    Hi,
    When using
    data: l_cnt type i.
    l_cnt = xstrlen( g_zip_content ) .
    xstrlen will return only in byte mode and not in character mode.
    Thus the value l_cnt = 12112 which you got is in bytes which can be used to check your condition.
    Regards,
    Vik
    Edited by: vikred on Jul 29, 2009 4:01 PM

  • There is an invalid number of result bindings returned for the ResultSetType

    SSIS SQL Task:  Single Row Result Set
    Code was updated to test for data in target:  If Exists Do Merge  ELSE Do Insert
    Previously was just a merge that Output $Action to @ChangeSum and then @ChangeSum queried for updates and inserts
    That all worked but after injecting new code I receive the error There is an invalid number of result bindings returned for the ResultSetType that I don't know what it means or how to troubleshoot.
    Inject New Code:
    IF OBJECT_ID('tempdb..##TblTemp', 'U') IS NOT NULL
    DROP TABLE ##TblTemp
    Declare @sql nvarchar(max);
    set @sql = @TestForData
    exec (@sql);
    IF EXISTS  (select top 1 * from ##TblTemp)
           Begin
    --Beginning of existing code
               begin transaction;
                begin try
                declare @MergeQuery varchar(max)
                set @MergeQuery = convert(varchar(max), @MergeQuery1) +  convert(varchar(max), @MergeQuery2)
                + ' ' + convert(varchar(max), @MergeQuery3)
                + ' ' + convert(varchar(max), @MergeQuery4)
                + ' ' + convert(varchar(max), @MergeQuery5);
                exec(@MergeQuery);
                end try
                begin catch
                    declare
                    @Message VARCHAR(4000)
                    ,@Severity INT
                    ,@State  INT;
                    select
                    @Message = ERROR_MESSAGE()
                    ,@Severity = ERROR_SEVERITY()
                    ,@State = ERROR_STATE();
                    if @@TRANCOUNT > 0
                    rollback transaction;
                    raiserror(@Message, @Severity, @State);
                end catch;
                if @@trancount > 0
                begin
                    commit transaction;
                end
    --End of existing code
          End
    else
           Begin
        declare @InsertQuery nvarchar(max)
        set @InsertQuery = convert(varchar(max),@InsertQuery1)
        exec (@InsertQuery);
          end
    Drop Table ##TblTemp
    =================================
    SSIS Variable @InsertQuery1:
    This variable is executed in SQL Task and the last 3 lines I expect a single row of Insert & Update counts to be returned.
       declare @ChangeSum table(change varchar(25));
       declare @Inserted int = 0;
       declare @Updated int = 0;
    While 1 = 1  
        Begin  
            INSERT INTO [R_Paid].[BusCodeF454x93]
            OUTPUT Inserted.Sta3n INTO @ChangeSum
            SELECT TOP 1000 s.*
            FROM [R_Stage].[BusCodeF454x93] s
            WHERE NOT EXISTS
              SELECT 1
                FROM [R_Paid].[BusCodeF454x93]
                WHERE STA3N=S.STA3N and [BusCodeF454x93IEN] = s.[BusCodeF454x93IEN]
           IF @@ROWCOUNT  = 0 BREAK       
    END
       set @Inserted = (select count(*) from @ChangeSum );
       set @Updated = 0;
     select @Inserted as Inserted, @Updated as Updated;

    "SELECT " + (DT_WSTR,50)@[User::TargetExists] + " = CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END
    FROM " + (DT_WSTR, 100) @[User::DataDestinationTable]
    must do the trick
    The T-SQL merge allows both inserts and updates:
    MERGE Target AS T
    USING Source AS S
    ON (T.EmployeeID = S.EmployeeID)
    WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%'
    THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName)
    WHEN MATCHED
    THEN UPDATE SET T.EmployeeName = S.EmployeeName
    WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'
    THEN DELETE
    OUTPUT $action, inserted.*, deleted.*;
    ROLLBACK TRAN;
    GO
    Arthur My Blog

  • How can I get the variable with the value from Thread Run method?

    We want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
         public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    // I should get Inside the run method::: But I get only Inside
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";
    NB: if i write the variable in to a file I am able to read it from external method. This I dont want to do

    We want to access a variable from the run method of a
    Thread externally in a class or in a method. I presume you mean a member variable of the thread class and not a local variable inside the run() method.
    Even
    though I make the variable as public /public static, I
    could get the value till the end of the run method
    only. After that scope of the variable gets lost
    resulting to null value in the called method/class..
    I find it easier to implement the Runnable interface rather than extending a thread. This allows your class to extend another class (ie if you extend thread you can't extend something else, but if you implement Runnable you have the ability to inherit from something). Here's how I would write it:
    public class SampleSynchronisation
      public static void main(String[] args)
        SampleSynchronisation app = new SampleSynchronisation();
      public SampleSynchronisation()
        MyRunnable runner = new MyRunnable();
        new Thread(runner).start();
        // yield this thread so other thread gets a chance to start
        Thread.yield();
        System.out.println("runner's X = " + runner.getX());
      class MyRunnable implements Runnable
        String X = null;
        // this method called from the controlling thread
        public synchronized String getX()
          return X;
        public void run()
          System.out.println("Inside MyRunnable");
          X = "MyRunnable's data";
      } // end class MyRunnable
    } // end class SampleSynchronisation>
    public class SampleSynchronisation
    public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run
    method "+sathr.x);
    // I should get Inside the run method::: But I get
    only Inside
    class sampleThread extends Thread
    public String x="Inside";
    public void run()
    x+="the run method";
    NB: if i write the variable in to a file I am able to
    read it from external method. This I dont want to do

  • Why do we declare the variables private in a bean

    Hi,
    when we create a bean in the MVC architecture why do we declare the variables private. Also when do we use the access specifier private.
    Regards,
    Prashant

    pksingh79 wrote:
    Hi ^^,
    thanks for replying.I had a discussion with one of my trainers and he was of the opinion that the variables should generally be declared private. In this way we prevent classes from accessing and setting illegal values to those variables.
    Say for instance we have the class person as follows:
    public class Person
    int age;
    setAge(int age)
    if (age < 0)
    return null
    Person p = new Person() ;
    p.age = -2;
    //this would be perfectly legal
    //where as if we declare the variable as private as follows:
    public class Person
    private int age;
    setAge(int age)
    if (age < 0)
    return null
    Person p = new Person() ;
    // P.age = -2;   this would be illegal as age is private and would have to be accessed by the method defined above.
    p.setAge(-2);
    //the cbove line would retun null values.
    public class Person {
        private int age;
        public void setAge(int age) {
            if (age < 0) {
                throw new IllegalArgumentException("...");
            this.age = age;
    }

  • How do I change the variable across different methods

       A tic-tac-toe board.
    public class TicTacToe
       private String[][] board;
       private static int SIZE = 3;
          Constructs an empty board.
       public TicTacToe()
          board = new String[SIZE][SIZE];
          // Fill with spaces
          for (int i = 0; i < SIZE; i++)
             for (int j = 0; j < SIZE; j++)
                board[i][j] = " ";
          Sets a field in the board. The field must be unoccupied.
          @param i the row index
          @param j the column index
          @param player the player ("x" or "o")
       public void set(int i, int j, String player)
          if (board[i][j].equals(" "))
             board[i][j] = player;
          Creates a string representation of the board, such as
          |x  o|
          |  x |
          |   o|
          @return the string representation
       public String toString()
          String r = "";
          for (int i = 0; i < SIZE; i++)
             r = r + "|";
             for (int j = 0; j < SIZE; j++)        
                r = r + board[i][j];
             r = r + "|\n";
          return r;
    //**my TicTacToeTester
    import java.util.Scanner;
       This program tests the TicTacToe class by prompting the
       user to set positions on the board and printing out the
       result.
    public class TicTacToeTester
       public static void main(String[] args)
          Scanner in = new Scanner(System.in);
          String player = "x";
          TicTacToe game = new TicTacToe();
          boolean done = false;
          while (!done)
             System.out.print(game.toString());
             System.out.print(
                   "Row for " + player + " (-1 to exit): ");
             int row = in.nextInt();
             if (row < 0) done = true;
             else
                System.out.print("Column for " + player + ": ");
                int column = in.nextInt();
                game.set(row, column, player);
                if (player.equals("x"))
                   player = "o";
                else
                   player = "x";   
    }I had a post earlier but couldn't find it, but how do I use the user input to change the variable SIZE in TicTacToe() and toString(), this is for a class project, don't really know the language yet, I know the code that does this has to be in my main method which is in my TicTacToeTester class, I know this is probably pretty easy if you can help me with the code it would be appreicated, somebody explained it to me in words but I don't really know the language yet so a few lines of code would help me more then explaining it thanks.

    Hi,
    try it that way:
    //**my TicTacToeTester
    import java.util.Scanner;
       This program tests the TicTacToe class by prompting the
       user to set positions on the board and printing out the
       result.
    public class TicTacToeTester
       public static void main(String[] args)
          Scanner in = new Scanner(System.in);
          System.out.print("Number of cols, rows: ");
          TicTacToe game = new TicTacToe(in.nextInt());
          String player = "x";
          boolean done = false;
          while (!done)
             System.out.print(game.toString());
             System.out.print(
                   "Row for " + player + " (-1 to exit): ");
             int row = in.nextInt();
             if (row < 0) done = true;
             else
                System.out.print("Column for " + player + ": ");
                int column = in.nextInt();
                game.set(row, column, player);
                if (player.equals("x"))
                   player = "o";
                else
                   player = "x";   
       A tic-tac-toe board.
    public class TicTacToe
       private String[][] board;
       private int size;
          Constructs an empty board.
       public TicTacToe(int newSize)
          this.size = newSize;
          board = new String[size][size];
          // Fill with spaces
          for (int i = 0; i < size; i++)
             for (int j = 0; j < size; j++)
                board[i][j] = " ";
          Sets a field in the board. The field must be unoccupied.
          @param i the row index
          @param j the column index
          @param player the player ("x" or "o")
       public void set(int i, int j, String player)
          if (board[i][j].equals(" "))
             board[i][j] = player;
          Creates a string representation of the board, such as
          |x  o|
          |  x |
          |   o|
          @return the string representation
       public String toString()
          String r = "";
          for (int i = 0; i < size; i++)
             r = r + "|";
             for (int j = 0; j < size; j++)        
                r = r + board[i][j];
             r = r + "|\n";
          return r;
    }L.P.

  • Getting name of the variable?

    Hi, Is there any way to get the name of the defined variable ?
    for example
    var description:String = "Some description";
    var variableName = getVariableName(description);
    trace(variableName); // output = "description"
    Thanks

    you can retrieve the xmllist of variables (string or otherwise), from any object (eg, the current timeline) using the following function.  each list item has a type property and name property:
    function variableF(o:Object):XMLList{
    return describeType(o).variable;

  • Is it possible to get a variable if I only know the variable by it'

    Is it possible to get a variable if I only know the variable by it's string name?
    In my case I would like to call Resources.GetStringToDisplay("TEXT_0") and get the string "bla bla 0"
    public class Resources {
    public string GetStringToDisplay(String s)
    {          //how can I to return the value of one variable
    return ............;
    public static String TEXT_0="bla bla 0";
    public static String TEXT_1="bla bla 1";
    public static String TEXT_2="bla bla 2";
    public static String TEXT_3="bla bla 3";
    Thanks

    NO you can not get Variable value by camparing string value in J2ME (because J2ME is not supporting reflection package). But you can do one thing to get same functionality.
    public static String TEXT_0="TEXT_0@bla bla 0";
    public static String TEXT_1="TEXT_1@bla bla 1";
    public static String TEXT_2="TEXT_2@bla bla 2";
    public static String TEXT_3="TEXT_3@bla bla 3";
    public string GetStringToDisplay(String s)
    if(TEXT_0.startsWith(s) )
    return TEXT_0.substring (TEXT_0.indexOf('@')+1, TEXT_0.length());
    else if(TEXT_1.startsWith(s) )
    return TEXT_1.substring (TEXT_1.indexOf('@')+1, TEXT_1.length());

  • Return to the cell after data validation in JTable

    Hi,
    I am implementing an editable JTable. I want the focus or selection return to the current editing cell when the user inputing a wrong format data. I can catch the validation error and pop up a error message to user. But I can not return the focus or selection to the editing cell.
    If anyone has already solved this problem, please give me your solution.
    Thank you!
    I have tried:
    1.
    In tableChanged(TableModelEvent e) method:
    int row = e.getFirstRow();
    int column = e.getColumn();
    Object data = newJTable.getValueAt(row, column);
    if(!validation(data)) // return true if validation OK
    editFailed = true;//class variable
    previousRow = row;//class variable
    previousCol = column;//class variable
    Add a focus listener to the table and implement the focus listener's focusLost method with:
    if(validationFailed)
    table.editCellAt(previousRow, previousCol);
    This does move the focus to the editing cells if you want to continue to edit the table.
    Problems are
    If you move the focus out of the table, the wrong date will be in the table or not edited.
    The selection color was shown on the next cell where you pointed your mouse to after you leave the editing cells.
    2. I have also tried to use:
    in the above focusLost method
    table.clearSelection();
    table.editCellAt(previousRow, previousCol);
    table.setRowSelectionInterval(previousRow, previousRow);
    table.setColumnSelectionInterval(previousCol, previousRow);
    But it did not change the selection.
    Shaolong

    This is the fix for the above problem.
    Basically we need to handle both mouse/keyboard actions on our own.
    This code returns the control to errorCell..
    /* TableCellValidator class */
    /* The class basically validates the input entry in a cell and */
    /* pops up a JOptionPane if its an invalid input */
    /* And an OK is clicked on the JOptionPane, the control returns back */
    /* to the same cell */
    /* Basic Idea: The controls Arrow/Tab/mouse clicks are handled by our */
    /* ----------- custom table. Its has been slightly tricky to handle */
    /* mouse clicks, since when you click the next cell, the */
    /* editingrow/editingcol advances. Hence the */
    /* previousrow/previouscol has been captured in the */
    /* setValueAt method. */
    /* To capture Table/Arrow/Numeric Arrow, The keyStrokes(TAB etc)*/
    /* assigned different AbstractionActions to execute like */
    /* validateBeforeTabbingToNextCell */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableCellValidator {
    * Constructor.
    * Basically instantiates the class and sets up the
    * JFrame object and the table.
    public TableCellValidator() {
    JFrame f = new JFrame("JTable test");
    f.getContentPane().add(new JScrollPane(createTable()), "Center");
    f.pack();
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    * A method which created our custom table.
    * The JTable methods processMouseEvent
    * and setValueAt are overridden to handle
    * Mouseclicks.
    * The Tables ActionMap is fed with different
    * AbstractAction classes eg: (validateBeforeTabbingToNextCell)
    * (Scroll down below for the innerclass
    * validateBeforeTabbingToNextCell).
    * So basically when TAB is pressed the stuff present
    * in the validateBeforeTabbingToNextCell's actionPerformed(..)
    * method is performed.
    * So we need to handle all the stuff a TAB does.
    * ie. if a TAB hits the end of the row, we need to increment
    * it to the next Row (if the validation is successful)
    * in the current row etc..
    * @return JTable
    * @see validateBeforeTabbingToNextCell
    * @see validateBeforeShiftTabbingToNextCell
    * @see validateBeforeMovingToNextCell
    * @see validateBeforeMovingDownToCell
    * @see validateBeforeMovingUpToCell
    * @see validateBeforeMovingLeftToCell
    private JTable createTable() {
    JTable table = new JTable(createModel()){
    private int previousRow =0;
    private int previousCol =0;
    * Processes mouse events occurring on this component by
    * dispatching them to any registered
    * <code>MouseListener</code> objects.
    * <p>
    * This method is not called unless mouse events are
    * enabled for this component. Mouse events are enabled
    * when one of the following occurs:
    * <p><ul>
    * <li>A <code>MouseListener</code> object is registered
    * via <code>addMouseListener</code>.
    * </ul>
    * <p>Note that if the event parameter is <code>null</code>
    * the behavior is unspecified and may result in an
    * exception.
    * @param e the mouse event
    * @see java.awt.event.MouseEvent
    * @see java.awt.event.MouseListener
    * @see #addMouseListener
    * @see #enableEvents
    * @since JDK1.1
    protected void processMouseEvent(MouseEvent e) {
    boolean canMoveFocus = true;
    int currentRowAndColumn[] = getCurrentRowAndColumn(this); //we pull the current row and column
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    if ( e.getID() == MouseEvent.MOUSE_PRESSED || e.getID() == MouseEvent.MOUSE_CLICKED) {
    stopCurrentCellBeingEdited(this); //stop the cellbeing edited to grab its value
    final String value = (String)getModel().getValueAt(row,column);
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    JOptionPane.showMessageDialog(null,"Alpha value ="+ value ,"Invalid entry!",JOptionPane.WARNING_MESSAGE);
    changeSelection(previousRow,previousCol, true, true);
    editCellAt(previousRow, previousCol);
    requestFocus(); // or t.getEditorCompo
    if ( canMoveFocus ) {
    super.processMouseEvent(e);
    * The method setValueAt of the JTable is overridden
    * to save the previousRow/previousCol to enable us to
    * get back to the error cell when a Mouse is clicked.
    * This is circumvent the problem, when a mouse is clicked in
    * a different cell, the control goes to that cell and
    * when you ask for getEditingRow , it returns the row that
    * the current mouse click occurred. But we need a way
    * to stop at the previous cell(ie. the cell that we were editing
    * before the mouse click occurred) when an invalid data has
    * been entered and return the focus to that cell
    * @param aValue
    * @param row
    * @param col
    public void setValueAt(Object aValue,int row, int col) {     
    this.previousRow = row;
    this.previousCol = col;
    super.setValueAt(aValue,row,col);
    /* These are the various KeyStrokes like
    ENTER,SHIFT-TAB,TAB,Arrow Keys,Numeric Arrow keys being assigned an Abstract action (key string ) in to the
    inputMap first . Then an Action is assigned in the ActionMap object
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0) ,"validateBeforeTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,1) ,"validateBeforeShiftTabbingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_RIGHT,0) ,"validateBeforeMovingToNextCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0) ,"validateBeforeMovingDownToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP,0) ,"validateBeforeMovingUpToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT,0) ,"validateBeforeMovingLeftToCell");
    table.getActionMap().put("validateBeforeTabbingToNextCell",
    new validateBeforeTabbingToNextCell());
    table.getActionMap().put("validateBeforeShiftTabbingToNextCell",
    new validateBeforeShiftTabbingToNextCell());
    table.getActionMap().put("validateBeforeMovingToNextCell",
    new validateBeforeMovingToNextCell());
    table.getActionMap().put("validateBeforeMovingDownToCell",
    new validateBeforeMovingDownToCell());
    table.getActionMap().put("validateBeforeMovingUpToCell",
    new validateBeforeMovingUpToCell());
    table.getActionMap().put("validateBeforeMovingLeftToCell",
    new validateBeforeMovingLeftToCell());
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    return table;
    * A table model is created here for 5 rows/5 columns.
    * And the isCellEditable is overridden to return true,
    * indicating that the cell can be edited.
    * So fine tuned control can be done here by saying,
    * the user can be allowed to edit Row 1,3 or 5 only.
    * or column 1 only etc..
    * @return DefaultTableModel
    private DefaultTableModel createModel() {
    DefaultTableModel model = new DefaultTableModel(5, 5) {
    public boolean isCellEditable(int row, int column) {
    return true;
    return model;
    * This method basically returns the currentRow/currentCol value
    * If the current Row/Col is being edited then
    * it returns the getEditingRow/getEditingColumn
    * If its not being edited,
    * it return the getAnchorSelectionIndex of the JTables
    * ListSelectionModel.
    * If the column or row is -1, then it return 0.
    * The first element in the int[] array is the row
    * The second element in the int[] array is the column
    * @param t input a JTable
    * @return int[]
    * @see ListSelectionModel
    * @see JTable
    private int[] getCurrentRowAndColumn(JTable t){
    int[] currentRowAndColum = new int[2];
    int row, column;
    if (t.isEditing()) {
    row = t.getEditingRow();
    column = t.getEditingColumn();
    } else {
    row = t.getSelectionModel().getAnchorSelectionIndex();
    if (row == -1) {
    if (t.getRowCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column =t.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
    if (column == -1) {
    if (t.getColumnCount() == 0) {
    //actually this should never happen.. we need to return an exception
    return null;
    column = 0;
    currentRowAndColum[0]=row;
    currentRowAndColum[1]=column;
    return currentRowAndColum;
    * Tbis basically a wrapper method for CellEditors,
    * stopCellEditing method.
    * We need to do this because,
    * for instance we have entered a value in Cell[0,0] as 3
    * and when we press TAB or mouse click or any other relevant
    * navigation keys,
    * ** IF the cell is BEING EDITED,
    * when we do a getValueAt(cellrow,cellcol) at the TableModel
    * level , it would return "null". To overcome this problem,
    * we tell the cellEditor to stop what its doing. and then
    * when you do a getValueAt[cellrow,cellcol] it would
    * return us the current cells value
    * @param t Input a JTable
    * @see CellEditor
    private void stopCurrentCellBeingEdited(JTable t){
    CellEditor ce = t.getCellEditor(); /*this not the ideal way to do..
    since there is no way the CellEditor could be null.
    But a nullpointer arises when trying to work with mouse.. rather than just
    keyboard" */
    if (ce!=null) {
    ce.stopCellEditing();
    * The following Action class handles when a
    * RIGHT ARROW or NUMERIC RIGHT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * next Cell.. else take it back to the currentCell
    class validateBeforeMovingToNextCell extends AbstractAction {
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There is just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to
    * down by one Cell.. else take it back to the currentCell
    * @param e
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    if (column >= t.getColumnCount())
    column = column-1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * DOWN ARROW or NUMERIC DOWN ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move it to the
    * down by Cell.. else take it back to the currentCell
    class validateBeforeMovingDownToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row++;
    if (row >= t.getRowCount())
    row = row - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * UP ARROW or NUMERIC UP ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingUpToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    row--;
    if (row <0)
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a
    * LEFT ARROW or NUMERIC LEFT ARROW is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeMovingLeftToCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    if (column <0)
    column = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column++;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while (row < rows) {
    while (column < columns) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column++;
    row++;
    column = 0;
    row = 0;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    * The following Action class handles when a SHIFT TAB is pressed.
    * There just a basic checking for Numeric values
    * (Integer.parseInt) inside the code.
    * When validation is successfull, we need to move the cursor/
    * editable status up by a Cell.. else take it back to the currentCell
    class validateBeforeShiftTabbingToNextCell extends AbstractAction {
    public void actionPerformed(ActionEvent e) {
    JTable t = (JTable) e.getSource();
    int currentRowAndColumn[] = getCurrentRowAndColumn(t);
    int row = currentRowAndColumn[0];
    int column = currentRowAndColumn[1];
    stopCurrentCellBeingEdited(t);
    String value = (String)t.getModel().getValueAt(row,column);
    if (value!= null && !value.equals("")) {
    try {
    Integer.parseInt(value);
    } catch (NumberFormatException nfe) {
    JOptionPane.showMessageDialog(null,"Please input numeric values at cell[row="+row+","+"col="+column+"]","Invalid Input!!",JOptionPane.WARNING_MESSAGE);
    t.changeSelection(row, column, true, true);
    t.editCellAt(row,column);
    t.getEditorComponent().requestFocus();
    return;
    column--;
    int rows = t.getRowCount(), columns = t.getColumnCount();
    while ((row < rows) && (row >= 0)) {
    while ((column < columns) && (column >= 0)) {
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    column--;
    row--;
    column = columns - 1;
    row = rows - 1;
    if (t.isCellEditable(row, column)) {
    t.changeSelection(row, column, true, true);
    t.editCellAt(row, column);
    if ((t.getEditingRow() == row)
    && (t.getEditingColumn() == column)) {
    t.requestFocus();
    return;
    public static void main(String[] args) {
    new TableCellValidator();

Maybe you are looking for