Variable from one class to another

I have a Program that contains a JDesktop Pane, and when the program starts, it creates the "main" window as in JInternal Frame.
When a certain check box is checked, I call an external class that creates and returns a JInternalFrame. What I need to do is have the external class get a Vector from the main class (I pass it in when i create the object), edit the Vector, then return it to the main class. If i try to create a method in the main class like "returnVector()" or whatever to get the vector back to the main class, I get the error of "Non-static variable cannot be referenced from a non-static context". How can I get around that? The NEXT issue is this: I would like to cause the JInternalFrame that is created from the external class (on the JDesktopPane in the main class) to close itself when a button in it is clicked. I'm guess I'd need a Listener somewhere. Would that listener be in the Main class or in the external one. Does this make sense? Any help would be greatly appreciated.

Sorry, This might be a bit lengthy, but it works and illustrates my problem. I created it in NetBeans. There are the two classes I'm jusing. The issue is illustrated in the button listener on the 2nd class:
The First:
package javaapplication3;
import java.beans.PropertyVetoException;
import java.util.Vector;
import javax.swing.JInternalFrame;
public class NewJFrame extends javax.swing.JFrame {
    Vector <String> TestVector = new Vector <String> (0); //Vector to move around.
    public NewJFrame() {
        //add some test strings to the Vector
        TestVector.add("String1");
        TestVector.add("String2");
        TestVector.add("String3");
        initComponents();
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
    private void initComponents() {
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jInternalFrame1.getContentPane().setLayout(new java.awt.FlowLayout());
        jInternalFrame1.setVisible(true);
        jLabel1.setText("This is a VERY simple example");
        jInternalFrame1.getContentPane().add(jLabel1);
        jButton1.setText("Press this");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonListen(evt);
        jInternalFrame1.getContentPane().add(jButton1);
        jInternalFrame1.setBounds(10, 10, 350, 120);
        jDesktopPane1.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jDesktopPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jDesktopPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        pack();
    }// </editor-fold>                       
    private void ButtonListen(java.awt.event.ActionEvent evt) {                             
        JInternalFrame newFrame;
        NewJFrame2 roadframe = new NewJFrame2(TestVector);
        newFrame= roadframe.getFrameBack();
        newFrame.setVisible(true);
        jDesktopPane1.add(newFrame);
        try {
            newFrame.setSelected(true);
        } catch (PropertyVetoException ex) {
            ex.printStackTrace();
    //created this in hopes of using it to return the vector from NewJFrame2
    public void returnVector(Vector<String> vectorAgain){
        this.TestVector=vectorAgain;
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                  
}The 2nd:
package javaapplication3;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JInternalFrame;
public class NewJFrame2 extends javax.swing.JFrame {
    Vector <String> testVector=new Vector<String>(0);
    DefaultListModel model;
    public NewJFrame2(Vector <String> TestVector) {
        this.testVector=TestVector;
        initComponents();
    public JInternalFrame getFrameBack(){
        return jInternalFrame1;
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        jInternalFrame1 = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        model=new DefaultListModel();
        for (int a=0; a<testVector.size();a++){
            model.addElement(testVector.get(a));
        jList1 = jList1=new javax.swing.JList(model);
        jButton1 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jInternalFrame1.setVisible(true);
        jLabel1.setText("This is the 2nd class I was referencing I passed TestVector from NewFrame. It Contains:");
        jInternalFrame1.getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
        jLabel2.setText("Now I want to Edit this list here, and then send it back to NewFrame1. The button will attemp.");
        jInternalFrame1.getContentPane().add(jLabel2, java.awt.BorderLayout.SOUTH);
        jScrollPane1.setViewportView(jList1);
        jInternalFrame1.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
        jButton1.setText("Return Vector");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ReturnVectorButtonListener(evt);
        jInternalFrame1.getContentPane().add(jButton1, java.awt.BorderLayout.EAST);
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jInternalFrame1)
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jInternalFrame1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        pack();
    }// </editor-fold>
    private void ReturnVectorButtonListener(java.awt.event.ActionEvent evt) {
    NewJFrame.returnVector(testVector);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
}

Similar Messages

  • 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.

  • 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

  • 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.

  • Using a variable from one class to another

    Hi !
    I've a class called ModFam (file ModFam.java) where I define a variable as
    protected Connection dbconn;
    Inside ModFam constructor I said:
    try
    String url = "jdbc:odbc:baselocal";
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    dbconn = DriverManager.getConnection(url);
    System.err.println("Connection successful");
    } ..... rest of code
    This class define a TabbedPane as follows:
    tabbedPane.addTab("Welcome",null,new Familias(),"Familias");
    As you can see it call a new instance of the Familias class (file Familias.java).
    This constructor will try to connect with the DB to populate a combo box with some data retireved from the DB.
    If I do
    Statement stmt;
    stmt = dbconn.createStatement();
    inside Familias constructor I receive the message
    Familias.java:50: cannot resolve symbol
    symbol : variable dbconn
    location: class fam.Familias
    stmt = dbconn.createStatement();
    at compile time.
    While I can�t use a variable defined as "protected" in one class of my package on another class of the same package ?
    How could I do ?
    Thanks in advance
    <jl>

    Familias doesn't have a reference to ModFam or the Connection.
    So change the constructor in Familias to be
    public class Familias {
      private ModFam modFam;
      public Familias(ModFam m) {
        modFam = m;
    // ... somewhere else in the code
    Statement stmt = modFam.dbconn.createStatement();
    }or
    public class Familias {
      private Connection dbconn;
      public Familias(Connection c) {
        dbconn = c;
    // ... somewhere else in the code
    Statement stmt = dbconn.createStatement();
    }And when you instantiate Familias it should then be
    new Familias(this) // ModFam reference
    or
    new Familias(dbconn)

  • Sending a variable from one class to another?

    Dear Java Users - please can you help me out here... I know that what I am asking should be straight forward BUT I just don't understand any of the responses people have put on the web....
    Here is what I am trying to do:
    This piece of code - creates a window with a simple textbox on it to enter a word...
    The button then calls another class file to open a new window...
    All I want to do is to take the word from the text box and print it in the new window....
    The first .java file I have is this:
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class FrontPageGUI extends JFrame implements ActionListener
         //declare all instance variables for THIS per class
              JLabel lblInfoOne;
              JLabel lblButtonPopUp;
              JTextField txtName;
              JButton close;
              JButton popUp;
         public FrontPageGUI()
              //set characteristics of the JFrame object
              super("Title Bar");
              setSize(600,600);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              //we need to define a Container to place objects onto the frame - this is inside the JFrame Object Above
              Container ca = getContentPane( );
              ca.setSize(600,600);
              ca.setBackground(Color.white);
              ca.setLayout(null);                
              //define all other objects and set thier characteristics
              lblInfoOne     = new JLabel("Enter a word in the box above to send:");
              lblButtonPopUp = new JLabel("Click Here:");
              txtName          = new JTextField("");
              //create Button components
              close = new JButton("Close");
              popUp = new JButton("Click Me");
              //now add all objects to the container
              //Labels
              addXY(ca,lblInfoOne, 30, 160, 550,45);
              addXY(ca,lblButtonPopUp, 30, 210, 550,45);
              //TextField
              addXY(ca,txtName, 120, 100, 200,30);
              //Buttons
              addButtonXY(ca, popUp, 30, 260, 200, 45);
              addButtonXY(ca, close, 30, 310, 80, 30);
              // add the Container to the Frame     
              setContentPane(ca);          
         void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
               cp.setBounds(x,y,w,h);
               cp.addActionListener(this);
               c.add(cp);     
         void addXY(Container c, Component cp, int x, int y, int w, int h)
               cp.setBounds(x,y,w,h);
               c.add(cp);
         public void actionPerformed(ActionEvent event)
              if (event.getSource()== popUp)
                   //This is WHERE THE PROBLEM IS...
                   //Here I want to send to contents of the textfield - txtName
                   String temp = txtName.getText();
                   new PopUpGUI(temp);
              if (event.getSource()==close)
                   closeUp();
         void closeUp()
              System.exit(0);
              //dispose();
    //we need a driver program - this is the only time MAIN is used.
    public class FrontPage
         //create an instance of the GUI and showit
         public static void main(String args [])
              new FrontPageGUI();
                   The second .java file I have is this:
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class PopUpGUI extends JFrame implements ActionListener
         //declare all instance variables ie per class
              JLabel headerLabel;
              JLabel sentLabel;          
              JButton close;
         public PopUpGUI(String Sent)
              //set characteristics of the JFrame object
              super("Pop Up Window");
              setSize(320,450);
              setVisible(true);
              //need to define a Container to place objects onto the frame
              Container ca = getContentPane( );
              ca.setSize(320,450);
              ca.setLayout(null);                
              //define all other objects and set characteristics
              headerLabel = new JLabel("New Window!"); //heading label
              sentLabel = new JLabel(Sent);
              close = new JButton("Close");
              //now add all objects to the container
              addXY(ca,headerLabel,10,10,380,80);
              addXY(ca,sentLabel,10,100,380,80);
              addButtonXY(ca, close, 50, 200, 100, 30); //Bottom Left
              // add the Container to the Frame     
              setContentPane(ca);
         //We need these 2 methods - EVERY TIME
         void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
               cp.setBounds(x,y,w,h);
               cp.addActionListener(this);
               c.add(cp);     
         void addXY(Container c, Component cp, int x, int y, int w, int h)
               cp.setBounds(x,y,w,h);
               c.add(cp);
         //What to do when the click happens
         public void actionPerformed(ActionEvent event)
              if (event.getSource()==close)
                   dispose();
                   //closeUp(); - Doesn't run CLOSEUP this time (i.e. exit program) - instead just DISPOSEs of the window
    //Driver class is in FrontPage.javaThis seems to work... but is it the best way to do it????
    Tony.

    Well,
    Using the constructor is the way to go. Otherwise create a method that takes the string as parameter.

  • Is there a way to reference a private variable from one class in another?

    My first class starts off by declaring variables like so:
    class tStudent {
      // declare student name, id, grades 1 & 2, and gpa
      private String fname, lname, g1, g2;
      private int id;
      private double gpa;
      // define a constructor for a new student
      tStudent () {fname=lname=g1=g2=null; id=-1; gpa=0.0;}
      // define methods for manipulating the data members.
      // readStudent: reads information for just one student
    public void read (Scanner input) {
          fname = input.next();
          lname = input.next();
          id = input.nextInt();
          g1 = input.next();
          g2 = input.next();
    }And the second class:// tStudentList: for a list of students
    class tStudentList {
      private int nStudents;
      private tStudent[] list;
      // constructor for creating student list
      tStudentList() {
          list = new tStudent[36];
          for (int i=0; i < 36; i++) list=new tStudent();
    // read the individual students into the student list
    public void read(Scanner scan) {
    nStudents=0;
    while (scan.hasNext()) {list[nStudents++].read(scan);}
    // display the list of all students - fname, lname, id, g1, g2 and gpa
    // with an appropriate header so the output matches my sample //output
    public void print() {
    Is there a way to reference the variables in the first class to use in the second? Specifically in the last section of code where I am going to print the list.

    Not without resorting to reflection hackery. If the fields are private (and are supposed to be), then that means "don't allow access to these to outsiders of this class" by design.
    So if you really meant them to be accessible, then don't use private, or provide public accessors for them.

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

    hello,
    i have "One.as", which is the document class for one.swf.
    i also have "two.swf", with "Two.swf" entered as its document
    class...
    One loads two into it. two is basically a 10 frame movieClip
    with a variable at the beginning called "var endFrame:Boolean =
    false", then on the last frame it says endFrame = true.
    my question: how in the world do I communicate this back to
    One.as??? i've tried ENTER_FRAME listeners, declaring the variable
    here and there... and many other embarrassingly usuccessful
    strategies.
    i would just like to load in "three.swf" after two.swf
    finishes... but One needs to know that it has indeed finished.
    your help would be greatly appreciated. thanks

    yarkehsiow,
    > David,
    > thank you for responding.
    Sure thing! :)
    > so does what you are saying mean that endFrame is a
    property of
    > two (the movieClip), or Two (the Class)?
    If you've written a property named endFrame for your Two
    class, then
    yes, Two.endFrame is a property of that class.
    Looking back at your original post, I see that you wrote
    this:
    > One loads two into it. two is basically a 10 frame
    movieClip
    > with a variable at the beginning called "var
    endFrame:Boolean = false",
    > then on the last frame it says endFrame = true.
    So it sounds like your Two class extends MovieClip. (I'm not
    sure
    that's true, but that's what it sounds like.) That means your
    Two class
    supports all the features of the MovieClip class, including a
    play() method,
    a currentFrame property, and so on. In addition, you've added
    new
    functionality that amounts to -- by the sound of it -- a
    property named
    endFrame. If you made your property public (i.e., public var
    endFrame),
    then it should be accessible by way of an object reference to
    your Two
    instance.
    myTwoInstance.endFrame;
    > so can i invoke that method in One.as? do I call it
    Two.endFrame (if
    > (Two.endFrame == true) {?
    Methods are things an object can *do,* such as
    gotoAndPlay(). What
    you're describing is a property (a characteristic ... in this
    case, a
    Boolean characteristic). You wouldn't use the expression
    Two.endFrame
    unless that property was static. Static classes are those
    that cannot have
    an instance made of them. Think of the Math class. It
    contains numerous
    static properties in the form of constants, such as Math.PI,
    Math.E,
    Math.SQRT2, and so on. You can't create an instance of the
    Math class -- it
    wouldn't make sense to -- so Math is a static class.
    On the other hand, you definitely create instances of the
    MovieClip
    class. Every movie clip symbol is an instance of MovieClip
    class, which
    means that each instance carries its own unique values for
    MovieClip class
    members. The MovieClip class defines x and y properties, but
    each movie
    clip symbol (that is, each instance of the MovieClip class)
    configures its
    own values of those properties, depending on where each
    instance is located
    on the Stage.
    Assuming your Two class is not static, then somewhere along
    the line,
    your One class will have to make an instance of it. Somethine
    like ...
    // inside your One class ...
    var myTwo:Two = new Two();
    ... at which point that myTwo variable because a reference to
    that
    particular instance of Two. You can invoke Two methods on
    that instance.
    You can invoke Two properties and events on that instance.
    You can invoke
    whatever functionality is defined by the Two class on that
    myTwo instance.
    If Two extends MovieClip, that means you can also invoke any
    MovieClip class
    member on that myTwo instance.
    At some point in your One class, you can refer to that myTwo
    instance
    later and check if the value of myTwo.endFrame is true or
    false.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Passing a variable from one class to another

    Hello:
    I am new to java programming. I am developing an application in Java
    At a particular JTextField call it jtf3, I am invoking Calendar application by clikcing a jbutton.
    I would like to set text in jtf by obtaining the date clicked by the user. I am storing complete date string in the Calendar application during ActionPerformed event at Calendar Application level.
    I do not know how to pass this string to calling frame as it does not listen to the button event happening at the Calendar Application.
    Much appreciated
    Thanks a lot for your time
    regards

    This is the application from which the I am calling the calendar application.
    The method setDate set the date obtained from calendar class during actionperformed event.
    The actionperfomed event from CalendarClass is pasted below as well.
    Much appreciated
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.*;
    public class TestDrive
    public static void main(String[] args) {
    DatePanelFrame dpf = new DatePanelFrame();
    dpf.addWindowListener(new WindowAdapter( ) {
    public void windowClosing(WindowEvent we) { System.exit(0); }
    dpf.pack();
    dpf.setVisible(true);
    class DatePanelFrame extends JFrame {
    JTextField djtf;
    String dateInput;
    public DatePanelFrame() {
    setTitle("Date Panel");
    setSize(100, 800);
    setLocation(300, 100);
    Container content = getContentPane();
    JPanel datePanel = new JPanel();
    JButton calButton = new JButton(".....");
    datePanel.add(calButton, BorderLayout.SOUTH);
    djtf = new JTextField(" ");
    datePanel.add(djtf, BorderLayout.NORTH);
    content.setLayout(new BorderLayout());
    content.add(datePanel, BorderLayout.CENTER);
    calButton.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent event)
    JFrame fr = new CalendarClass();
    fr.setSize(400, 400);
    fr.setLocation(600, 100);
    ObjCal oc = new ObjCal();
    fr.setVisible(true);
    public void setDate(String d)
    djtf.setText(d);
    repaint();
    System.out.println(djtf.getText());
    The ActionPerformed event from CalendarClass
    jbtArray.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent event)
    if (event.getActionCommand() != " ")
              daySelected = event.getActionCommand();
              yearSelected = jtfYear.getText();
              int intYearSelected = Integer.valueOf(yearSelected).intValue();
              monthSelected = jtfMonth.getText();
              intDaySelected = Integer.valueOf(daySelected).intValue();
              int intMonthSelected = getMonthNum(monthSelected);
              dateSelected = getDate(intYearSelected, intMonthSelected, intDaySelected);
              TestDrive td = new TestDrive();
              DatePanelFrame dpf = new DatePanelFrame();
              dpf.setDate(dateSelected);

  • Using a variable from one class in another

    For learning purposes, I thought I'd have a stab at making a role-playing RPG.
    The first class I made was the Player class;
    public class Player
         public static void main(String[] args)
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public static String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public static void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public static void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public static void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public static void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public static void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public static void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public static void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
    }And that would be used in the Play class;
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }     But I'm not sure how the Play class will get the arrays from the Player class. I tried simply putting public in front of the them, for example;
    public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};But I get an illegal start of expression error.
    I may have taken the wrong approach to this all together, I'm completely new, so feel free to suggest anything else. Sorry for any ambiguity.
    Edited by: xcd on Jan 6, 2010 8:12 AM
    Edited by: xcd on Jan 6, 2010 8:12 AM

    HI XCD ,
    what about making Player class as
    public class Player
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
         }and Play class
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }Now you can access names , you can't assign keyword to variable into method scope , make it class variable .
    Hope it help :)

  • Variable from one class to another in a game

    I am making a game in which a user can enter the speed of the initial velocity of a ball. My problem is that when i run the program and enter the speed of the ball in the JTextField, it doesn't actually change the speed of the ball. The ball just uses the speed that was set before the program ran
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.*;
    import java.util.*;
    /*Main Class*/
    class Junaid_Java_ISU
         public static void main(String[] args)
             JFrame frame = new GameFrame();
             frame.show();
    /*GameFrame Class*/
    class GameFrame extends JFrame implements ActionListener                                                  //got rid of BounceThreadFrame
         public JTextField getHeight;
         public JTextField velocityText;
         private JTextField windSpeed;
         private double dxUser = 5;
         private int hyUser;
         private JPanel canvas;
           public GameFrame()
                setSize(640, 480);
             setTitle("Bounce");
             addWindowListener(new WindowAdapter()                                    //Need to replace this with one line
                    public void windowClosing(WindowEvent e)
                         System.exit(0);
             Container contentPane = getContentPane();
             canvas = new JPanel();
             contentPane.add(canvas, "Center");
             JPanel p = new JPanel();
             getHeight = new JTextField(2);
             getHeight.addActionListener(this);
             velocityText = new JTextField(2);
             velocityText.addActionListener(this);
             windSpeed = new JTextField(2);
             windSpeed.setEditable(false);
             velocityText.setText("5");
             /*Start Button*/
               JButton start = new JButton("Start");
               p.add(start);
               start.addActionListener(this);
               /*Close Button*/
               JButton close = new JButton("Close");
               p.add(close);
               close.addActionListener(this);
             contentPane.add(p, "South");
             p.add(new JLabel ("Enter Height:"));
             p.add(getHeight);
             p.add(new JLabel ("Enter X Velocity:"));
             p.add(velocityText);
             p.add(new JLabel ("Velocity Test:"));                              //Change this to "Wind Speed:" after
             p.add(windSpeed);
         public void actionPerformed (ActionEvent e)
                if (e.getActionCommand().equals("Start"))
                     Ball b = new Ball(canvas);
                 b.start();
                 windSpeed.setText("" + getVelocity());
                else if (e.getActionCommand().equals("Close"))
                 canvas.setVisible(false);
                 System.exit(0);                 
           public double getVelocity()
                 return Double.parseDouble(velocityText.getText().trim());
    /*Ball Class*/
    class Ball extends Thread
         GameFrame vx = new GameFrame();
         double getDx = vx.getVelocity();
           public Ball(JPanel b)
                 box = b;
           public void draw()                                        //Draw ball
             Graphics g = box.getGraphics();
             g.fillOval(x, y, XSIZE, YSIZE);
             g.dispose();                                        //Might not need this
           /*This is how the ball will move Speed of ball*/
           public void move()
             if (!box.isVisible())
                    return;
             Graphics g = box.getGraphics();
             g.setXORMode(box.getBackground());
             g.fillOval(x, y, XSIZE, YSIZE);
             x += dx;
             y += dy;
             Dimension d = box.getSize();
             /*Change velocity*/
             dx = getDx;
             if (x>= 615 || y>= 390)
                  dx = 0;
                  dy = 0;
             else if(y<= 0)
                  dy = dy + 0.2;
             else
                  if (x>=0)
                       long elapsed = System.currentTimeMillis() - start;               //Current time
                       dx = (dx + windX + (0 * elapsed));
                  if (y >= 0)
                       long elapsed = System.currentTimeMillis() - start;
                       dy = ((dy + windY + (accelY * elapsed)) * 0.0005);
             g.fillOval(x, y, XSIZE, YSIZE);
             g.dispose();                                                                      //Possibly need to remove
           public void run()
             try
               draw();
               for (int i = 1; i <= 1000; i++)                    //Number of times the ball moves
                 move();
                 sleep(25);                                             //Speed of ball
             } catch (InterruptedException e)
           private JPanel box;
           /*Size of ball*/
           private static final int XSIZE = 10;
           private static final int YSIZE = 10;
           /*Possition of ball*/
           private int x = 0;
           private int y = 300;
           /*X and Y speed of ball*/
           private double dx = 0;                         //Changed from int to double
           private double dy = 0;                              //Vertical Distance
           long start = System.currentTimeMillis();          //Computer Time
           //Wind and acceleration
           private static final double accelY = 9.8;
           private double windX = (2 * Math.random()) + 0;
           private double windY = (-7000 * Math.random()) + 0;
    }

    Junaid wrote:
    I am making a game in which a user can enter the speed of the initial velocity of a ball. My problem is that when i run the program and enter the speed of the ball in the JTextField, it doesn't actually change the speed of the ball. The ball just uses the speed that was set before the program ranFirst, from my experiences, use the JPanel's paint( Graphics ) method and the passed graphics rather than writing your own draw().
    Second, and the reason your ball speed doesn't change, is that in the creation of the Ball, it makes its own GameFrame, rather than using the old one.
    Change the start of Ball to:
    class Ball extends Thread
         GameFrame vx;
         double getDx;
           public Ball(JPanel b, GameFrame vx)
                    this.vx = vx;
                    getDx = vx.getVelocity()
                 box = b;
           }and the creation of the Ball to:
         public Ball makeBall() {
              return new Ball( canvas, this );
         public void actionPerformed (ActionEvent e)
                if (e.getActionCommand().equals("Start"))
                   // the reason I don't say Ball( canvas, this ) here
                   // is that this statement is inside an ActionListener
                   // not a GameFrame.
                   // Calling a method in GameFrame will pass the right object
                     Ball b = makeBall();
                   .

  • How to transter contents of itab from one class to another...

    Hello experts,
    I am currently having problems on how to transfer the contents of an itab or even
    the value of a variable from one class to another. For example, I have 10 records
    in it_spfli in class 1 and when I loop at it_spfli in the method of class 2 it has no records!
    This is an example:
    class lcl_one definition.
    public section.
    data: gt_spfli type table of spfli.
    methods get_data.
    endclass.
    class lcl_one implementation.
    method get_data.
      select * from spfli
      into table gt_spfli.
    endmethod.
    endclass.
    class lcl_two definition inheriting from lcl_one.
    public section.
      methods loop_at_itab.
    endclass.
    class lcl_two implementation.
    method loop_at_itab.
      field-symbols: <fs_spfli> like line of gt_spfli.
      loop at gt_spfli assigning <fs_spfli>.
       write: / <fs_spfli>-carrid.
      endloop.
    endmethod.
    endclass.
    start-of-selection.
    data: one type ref to lcl_one,
          two type ref to lcl_two.
    create object: one, two.
    call method one->get_data.
    call method two->loop_at_itab.
    In the example above, the contents of gt_spfli in class lcl_two is empty
    even though it has records in class lcl_one. Help would be appreciated.
    Thanks a lot guys and take care!

    Hi Uwe,
    It is still the same. Here is my code:
    REPORT zfi_ors_sms
           NO STANDARD PAGE HEADING
           LINE-SIZE 255
           LINE-COUNT 65
           MESSAGE-ID zz.
    Include program/s                            *
    INCLUDE zun_standard_routine.           " Standard Routines
    INCLUDE zun_header.                     " Interface Header Record
    INCLUDE zun_footer.                     " Interface Footer Record
    INCLUDE zun_interface_control.          " Interface Control
    INCLUDE zun_external_routine.           " External Routines
    INCLUDE zun_globe_header.               " Report header
    INCLUDE zun_bdc_routine.                " BDC Routine
    Data dictionary table/s                      *
    TABLES: bkpf,
            rf05a,
            sxpgcolist.
    Selection screen                             *
    SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
    PARAMETERS: p_file TYPE sxpgcolist-parameters.
    SELECTION-SCREEN END OF BLOCK b1.
    */ CLASS DEFINITIONS
          CLASS lcl_main DEFINITION
    CLASS lcl_main DEFINITION ABSTRACT.
      PUBLIC SECTION.
    Structure/s                                  *
        TYPES: BEGIN OF t_itab,
                rec_content(100) TYPE c,
               END OF t_itab.
        TYPES: BEGIN OF t_upfile,
                record_id(2)    TYPE c,            " Record ID
                rec_date(10)    TYPE c,            " Record Date MM/DD/YYYY
                prod_line(10)   TYPE c,            " Product Line
                acc_code(40)    TYPE c,            " Acc Code
                description(50) TYPE c,            " Description
                hits(13)        TYPE c,            " Hits
                amount(15)      TYPE c,            " Amount
               END OF t_upfile.
    Internal table/s                             *
        DATA: gt_bdcdata    TYPE STANDARD TABLE OF bdcdata,
              gt_bdcmsgcoll TYPE STANDARD TABLE OF bdcmsgcoll,
              gt_itab       TYPE STANDARD TABLE OF t_itab,
              gt_header     LIKE TABLE OF interface_header,
              gt_footer     LIKE TABLE OF interface_footer,
              gt_upfile     TYPE STANDARD TABLE OF t_upfile.
    Global variable/s                            *
        DATA: gv_target             TYPE rfcdisplay-rfchost,
              gv_err_flag(1)        TYPE n VALUE 0,
              gv_input_dir(100)     TYPE c
                                     VALUE '/gt/interface/FI/ORS/inbound/',
              gv_inputfile_dir(255) TYPE c,
              gv_eof_flag           TYPE c VALUE 'N',
              gv_string             TYPE string,
              gv_delimiter          TYPE x VALUE '09',
              gv_input_records(3)   TYPE n,
              gv_input_file_ctr(6)  TYPE n,
              gv_proc_tot_amt(14)   TYPE p DECIMALS 2,
              gv_prg_message        TYPE string,
              gv_gjahr              TYPE bkpf-gjahr,
              gv_monat              TYPE bsis-monat.
    Work area/s                                  *
        DATA: wa_itab               LIKE LINE OF gt_itab,
              wa_upfile             LIKE LINE OF gt_upfile,
              wa_footer             LIKE LINE OF gt_footer,
              wa_header             LIKE LINE OF gt_header.
    ENDCLASS.
          CLASS lcl_read_app_server_file DEFINITION
    CLASS lcl_read_app_server_file DEFINITION INHERITING FROM lcl_main.
      PUBLIC SECTION.
        METHODS: read_app_server_file,
                 read_input_file,
                 split_header,
                 process_upload_file,
                 split_string,
                 conv_num CHANGING value(amount) TYPE t_upfile-amount,
                 split_footer,
                 update_batch_control,
                 process_data.
    ENDCLASS.
          CLASS lcl_process_data DEFINITION
    CLASS lcl_process_data DEFINITION INHERITING FROM
                                                 lcl_read_app_server_file.
      PUBLIC SECTION.
        METHODS process_data REDEFINITION.
    ENDCLASS.
    */ CLASS IMPLEMENTATIONS
          CLASS lcl_read_app_server_file IMPLEMENTATION
    CLASS lcl_read_app_server_file IMPLEMENTATION.
    */ METHOD read_app_server_file  -  MAIN METHOD
      METHOD read_app_server_file.
        gv_target = sy-host.
        PERFORM file_copy USING 'ZPPDCP' p_file 'HP-UX'
                gv_target CHANGING gv_err_flag.
        CONCATENATE gv_input_dir p_file INTO gv_inputfile_dir.
      open application server file
        PERFORM open_file USING gv_inputfile_dir 'INPUT'
                                   CHANGING gv_err_flag.
        WHILE gv_eof_flag = 'N'.
          READ DATASET gv_inputfile_dir INTO wa_itab.
          APPEND wa_itab TO gt_itab.
          IF sy-subrc <> 0.
            gv_eof_flag = 'Y'.
            EXIT.
          ENDIF.
          CALL METHOD me->read_input_file.
        ENDWHILE.
      close application file server
        PERFORM close_file USING gv_inputfile_dir.
        IF wa_footer-total_no_rec <> gv_input_file_ctr.
          MOVE 'Header Control on Number of Records is Invalid' TO
               gv_prg_message.
          PERFORM call_ws_message USING 'E' gv_prg_message 'Error'.
          gv_err_flag = 1.
        ELSEIF wa_footer-total_no_rec EQ 0 AND gv_input_file_ctr EQ 0.
          MOVE 'Input File is Empty. Batch Control will be Updated' TO
               gv_prg_message.
          PERFORM call_ws_message USING 'I' gv_prg_message 'Information'.
          CALL METHOD me->update_batch_control.
          gv_err_flag = 1.
        ENDIF.
        IF gv_err_flag <> 1.
          IF wa_footer-total_amount <> gv_proc_tot_amt.
            MOVE 'Header Control on Amount is Invalid' TO gv_prg_message.
            PERFORM call_ws_message USING 'E' gv_prg_message 'Error'.
            gv_err_flag = 1.
          ENDIF.
        ENDIF.
      ENDMETHOD.
    */ METHOD read_input_file
      METHOD read_input_file.
        CASE wa_itab-rec_content+0(2).
          WHEN '00'.
            CALL METHOD me->split_header.
          WHEN '01'.
            CALL METHOD me->process_upload_file.
            ADD 1 TO gv_input_file_ctr.
            ADD wa_upfile-amount TO gv_proc_tot_amt.
          WHEN '99'.
            CALL METHOD me->split_footer.
          WHEN OTHERS.
            gv_err_flag = 1.
        ENDCASE.
      ENDMETHOD.
    */ METHOD split_header
      METHOD split_header.
        CLEAR: wa_header,
               gv_string.
        MOVE wa_itab TO gv_string.
        SPLIT gv_string AT gv_delimiter INTO
              wa_header-record_id
              wa_header-from_system
              wa_header-to_system
              wa_header-event
              wa_header-batch_no
              wa_header-date
              wa_header-time.
        APPEND wa_header TO gt_header.
      ENDMETHOD.
    */ METHOD process_upload_file
      METHOD process_upload_file.
        CLEAR gv_string.
        ADD 1 TO gv_input_records.
        MOVE wa_itab-rec_content TO gv_string.
        CALL METHOD me->split_string.
        CALL METHOD me->conv_num CHANGING amount = wa_upfile-amount.
        APPEND wa_upfile TO gt_upfile.
      ENDMETHOD.
    */ METHOD split_string
      METHOD split_string.
        CLEAR wa_upfile.
        SPLIT gv_string AT gv_delimiter INTO
              wa_upfile-record_id
              wa_upfile-rec_date
              wa_upfile-prod_line
              wa_upfile-acc_code
              wa_upfile-description
              wa_upfile-hits
              wa_upfile-amount.
      ENDMETHOD.
    */ METHOD conv_num
      METHOD conv_num.
        DO.
          REPLACE gv_delimiter WITH ' ' INTO amount.
          IF sy-subrc <> 0.
            EXIT.
          ENDIF.
        ENDDO.
      ENDMETHOD.
    */ METHOD split_footer
      METHOD split_footer.
        CLEAR: wa_footer,
               gv_string.
        MOVE wa_itab TO gv_string.
        SPLIT gv_string AT gv_delimiter INTO
              wa_footer-record_id
              wa_footer-total_no_rec
              wa_footer-total_amount.
        CALL METHOD me->conv_num CHANGING amount = wa_footer-total_amount.
        APPEND wa_footer TO gt_footer.
      ENDMETHOD.
    */ METHOD update_batch_control
      METHOD update_batch_control.
        DATA: lv_sys_date      TYPE sy-datum,
              lv_sys_time      TYPE sy-uzeit,
              lv_temp_date(10) TYPE c.
        CONCATENATE wa_header-date4(4) wa_header-date2(2)
                    wa_header-date+0(2)
               INTO lv_temp_date.
        MOVE lv_temp_date TO wa_header-date.
        APPEND wa_header-date TO gt_header.
      Update ZTF0001 Table
        PERFORM check_interface_header USING wa_header 'U' 'GLOB'
                                       CHANGING gv_err_flag.
      Archive files
        PERFORM archive_files USING 'ZPPDARC' gv_inputfile_dir 'HP-UX'
                gv_target CHANGING gv_err_flag.
      ENDMETHOD.
      METHOD process_data.
        SORT gt_upfile ASCENDING.
        CLEAR wa_upfile.
        READ TABLE gt_upfile INDEX 1 INTO wa_upfile.
        IF sy-subrc = 0.
          MOVE: wa_upfile-rec_date+6(4) TO gv_gjahr,
                wa_upfile-rec_date+0(2) TO gv_monat.
        ENDIF.
      ENDMETHOD.
    ENDCLASS.
          CLASS lcl_process_data IMPLEMENTATION
    CLASS lcl_process_data IMPLEMENTATION.
      METHOD process_data.
        CALL METHOD super->process_data.
        IF NOT gt_upfile[] IS INITIAL.
        ENDIF.
      ENDMETHOD.
    ENDCLASS.
    Start of selection                           *
    START-OF-SELECTION.
      DATA: read TYPE REF TO lcl_read_app_server_file,
            process TYPE REF TO lcl_process_data.
      CREATE OBJECT: read, process.
      CALL METHOD read->read_app_server_file.
      CALL METHOD process->process_data.

  • Reading a variable from one method to another method

    I am pretty new to Java and object code, so please understand if you think I should know the answer to this.
    I wish to pass a variable from one method to another within one servet. I have a doPost method:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              HttpSession session = request.getSession();
             String userID = (String)session.getAttribute("userID");
             String title = request.getParameter("title");
            PrintWriter out = response.getWriter();
            out.println("userID is ..."+userID);
    } and wish to pass the variable userID to:
      public static void writeToDB(String title) {
             try{
                  String connectionURL = "jdbc:mysql://localhost/cms_college";
                  Connection connection=null;     
                 Class.forName("com.mysql.jdbc.Driver");
                 connection = DriverManager.getConnection(connectionURL, "root", "");
                 Statement st = connection.createStatement();         
                   st.executeUpdate ("INSERT INTO cmsarticles (title, userID) VALUES('"+title+"','"+userID+"')");
             catch(Exception e){
                   System.out.println("Exception is ;"+e);
        }because, at the moment the userID cannot be resolved in the writeToDB method. Thanking you in anticipation.

    Thanks for responding.
    If I replace
    public static void writeToDB(String title)with
    public static void writeToDB(String title, String userID)It throws up an error in the following method
    public void processFileItem(FileItem item) {
              // Can access all sorts of useful info. using FileItem methods
              if (item.isFormField()) {
                   //Map<String, String> formParameters = new LinkedHashMap<String, String>();
                   //String filename = item.getFieldName();
                   //String title = item.getString();
                   //System.out.println("received filename is ... " + filename );
                   //formParameters.put(title, filename);
                   } else {
                      // Is an uploaded file, so get name & store on local filesystem
                      String uploadedFileName = new File(item.getName()).getName();            
                      File savedFile = new File("c:/uploads/"+uploadedFileName);
                      long sizeInBytes = item.getSize();
                      System.out.println("uploadedFileName is " + uploadedFileName);
                      String title = uploadedFileName;
                      System.out.println("size in bytes is " + sizeInBytes);
                      writeToDB(title);
                      try {
                        item.write(savedFile);// write uploaded file to local storage
                      } catch (Exception e) {
                        // Problem while writing the file to local storage
              }      saying there are not enough arguments in writeToDB(title);
    and if I put in an extra argumenet writeToDB(title,String userID);
    again it does not recognise userID

  • Passing a parameter from one class to another class in the same package

    Hi.
    I am trying to pass a parameter from one class to another class with in a package.And i am Getting the variable as null every time.In the code there is two classes.
    i. BugWatcherAction.java
    ii.BugWatcherRefreshAction.Java.
    We have implemented caching in the front-end level.But according to the business logic we need to clear the cache and again have to access the database after some actions are happened.There are another class file called BugwatcherPortletContent.java.
    So, we are dealing with three java files.The database interaction is taken care by the portletContent.java file.Below I am giving the code for the perticular function in the bugwatcherPortletContent.java:
    ==============================================================
    public Object loadContent() throws Exception {
    Hashtable htStore = new Hashtable();
    JetspeedRunData rundata = this.getInputData();
    String pId = this.getPorletId();
    PortalLogger.logDebug(" in the portlet content: "+pId);
    pId1=pId;//done by sraha
    htStore.put("PortletId", pId);
    htStore.put("BW_HOME_URL",CommonUtil.getMessage("BW.Home.Url"));
    htStore.put("BW_BUGVIEW_URL",CommonUtil.getMessage("BW.BugView.Url"));
    HttpServletRequest request = rundata.getRequest();
    PortalLogger.logDebug(
    "BugWatcherPortletContent:: build normal context");
    HttpSession session = null;
    int bugProfileId = 0;
    Hashtable bugProfiles = null;
    Hashtable bugData = null;
    boolean fetchProfiles = false;
    try {
    session = request.getSession(true);
    // Attempting to get the profiles from the session.
    //If the profiles are not present in the session, then they would have to be
    // obtained from the database.
    bugProfiles = (Hashtable) session.getAttribute("Profiles");
    //Getting the selected bug profile id.
    String bugProfileIdObj = request.getParameter("bugProfile" + pId);
    // Getting the logged in user
    String userId = request.getRemoteUser();
    if (bugProfiles == null) {
    fetchProfiles = true;
    if (bugProfileIdObj == null) {
    // setting the bugprofile id as -1 indicates "all profiles" is selected
    bugProfileIdObj =(String) session.getAttribute("bugProfileId" + pId);
    if (bugProfileIdObj == null) {
    bugProfileId = -1;
    else {
    bugProfileId = Integer.parseInt(bugProfileIdObj);
    else {
    bugProfileId = Integer.parseInt(bugProfileIdObj);
    session.setAttribute(
    ("bugProfileId" + pId),
    Integer.toString(bugProfileId));
    //fetching the bug list
    bugData =BugWatcherAPI.getbugList(userId, bugProfileId, fetchProfiles);
    PortalLogger.logDebug("BugWatcherPortletContent:: got bug data");
    if (bugData != null) {
    Hashtable htProfiles = (Hashtable) bugData.get("Profiles");
    } else {
    htStore.put("NoProfiles", "Y");
    } catch (CodedPortalException e) {
    htStore.put("Error", CommonUtil.getErrMessage(e.getMessage()));
    PortalLogger.logException
    ("BugWatcherPortletContent:: CodedPortalException!!",e);
    } catch (Exception e) {
    PortalLogger.logException(
    "BugWatcherPortletContent::Generic Exception!!",e);
    htStore.put(     "Error",CommonUtil.getErrMessage(ErrorConstantsI.GET_BUGLIST_FAILED));
    if (fetchProfiles) {
    bugProfiles = (Hashtable) bugData.get("Profiles");
    session.setAttribute("Profiles", bugProfiles);
    // putting the stuff in the context
    htStore.put("Profiles", bugProfiles);
    htStore.put("SelectedProfile", new Integer(bugProfileId));
    htStore.put("bugs", (ArrayList) bugData.get("Bugs"));
    return htStore;
    =============================================================
    And I am trying to call this function as it can capable of fetching the data from the database by "getbugProfiles".
    In the new class bugWatcherRefreshAction.java I have coded a part of code which actually clears the caching.Below I am giving the required part of the code:
    =============================================================
    public void doPerform(RunData rundata, Context context,String str) throws Exception {
    JetspeedRunData data = (JetspeedRunData) rundata;
    HttpServletRequest request = null;
    //PortletConfig pc = portlet.getPortletConfig();
    //String userId = request.getRemoteUser();
    /*String userId = ((JetspeedUser)rundata.getUser()).getUserName();//sraha on 1/4/05
    String pId = request.getParameter("PortletId");
    PortalLogger.logDebug("just after pId " +pId);  */
    //Calling the variable holding the value of portlet id from BugWatcherAction.java
    //We are getting the portlet id here , through a variable from BugWatcherAction.java
    /*BugWatcherPortletContent bgAct = new BugWatcherPortletContent();
    String portletID = bgAct.pId1;
    PortalLogger.logDebug("got the portlet ID in bugwatcherRefreshAction:---sraha"+portletID);*/
    // updating the bug groups
    Hashtable result = new Hashtable();
    try {
    request = data.getRequest();
    String userId = ((JetspeedUser)data.getUser()).getUserName();//sraha on 1/4/05
    //String pId = (String)request.getParameter("portletId");
    //String pId = pc.getPorletId();
    PortalLogger.logDebug("just after pId " +pId);
    PortalLogger.logDebug("after getting the pId-----sraha");
    result =BugWatcherAPI.getbugList(profileId, userId);
    PortalLogger.logDebug("select the new bug groups:: select is done ");
    context.put("SelectedbugGroups", profileId);
    //start clearing the cache
    ContentCacheContext cacheContext = getCacheContext(rundata);
    PortalLogger.logDebug("listBugWatcher Caching - removing markup content - before removecontent");
    // remove the markup content from cache.
    PortletContentCache.removeContent(cacheContext);
    PortalLogger.logDebug("listBugWatcher Caching-removing markup content - after removecontent");
    //remove the backend content from cache
    CacheablePortletData pdata =(CacheablePortletData) PortletCache.getCacheable(PortletCacheHelper.getUserHandle(((JetspeedUser)data.getUser()).getUserName()));
    PortalLogger.logDebug("listBugWatcher Caching User: " +((JetspeedUser)data.getUser()).getUserName());
    PortalLogger.logDebug("listBugWatcher Caching pId: " +pId);
    if (pdata != null)
    // User's data found in cache!
    PortalLogger.logDebug("listBugWatcher Caching -inside pdata!=null");
    pdata.removeObject(PortletCacheHelper.getUserPortletHandle(((JetspeedUser)data.getUser()).getUserName(),pId));
    PortalLogger.logDebug("listBugWatcher Caching -inside pdata!=null- after removeObject");
    PortalLogger.logDebug("listBugWatcher Caching -finish calling the remove content code");
    //end clearing the cache
    // after clearing the caching calling the data from the database taking a fn from the portletContent.java
    PortalLogger.logDebug("after clearing cache---sraha");
    BugWatcherPortletContent bugwatchportcont = new BugWatcherPortletContent();
    Hashtable httable= new Hashtable();
    httable=(Hashtable)bugwatchportcont.loadContent();
    PortalLogger.logDebug("after making the type casting-----sraha");
    Set storeKeySet = httable.keySet();
    Iterator itr = storeKeySet.iterator();
    while (itr.hasNext()) {
    String paramName = (String) itr.next();
    context.put(paramName, httable.get(paramName));
    PortalLogger.logDebug("after calling the databs data from hashtable---sraha");
    } catch (CodedPortalException e) {
    PortalLogger.logException("bugwatcherRefreshAction:: Exception- ",e);
    context.put("Error", CommonUtil.getErrMessage(e.getMessage()));
    catch (Exception e) {
    PortalLogger.logException("bugwatcherRefreshAction:: Exception- ",e);
    context.put(     "Error",CommonUtil.getErrMessage(ErrorConstantsI.EXCEPTION_CODE));
    try {
    ((JetspeedRunData) data).setCustomized(null);
    if (((JetspeedRunData) data).getCustomized() == null)
    ActionLoader.getInstance().exec(data,"controls.EndCustomize");
    catch (Exception e)
    PortalLogger.logException("bugwatcherRefreshAction", e);
    ===============================================================
    In the bugwatcher Action there is another function called PostLoadContent.java
    here though i have found the portlet Id but unable to fetch that in the bugWatcherRefreshAction.java . I am also giving the code of that function under the bugWatcherAction.Java
    ================================================
    // Get the PortletData object from intermediate store.
    CacheablePortletData pdata =(CacheablePortletData) PortletCache.getCacheable(PortletCacheHelper.getUserHandle(
    //rundata.getRequest().getRemoteUser()));
    ((JetspeedUser)rundata.getUser()).getUserName()));
    pId1 = (String)portlet.getID();
    PortalLogger.logDebug("in the bugwatcher action:"+pId1);
    try {
    Hashtable htStore = null;
    // if PortletData is available in store, get current portlet's data from it.
    if (pdata != null) {
    htStore =(Hashtable) pdata.getObject(     PortletCacheHelper.getUserPortletHandle(
    ((JetspeedUser)rundata.getUser()).getUserName(),portlet.getID()));
    //Loop through the hashtable and put its elements in context
    Set storeKeySet = htStore.keySet();
    Iterator itr = storeKeySet.iterator();
    while (itr.hasNext()) {
    String paramName = (String) itr.next();
    context.put(paramName, htStore.get(paramName));
    bugwatcherRefreshAction bRefAc = new bugwatcherRefreshAction();
    bRefAc.doPerform(pdata,context,pId1);
    =============================================================
    So this is the total scenario for the fetching the data , after clearing the cache and display that in the portal.I am unable to do that.Presently it is still fetching the data from the cache and it is not going to the database.Even the portlet Id is returning as null.
    I am unable to implement that thing.
    If you have any insight about this thing, that would be great .As it is very urgent a promt response will highly appreciated.Please send me any pointers or any issues for this I am unable to do that.
    Please let me know as early as possible.
    Thanks and regards,
    Santanu Raha.

    Have you run it in a debugger? That will show you exactly what is happening and why.

  • OBIEE 11g How to pass variable from one prompt to another prompt in dashboard page.

      How to pass variable from one prompt to another prompt in dashboard page.
    I have two prompt in dashboard page as below.
    Reporttype
    prompt: values(Accounting, Operational) Note: values stored as
    presentation variable and they are not coming from table.
    Date prompt values (Account_date, Operation_date)
    Note:values are coming from dim_date table.  
    Now the task is When user select First
    Prompt value  “Accounting” Then in the
    second prompt should display only Accounting_dates , if user select “operational”
    and it should display only operation_dates in second prompt.
    In order to solve this issue I made the
    first prompt “Reporttype” values(Accounting, Operational) as presentation
    values (custom specific values) and default presentation value is accounting.
    In second prompt Date are coming from
    dim_date table and I selected Sql results as shown below.
    SELECT case when '@{Reporttype}'='Accounting'
    then "Dates (Receipts)"."Acct Year"
    else "Dates (Receipts)"."Ops
    Year"  End  FROM "Receipts"
    Issue: Presentation variable value is not
    changing in sql when user select “operation” and second prompt always shows
    acct year in second prompt.
    For testing pupose I kept this presentation
    variable in text object of dashboard and values are changing there, but not in
    second prompt sql.
    Please suggest the solution.

    You will want to use the MoveClipLoader class (using its loadClip() and addListener() methods) rather than loadMovie so that you can wait for the file to load before you try to access anything in it.  You can create an empty movieclip to load the swf into, and in that way the loaded file can be targeted using the empty movieclip instance name.

Maybe you are looking for

  • Withholding tax error

    Hi, Advance entry posted to the vendor with Rs.100000/- and TDS @ 2% on it in T.code f-48. Invoice entry posted to the same vendor for Rs.1000000/- and TDS @ 2% on it through T.code f-43.  For both the entries, FBL1N report shows Rs.100000 as advance

  • GRC 10.0 SP 14 access request form displays unassigned roles

    Dear experts, when I open the Access Request form and I select a user, and then I click on existing assignments, I am shown a list of roles and systems assigned to this user. However, when I go to those corresponding backend systems to see if the rol

  • Calling a function in an attached MovieClip

    I am trying the following, but it seems like the function is not getting called. If I trace it, it returns an undefined. What am I doing wrong? Thanks a lot for any help. this.attachMovie("team_" + whichProfile, "team_" + whichProfile, this.getNextHi

  • C Parser only Parses file?

    Re the new Parser for C I can only see a method to parse xml in a file, there doesn t seem anyway to parse froma buffer or stream. Is this correct or have I missed something. Thanks Rob null

  • Tuning Memory Structures

    Guys, My application runs on oracle Database, in order to improve the performance by reducing I/0 we haev spread the datafiles and redolog files across 4 different drives. Now when I try to tune application based on increasing the SGA, buffer cache (