Newbie: Return variable from class?

I'm calling a class to verify some data. The verification is quite complicated so the class will use a JFrame to make things clearer and will popup some additional dialogs. What I can't work out is the syntax for returning a variable from the class.
I'm using the constructor to build and show the JFrame with the data to be verified and then triggering off a JButton to start the verification. If all is OK then the class would return a result.
What I would like is to call either the Constructor or a Method in the class to show the JFrame, and to get that to return a value to me when a JButton is clicked. Does anyone have any code samples of something like this, or could point me in the right direction? It feels messed up right now.

The simplest way is to use JDialog with setModal(true). Write your subclass of it and include a result field, typically a boolean that determines whether you exited via "OK" or "Cancel". The handlers for the buttons set this field appropriately, then you do "show" on the dialog (which waits until one of the button handlers calls "dispose" on the dialog), then test the flag.
public class MyDialog extends JDialog {
       boolean resultOk;
       JButton okButton, cancelButton;
     public  MyDialog(Frame parent) {
         super(parent, "Validate dialog", true);
       okButton = new JButton("OK");
       okButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent evt) {
               if(formIsValid()) {
                     resultOk = true;
                     dispose();
      cancelButton = new JButton("Cancel");
      cancelButton.addActionListner(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
              resultOK = false;
             dispose();
     private boolean formIsValid() {
        .... validation
    MyDialog dlg = new MyDialog(parentFrame);
    dlg.show();
     if(dlg.resultOK)  { // ok button selected
       ...

Similar Messages

  • DB adapter not returning return variable from database function

    Hi,
    We are calling a function using db adapter from our BPEL Process. It worked fine in 10.1.3.3.
    after we migrated to 10.1.3.4 MLR# 8 , we are not able to see the return variable which function is returing.
    Function is working fine when executed standalone. Its returing the variable. But we are not able to see that variable in bpel process invoke response variable. This is causing issue.
    Any idea what causing the issue.
    Thanks

    Check your XSD to see if it is qualified (elementFormDefault="qualified") or unqualified. The XSDs were unqualified in 10.1.3.3. They became qualified in 10.1.3.4. If you have an unqualified XSD and you're using a 10.1.3.4 runtime you will likely have namespace issues that cause problems with the generated XML. The solution is to regenerate your XSD so that it becomes qualified.

  • 1.6.0_10 and 11, Memory leak returning variables from Java to JavaScript

    Environment: Windows XP SP2, IE7, JScript 5.7, JRE 1.6.0_11-b03 and 1.6.0_10
    Memory allocated in Java and returned as a JavaScript variable value is not garbage collected in Java when the JavaScript variable is re-used.
    In the following simplified example, a populated HashMap is returned from the applet test1 method to the JavaScript variable hash1.
    The JavaScript variable hash1 is re-used on the next iteration so I would expect it should be marked for garbage collection.
    In 1.6.0_7 and previous releases, the memory associated with this Java HashMap is freed implicitly.
    In 1.6.0_10 and 1.6.0_11 the HashMap memory is never freed.
    Is this is what we should expect, a feature of the significant LiveConnect changes that were part of 1.6.0_10?
    Do we need to rewrite our code to call new Java methods from JavaScript explicitly freeing the memory, in this example calling the freeMem method?
    Has anybody else experienced this problem since 1.6.0_10?
    Thanks
    Rob
    Example code ...
    TestRLApplet.java
    import java.applet.Applet;
    import java.util.HashMap;
    public class TestRLApplet extends Applet
    private HashMap hash1;
    public TestRLApplet()
    public void init()
    public HashMap test1()
    hash1 = new HashMap();
    for (int i = 0; i <10; i++) {
    hash1.put(Integer.toString(i),Integer.toString(i));
    return (hash1);
    public void freeMem() {
    hash1.clear();
    hash1 = null;
    TestClient.htm
    <HEAD>
    <TITLE></TITLE>
    <SCRIPT LANGUAGE="javascript">
    function window_onload()
    var hash1;
    testAppplet = document.TestRLApplet;
    for (cnt=0; cnt < 1000; cnt++)
    hash1= testAppplet.test1();
    </SCRIPT>
    </HEAD>
    <object
    classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    WIDTH = 1 HEIGHT = 1 NAME = "TestRLApplet" >
    <PARAM NAME = CODE VALUE = "TestRLApplet.class" >
    <PARAM NAME = ARCHIVE VALUE = "../applets/TestRLApplet.jar" >
    <PARAM NAME = NAME VALUE = "TestRLApplet" >
    <PARAM NAME = MAYSCRIPT VALUE = true >
    <param name = "type" value = "application/x-java-applet;version=1.6">
    <param name = "scriptable" value = "false">
    </object>
    <BODY LANGUAGE=javascript onload="return window_onload()" leftMargin=40 id=body >
    </BODY>
    </HTML>
    Java Console
    Java Plug-in 1.6.0_10
    Using JRE version 1.6.0_10 Java HotSpot(TM) Client VM
    c: clear console window
    f: finalize objects on finalization queue
    g: garbage collect
    h: display this help message
    l: dump classloader list
    m: print memory usage
    o: trigger logging
    q: hide console
    r: reload policy configuration
    s: dump system and deployment properties
    t: dump thread list
    v: dump thread stack
    x: clear classloader cache
    0-5: set trace level to <n>
    Memory: 5,056K Free: 2,551K (50%) ... completed.
    Memory: 7,996K Free: 3,499K (43%) ... completed.
    Memory: 7,996K Free: 1,038K (12%) ... completed.
    Memory: 13,180K Free: 3,745K (28%) ... completed.
    Memory: 22,844K Free: 5,614K (24%) ... completed.
    Memory: 37,984K Free: 15,009K (39%) ... completed.
    Memory: 37,984K Free: 13,069K (34%) ... completed.
    Memory: 37,984K Free: 6,125K (16%) ... completed.
    Memory: 65,088K Free: 25,107K (38%) ... completed.
    Memory: 65,088K Free: 21,201K (32%) ... completed.
    Memory: 65,088K Free: 13,381K (20%) ... completed.
    Memory: 65,088K Free: 7,967K (12%) ... completed.
    Memory: 65,088K Free: 5,013K (7%) ... completed.
    Memory: 65,088K Free: 414K (0%) ... completed.

    What are you missing?
    I inherited this app and signing the third party jars is how it was setup, I was wondering the same thing too, why was it necessary to sign the third party jars?
    The applet runs in either JRE 1.6.0_13 or JRE 1.6.0_27 depending on the other Java apps the user uses. JRE 1.6.0_13 does not have the mixed code security (so it is like is disable), but JRE 1.6.0_27 does have the mixed code security and the applet will not launch with mixed code security enable, so we have to disable it. With all the hacking going on in the last two years, is important to improve security; so this is a must.
    Yes, I always clear up the cache.
    Any idea on how to resolve this problem?

  • Cant return text from class

    Hi guys,
    I'm hopeing someone out there can help me out with a problem that has been bothering me for the last few days. Basically I can not get my class to return any text at all by calling the appropriate function, yet if I do a system.out.println() from within the class its self the text will be outputed to the console without a problem.
    Below is the threaded class I want to retrieve the text from:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class SockThread implements Runnable{
         private String chatter;
         public String chatText;
         private String charText;
         private Thread runner;
         private Socket socktest;
         private PrintStream out;
         private BufferedReader in;
         public SockThread() {
              if (runner == null) {
                   runner = new Thread(this);
                   runner.start();
         public void run() {
              try {
                   this.connect();
              } catch (IOException ioe) {
         public void connect() throws java.io.IOException{
              String hostname = "efnet.xs4all.nl";
              int portnumber = 6669;
              this.socktest = new Socket(hostname, portnumber);
              this.out = new PrintStream(this.socktest.getOutputStream());
             this.in = new BufferedReader(new InputStreamReader(this.socktest.getInputStream()));
              this.out.print("user "+ "strangename" + " stranger irc : " + "Stranger");
              this.out.print("\n");
              this.out.print("nick " + "Shadwick");
              this.out.print("\n");
              Boolean eof = false;
                   try {
                        while (!eof) {
                             this.charText = in.readLine();
                                  if (this.charText == null){
                                       eof = true;
                                       socktest.close();
                                  } else {
                                       this.chatText = charText;
              } catch (IOException ioe) {
                   System.out.println("Its not working :( " + ioe);
         public void showStatus() {
              System.out.println(this.chatText);
    }And here is my main class:
    public class ChatConsole {
         public static void main(String[] arguments) {
              SockThread st = new SockThread();
              st.showStatus();
    }No matter if i try accessing the text via the showStatus() function or directly access the chatText variable i get nothing. I'm pretty sure i'm missing something thats stopping me from getting the text but I just cant see it. If anyone can help I'd greatly appreciate it.

    As you are creating another thread with the SockThread class, it runs independently from the main thread. So the SockThread Thread has probably not gotten to the part where it initiates the chatText var by the time the main thread calls the showStatus() method.
    To varify this, either do:
    put System.out.println("TEST"); in the show status method. If this prints then the var just hasnt been initiated yet.
    OR
    Use Thread.Sleep(2000); in the main method to make is sleep for a while to give the SocketThread Thread a chance to initiate the var.

  • Problem returning variables from dynamic SQL/PLSQL

    Hi, I have a problem I am trying to solve using a very short piece of dynamic SQL or PLSQL but I am having problems getting the variable values out of the dynamic block.
    I have 16 counters whose names are made up of three variable parts - 'scheme', 'contributory category' and 'employment category'
    The 'scheme' can be either 'no1', 'no2', 'off', 'cg' or 'amc'
    The 'contributory category' can be either 'cont' or 'noncont'
    The 'employment category' can be either 'ft' or 'pt'
    (There are only 16 because only 16 combinations are possible)
    For example the total counter name could be 'v_cg_noncont_ft_count'
    I have created a variable by concatenating the various elements called v_incr_count_name which holds the name of the counter I want to increment.
    I am running this whole thing within an anonymous PLSQL block so I cannot use global variables meaning that my variables are not visible within a dynamic PLSQL block.
    I believe this means that either I need to bind the variables within a PLSQL block or use a SELECT FROM INTO SQL block.
    I have tried a few solutions with no luck such as the following PLSQL:
    v_incr_count := 'v_'||v_scheme||'_'||v_cont_cat||'_'||v_emp_cat||'_count';
    sql_stmt := 'BEGIN :a := :a + 1; END;';
    EXECUTE IMMEDIATE sql_stmt USING v_incr_count_name;
    Unfortunately I am getting the 'IN bind variable bound to an OUT position' error which I believe is because it is trying to return a value into v_incr_count_name which has been defined by default as an IN variable. The problem is that I need to store the returned value into the variable whose name is stored in v_incr_count_name.
    Another solution I tried is:
    v_incr_count_name := 'v_'||v_scheme||'_'||v_cont_cat||'_'||v_emp_cat||'_count';
    sql_stmt := 'SELECT '||v_incr_count_name||' + 1 FROM DUAL';
    EXECUTE IMMEDIATE sql_stmt INTO v_return;
    This solution gives me an 'Invalid colum error'
    Any help would be greatly appreciated
    Cheers, Dan

    Repost:
    Problem with variables in dynamic SQL/PLSQL

  • Return variable from Function

    I have a function that if I write-host the variable $RDPUser from within the function it returns true, however I can't seem to get the variable to be seen outside the function, even if I make it global
    Function global:RDP (){
    $WorkstationName = Get-Content env:ComputerName
        # Run the qwinsta.exe and parse the output
        $queryResults = (qwinsta /server:$WorkstationName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)  
        # Pull the session information from each instance
        ForEach ($queryResult in $queryResults) {
            $RDPUser = $queryResult.USERNAME
            $sessionType = $queryResult.SESSIONNAME
            # We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number
            If (($RDPUser -match "[a-z]") -and ($RDPUser -ne $NULL)) {  
                # When running interactively, uncomment the Write-Host line below to show the output to screen
                 $LoggedOnUser = $RDPUser
             $RDPHost
                #$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType
    #Get Current Time
    $time2 = Get-Date
    #Get Logged-On User Details
    $user = Get-WmiObject Win32_Computersystem -ComputerName "."
    #Get Time User Logged On
    $time1 = Get-EventLog -LogName System -InstanceId 7001 -Newest 1
    #Set Variables for SQL
    $LogonDateTime = get-date -Format "MMM dd yyyy HH:mm:ss"
    $WorkstationName = Get-Content env:ComputerName
    $LoggedOnUser = $user.UserName
    $TimeToLogon = $time2.TimeOfDay.TotalSeconds - $time1.TimeGenerated.TimeOfDay.TotalSeconds
    $logonType = "Logon"
    #If workstation = QATest Set $result
    if ($workstationName -eq "QAtest") {$result = RDP ; $LoggedOnUser = $result}
    write-host $LogonDateTime
    write-host $WorkstationName
    write-host $LoggedOnUser
    write-host $TimeToLogon
    write-host $logonType
    Alter De Ruine

    For some reason I needed my If statement inside the function:
    Function RDP (){
    $WorkstationName = Get-Content env:ComputerName
        # Run the qwinsta.exe and parse the output
        $queryResults = (qwinsta /server:$WorkstationName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)  
        # Pull the session information from each instance
        ForEach ($queryResult in $queryResults) {
           $script:RDPUser = $queryResult.USERNAME
            $sessionType = $queryResult.SESSIONNAME
            # We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number
            If (($RDPUser -match "[a-z]") -and ($RDPUser -ne $NULL)) {  
                # When running interactively, uncomment the Write-Host line below to show the output to screen
             $RDPUser
                #$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType
    if ($workstationName -eq "QAV-RDHOST") {$script:LoggedOnUser = $RDPUser}
    #Get Current Time
    $time2 = Get-Date
    #Get Logged-On User Details
    $user = Get-WmiObject Win32_Computersystem -ComputerName "."
    #Get Time User Logged On
    $time1 = Get-EventLog -LogName System -InstanceId 7001 -Newest 1
    #Set Variables for SQL
    $LogonDateTime = get-date -Format "MMM dd yyyy HH:mm:ss"
    $WorkstationName = Get-Content env:ComputerName
    $LoggedOnUser = $user.UserName
    $TimeToLogon = $time2.TimeOfDay.TotalSeconds - $time1.TimeGenerated.TimeOfDay.TotalSeconds
    $logonType = "Logon"
    #Call function RDP
    RDP
    Alter De Ruine

  • How to pass a variable from one class to another class?

    Hi,
    Is it possible to pass a variable from one class to another? For e.g., I need the value of int a for calculation purpose in method doB() but I get an error <identifier> expected. What does the error mean? I know, it's a very, very simple question but once I learn this, I promise to remember it forever. Thank you.
    class A {
      int a;
      int doA() {
          a = a + 1;
          return a;
    class B {
      int b;
      A r = new A();
      r.a;  // error: <identifier> expected. What does that mean ?
      int doB() {
         int c = b/a;  // error: operator / cannot be applied to a
    }Thank you!

    elaine_g wrote:
    I am wondering why does (r.a) give an error outside the method? What's the reason it only works when used inside the (b/r.a) maths function? This is illegal syntax:
    class B {
      int b;
      A r = new A();
      r.a;  //syntax error
    }Why? Class definition restricts what you can define within a class to a few things:
    class X {
        Y y = new Y(); //defining a field -- okay
        public X() { //defining a constructor -- okay
        void f() { //defining a method -- okay
    }... and a few other things, but you can't just write "r.a" there. It also makes no sense -- that expression by itself just accesses a field and does nothing with it -- why bother?
    This is also illegal syntax:
    int doB() {
          A r = new A();
          r.a;  // error: not a statement
    }Again, all "r.a" does on its own is access a field and do nothing with it -- a "noop". Since it has no effect, writing this indicates confusion on the part of the coder, so it classified as a syntax error. There is no reason to write that.

  • Using a variable from another class

    hello friends, I have a class with the follow variable: dbcolTempMax, and the value of this variable I need in another class, how can do to use the value of the variable...thanks

    Both people above described the solution, but from the question I take it you are somewhat new to programming. Let me give you a code example which may help.
         public class ClassWithVariable {
              private int dbcolTempMax;
              public int getDbcolTempMax() {
                   return dbcolTempMax;
         public class SomeOtherClass {
              ClassWithVariable cwv = new ClassWithVariable();
              cwv.getDbcolTempMax(); // This gets the value of the variable
         }Now if the variable is static, you can provide a static "accessor" method to ge the variable. This will save you the trouble of constructing an object of the class.
    Cheers,
    Cypher

  • Accessing variable from another class

    Say I want to access String ABC from class XYZ from my main class. I have already created the object for the class I just don't know the syntax for accessing the variable.
    This is just an example. I figured this is just a problem of finding the right syntax so I didn't bother creating a compiling code.
    public class test{
    public static void main(String[]args){
         XYZ xyz = new XYZ ();
         String a = abc.XYZ(); // this is where i want to directly access the variable abc. i know this isn't correct and it's what im trying to find out how to do.
    public class XYZ{
         String abc = "hi";
    }Edited by: aznprdgy on Nov 3, 2009 2:13 PM

    No, that isn't possible.
    abc is said to be a local variable. And it's only useable within method().
    It's part of the job of the class Xyz to control the access to its state. As an example:
    public class Test {
        public static void main(String[] args) {
            Xyz xyz = new Xyz()
            String a = xyz.getSpecialValue();
    public class Xyz {
        private String a;
        public String getSpecialValue() {
            return a;
        public void method() {
            a = "hi";
    }Note that a won't be reference to the string "hi" until after method() has been called.

  • Passing Variables from One Class to Another

    Hello, I am new to Java Programming and I'm currently starting off by trying to build a simple application.
    I need help to pass variables created in one class to another.
    In my source package, I created 2 java classes.
    1. Main.java
    2. InputFileDeclared.java
    InputFileDeclared reads numerical data from an external text file and store them as string variables within the main method while Main converts a text string into a number.
    Hence, I would like to pass these strings variables from the InputFileDeclared class to the Main class so that they can be converted into numbers.
    I hope somebody out there may enlighten me on this.
    Thank you very much in advance!

    Values are passed from method to method, rather than from class to class. In a case such as you describe the code of a method in Main will probably call a method in InputFileDeclared which will return the String you want. The method in Main stores that in a local variable and processes it. It really doesn't matter here which class the method is in.
    You InputFileDeclared object probably contains "state" information in its fields such as the details of the file it's reading and how far it's got, but generally the calling method in Main won't need to know about this state, just the last data read.
    So the sequence in the method in Main will be:
    1) Create an new instance of InputFileDeclared, probably passing it the file path etc..
    2) Repeatedly call a method on that instance to return data values, until the method signals that it's reached the end of file, e.g. by returning a null String.
    3) Probably call a "close()" method on the instance, which you should have written to close the file.

  • Moving Variable from one class to another.

    I need to get a Variable from one class to another how would I do this?

    Well this is a very tipical scehario for every enterprise application. You always create logger classes that generate log files for your application, as that is the only way to track errors in your system when its in the production enviorment.
    Just create a simple class that acts as the Logger, and have a method in it that accepts a variable of the type that you are are trying to pass; most commonly a String; but can be overloaded to accept constom classes. e.g.
    class Logger
      public void log(String message)
        writeToFile("< " + new Date() + " > " + message);
      public void log(CustomClass queueEvent)
        log("queue message was: " + queueEvent.getMessage() + " at: " + queueEven.getEventTime());
    }Hope this makes things clearer
    Regards
    Omer

  • How do  I use a variable from an Interface class?

    Right now I have three classes. First class is called Game and it extends my second class call Parent and also implements my third class call Source. Source is an interface class. I have a variable that I want to use in my Source class named Checker. Now, How do I go among using that variable from my Game class? What should the code look like?
    ex.
    public class Game extends Parent implements Source
    need help badly....

    ok, what I forgot to tell you guys is that my variable
    in my interface class is a boolean type(true or
    false). It is set to true now. But I want it to change
    to false when a user triggers a button in the Game
    class. How do I do this? You don't because you can't. If you have a varaible declared in an interface it must be static and final. It cannot, therefore, be changed. Better head back to the drawing board.

  • Instead of using session How to pass the variable from action class to JSP

    Im using Struts1.2 version.Created the Sample application to get the username.Upto action class im getting the username then i have to display the username in the JSP.Is there any options rather than using session variable to display the username.

    did you check the answer in your previous thread
    Passing Variable from Javascript to Controller

  • Accessing public variables from other classes

    Probably a simple questions, but how can I access a variable from another class. My exact situation is as follows.
    A class called WorldCalender has a variable which is defined: public int hour; (the value is given to it elsewhere).
    I want to access this variable and increase it by one in a subroutine in the class Hour. In this class I have put: WorldCalender.hour++; but it doesn't seem to work. How should I do it?

    don't expose the hour variable at all.
    have a method eg addToHourBy( int hrs )
    Probably a simple questions, but how can I access a
    variable from another class. My exact situation is as
    follows.
    A class called WorldCalender has a variable which is
    defined: public int hour; (the value is given to it
    elsewhere).
    I want to access this variable and increase it by one
    in a subroutine in the class Hour. In this class I
    have put: WorldCalender.hour++; but it doesn't seem to
    work. How should I do it?

  • Use of variables from other class

    hallo,
    i have two classes A and B
    i would like to access a variable of the class B out of A class
    without class A extends B or
    A classA = new A();
    to use
    i attempted it with a constructor
    class A{
        B klb;
        public A(B b1){
        this.klb = b1;
       int a;
       a= klb.varausB;
    }with that I get, however, a NullPointerException
    in a similar form i saw it already once and it functioned
    somebody can help me?

    that is it what I mean
    public class ClassA {
    ClassB clb;
    public ClassA (ClassB cb){
    this.clb = cb;
    public static void main(String[] args) {
    System.out.println("Var from class B:
    class B: "+clb.varb1);// there is an error, i know
    but how it is right?
    public class ClassB {
    public String varb1 ="var b1";
    }nevertheless so similarly it should function, or?So if you create an instance of ClassA, clb will be initialized. But you don't do that in main. Hence your errors:
    1) You're not calling the constructor, so clb is null
    2) You're trying to access an instance variable without having an instance, so clb is not only null, it actually doesn't exist.
    public static void main(String[] args) {
      Class A myA = new ClassA();
      System.out.println("Var from class B: "+ myA.clb.varb1);
    }You're outside of any object, ehnce you need to address clb through an instance of ClassA.

Maybe you are looking for

  • How can I make a file a more manageable size?

    I'm looking to downsize a very hefty file.  It currently has a lot of information and is clumsy to deal with when attaching to email, opening it up, printing, etc.  Is there a straightforward way to save a version of this document with ONLY the infor

  • How to get report parameter in XML file

    hi all, i have created report with 5 parameters.i want report parameter to be linked with template. parametres should be displayed on output. how to do it. anyone help pls. thanks rajesh

  • What is Fire Vault exactly?

    I'm unsure. I was clicking around and hit the "Turn Fire Vault on" button then clicked out. Now, on my log in screen there's a "reset password" button which I want to get rid of. This happened after I did this whole accidental fire vault thing. any s

  • PASS DATA TO A REPORT BEING SCHEDULED AS A BACKGROUND JOB

    Moderator message: please do not use ALL CAPITALS in your subject Hi All, I need to pass some data to a Zreport_submit which I would be calling using SUBMIT statement from another Zreport_main. The report being called through the SUBMIT statement i.e

  • Installing DW problems

    I have an older version of DW MX 2004, 7.0.1.2181 and have tried to install on my MacBook running 10.5.5. I have tried using my old PowerBook as a target drive and copying the application files to the MacBook but DW wouldn't launch and then I used th