Call a class from another class from JSP?

I was wondering if anyone could tell me where Im going wrong with this one. Why is the result different if I uses a class, than a jsp page. Returning a regular string is fine, but a string I read from a file...
I have an application that is structured like so:
The class "packClass1" in      app
package "TestPackage" simply      |
calls a method in class           jspPage1.jsp
"packClass2". "packClass2" reads |
a Properties type from a        WEB-INF
file and returns it. Then              |
packClass1 just passes a string      classes
using getProperty back to the          |
caller.                             normalClass1.java
                              |
If the caller is normalClass1.java     TestPackage
(from the console) then it responds        |
as expected, returning the string          packClass1.java
from the file. BUT - if the caller is      packClass2.java
the jspPage1.jsp, then it returns
"null". Here is the code (names have
been changed to protect the innocent...)jspPage1.jsp (this outputs: "result is: null"):<%@ page import="TestPackage.*" %>
<jsp:useBean id="testOne" scope="page" class="tpack.packClass1" />
<% out.println(testOne.getAString()); %>normalClass1.java (this outputs: "result is: gotFromFile"):import TestPackage.*;
public class two{
     public static void main(String args[]){
          packClass1 testOne = new packClass1();
          System.out.println(testOne.oneOne(getAString()));
          three.load();
}packClass1.java:package TestPackage;
import java.util.Properties;
public class packClass1{
     public packClass1(){}
     public String packClass1(){
          Properties props = packClass2.load();
          return props.getProperty("aStringValue");
}packClass2.java:package TestPackage;
import java.util.Properties;
import java.io.*;
public class three{
     public three(){};
     public static Properties load(){
              Properties p = new Properties();
          //skipped out exception handlin' for brevity
             p.load(new java.io.FileInputStream("test.prop"));
                return p;
}I am VERY new to all this, and I (obviously) havent figured out differences between servlets and beans etc... I am reseaching! But in the mean time... any ideas?!

public String packClass1(){          Properties props = packClass2.load();          return props.getProperty("aStringValue");     }
this function name is bit dodgy coz it has same name as the class name??????
its confusing

Similar Messages

  • Calling a TextFields get method from another class as a String

    This is my first post so be kind....
    I'm trying to create a login screen with Java Studio Creator. The Login.jsp has a Text Field for both the username and password. JSC automatically created get and set methods for these.
    public class Login extends AbstractPageBean
    private TextField usernameTF = new TextField();
    public TextField getUsernameTF() {
    return usernameTF;
    public void setUsernameTF(TextField tf) {
    this.usernameTF = tf;
    private PasswordField passwordTF = new PasswordField();
    public PasswordField getPasswordTF() {
    return passwordTF;
    public void setPasswordTF(PasswordField pf) {
    this.passwordTF = pf;
    My problem is in trying to call these methods from another class and return the value as a string.
    Any help on this matter would be greatly appreciated.

    the method returns the textfield, so you just need to get its text
    import java.awt.*;
    class Testing
      public Testing()
        Login login = new Login();
        System.out.println(login.getUsernameTF().getText());//<----
      public static void main(String[] args){new Testing();}
    class Login
    private TextField usernameTF = new TextField("Joe Blow");
    public TextField getUsernameTF() {
        return usernameTF;
    }

  • Calling a method from another class... that requires variables?

    I'm calling a method from another class to change the date (its a date object) in another class.
    I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
    My code is:
    public int changeDate()
         cycleDate.setDate();
    }I'm guessing I need to pass 3 parameters (day, month, year), but I'm not sure how! I have tried, but then I get errors such as ')' expected?
    Any ideas! :D

    f1d wrote:
    I'm calling a method from another class to change the date (its a date object) in another class.
    I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
    My code is:
    public int changeDate()
    cycleDate.setDate();
    }I'm guessing I need to pass 3 parameters (day, month, year), seems that way from the error you posted
    but I'm not sure how!
    setDate(16, 6, 2008);
    I have tried, but then I get errors such as ')' expected?
    Any ideas! :Dyou need to post your code if you're getting specific errors like that.
    but typically ')' expected means just that, you have too many or not enough parenthesis (or in the wrong place, etc.)
    i.e. syntax error

  • Calling results of a method from another class

    Very very new to Java, so apologies for the lack of basic knowledge. I am making a programme with 3 classes. One class gathers details about a module. Another about the results of this module (which requires some of the information inputted for the first class). For some reason I cannot find how to use results created in the first class in this second class. How do you call the results of a method from one class in another class?
    Thanks.

    Thank you.
    I am given the following information:
    '_ModuleRecord_
    This class is used to record information about a module taken by a single student. It has a constructor that takes three parameters:
    a Module,
    an int representing the examination mark achieved by a student, and
    an int representing the coursework mark achieved by a student.
    The class has another constructor that takes a single Module parameter.'
    and the code looks like this:
    public class ModuleRecord
      public ModuleRecord(Module m, int eMark, int cMark)
      public ModuleRecord(Module m)
      } I am a bit confused by the whole thing to be honest. I assume that the Module is referring to the other class, but how do I forge the link between them here?

  • Calling a class's method from another class

    Hi, i would like to know if it's possible to call a Class's method and get it's return from another Class. This first Class doesn't extend the second. I've got a Choice on this first class and depending on what is selected, i want to draw a image on the second class witch is a Panel extended. I put the control "if" on the paint() method of the second class witch is called from the first by the repaint() (first_class.repaint()) on itemStateChanged(). Thankx 4 your help. I'm stuck with this.This program is for my postgraduation final project and i'm very late....

    import java.awt.*;
    import java.sql.*;
    * This type was generated by a SmartGuide.
    class Test extends Frame {
         private java.awt.Panel ivjComboPane = null;
         private java.awt.Panel ivjContentsPane = null;
         IvjEventHandler ivjEventHandler = new IvjEventHandler();
         private Combobox ivjCombobox1 = null;
    class IvjEventHandler implements java.awt.event.WindowListener {
              public void windowActivated(java.awt.event.WindowEvent e) {};
              public void windowClosed(java.awt.event.WindowEvent e) {};
              public void windowClosing(java.awt.event.WindowEvent e) {
                   if (e.getSource() == Test.this)
                        connEtoC1(e);
              public void windowDeactivated(java.awt.event.WindowEvent e) {};
              public void windowDeiconified(java.awt.event.WindowEvent e) {};
              public void windowIconified(java.awt.event.WindowEvent e) {};
              public void windowOpened(java.awt.event.WindowEvent e) {};
         private Panel ivjPanel1 = null;
    * Combo constructor comment.
    public Test() {
         super();
         initialize();
    * Combo constructor comment.
    * @param title java.lang.String
    public Test(String title) {
         super(title);
    * Insert the method's description here.
    * Creation date: (11/16/2001 7:48:51 PM)
    * @param s java.lang.String
    public void conexao(String s) {
         try {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String url = "jdbc:oracle:thin:system/[email protected]:1521:puc";
              Connection db = DriverManager.getConnection(url);
              //String sql_str = "SELECT * FROM referencia";
              Statement sq_stmt = db.createStatement();
              ResultSet rs = sq_stmt.executeQuery(s);
              ivjCombobox1.addItem("");
              while (rs.next()) {
                   String dt = rs.getString(1);
                   ivjCombobox1.addItem(dt);
              db.close();
         } catch (SQLException e) {
              System.out.println("Erro sql" + e);
         } catch (ClassNotFoundException cnf) {
    * connEtoC1: (Combo.window.windowClosing(java.awt.event.WindowEvent) --> Combo.dispose()V)
    * @param arg1 java.awt.event.WindowEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.WindowEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.dispose();
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the Combobox1 property value.
    * @return Combobox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Combobox getCombobox1() {
         if (ivjCombobox1 == null) {
              try {
                   ivjCombobox1 = new Combobox();
                   ivjCombobox1.setName("Combobox1");
                   ivjCombobox1.setLocation(30, 30);
                   // user code begin {1}
                   this.conexao("select * from referencia");
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjCombobox1;
    * Return the ComboPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getComboPane() {
         if (ivjComboPane == null) {
              try {
                   ivjComboPane = new java.awt.Panel();
                   ivjComboPane.setName("ComboPane");
                   ivjComboPane.setLayout(null);
                   getComboPane().add(getCombobox1(), getCombobox1().getName());
                   getComboPane().add(getPanel1(), getPanel1().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjComboPane;
    * Return the ContentsPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getContentsPane() {
         if (ivjContentsPane == null) {
              try {
                   ivjContentsPane = new java.awt.Panel();
                   ivjContentsPane.setName("ContentsPane");
                   ivjContentsPane.setLayout(new java.awt.BorderLayout());
                   getContentsPane().add(getComboPane(), "Center");
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjContentsPane;
    * Return the Panel1 property value.
    * @return Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Panel getPanel1() {
         if (ivjPanel1 == null) {
              try {
                   ivjPanel1 = new Panel();
                   ivjPanel1.setName("Panel1");
                   ivjPanel1.setBackground(java.awt.SystemColor.scrollbar);
                   ivjPanel1.setBounds(24, 118, 244, 154);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjPanel1;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         this.addWindowListener(ivjEventHandler);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combo");
              setLayout(new java.awt.BorderLayout());
              setSize(460, 300);
              setTitle("Combo");
              add(getContentsPane(), "Center");
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:02:58 PM)
    * @return java.lang.String
    public String readCombo() {
         String dado = ivjCombobox1.getSelectedItem();
         return dado;
    * Starts the application.
    * @param args an array of command-line arguments
    public static void main(java.lang.String[] args) {
         try {
              /* Create the frame */
              Test aTest = new Test();
              /* Add a windowListener for the windowClosedEvent */
              aTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosed(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Test");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 1:59:15 PM)
    * @author:
    class Combobox extends java.awt.Choice {
         public java.lang.String dado;
    * Combobox constructor comment.
    public Combobox() {
         super();
         initialize();
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combobox");
              setSize(133, 23);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Combobox aCombobox;
              aCombobox = new Combobox();
              frame.add("Center", aCombobox);
              frame.setSize(aCombobox.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Combobox");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 2:16:11 PM)
    * @author:
    class Panel extends java.awt.Panel {
    * Panel constructor comment.
    public Panel() {
         super();
         initialize();
    * Panel constructor comment.
    * @param layout java.awt.LayoutManager
    public Panel(java.awt.LayoutManager layout) {
         super(layout);
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Panel");
              setLayout(null);
              setSize(260, 127);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Panel aPanel;
              aPanel = new Panel();
              frame.add("Center", aPanel);
              frame.setSize(aPanel.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of java.awt.Panel");
              exception.printStackTrace(System.out);
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:18:36 PM)
    public void paint(Graphics g) {
    /* Here's the error:
    C:\Test.java:389: non-static method readCombo() cannot be referenced from a static context
         System.out.println(Test.lerCombo());*/
         System.out.println(Test.readCombo());

  • Can't add list element when calling a method from another class

    I am trying to call a method in another class, which contains code listmodel.addElement("text"); to add an element into a list component made in that class.
    I've put in System.out.println("passed"); in the method just to make sure if the method was being called properly and it displays normally.
    I can change variables in the other class by calling the method with no problem. The only thing I can't do is get listmodel.addElement("text"); to add a new element in the list component by doing it this way.
    I've called that method within it's class and it added the element with no problem. Does Java have limitations about what kind of code it can run from other classes? And if that's the case I'd really like to know just why.

    There were no errors, just the element doesnt get added to the list by doing it this way
    class showpanel extends JPanel implements ActionListener, MouseMotionListener {
           framepanel fp = new framepanel();
           --omitted--
         public void actionPerformed(ActionEvent e){
                  if(e.getSource() == button1){
                       fp.addLayer();
    /*is in a different class file*/
    class framepanel extends JPanel implements ActionListener{
            --omitted--
         public void addLayer(){
              listmodel.addElement("Layer"+numLayer);
              numLayer++;
    }

  • Help on Calling a method from another class

    how can i call a method from another class.
    Class A has 3 methods
    i just want to call only one of these 3 methods into my another class.
    How can I do that.

    When i am trying this
    A a=new A;
    Its calling all the methods from class A. I just want
    to call a specfic method.How can it be done?When i am trying this
    A a=new A();
    Its calling all the methods from class A. I just want to call a specfic method.How can it be done?

  • Calling repaint method from another class

    My question in a very simple form :
    how do I call repaint mathod from another class.
    e.g: Let's say class "A.java" is a JFrame .
    Class "B.java" is a JPanel which is added to the JFrame above.
    Class "C.java" is a JDialog containing some JButtons.
    How do I call the repaint method from the class "C.java".
    Thank you in advance!!

    My question in a very simple form :
    how do I call repaint mathod from another class.
    e.g: Let's say class "A.java" is a JFrame .
    Class "B.java" is a JPanel which is added to the JFrame above.
    Class "C.java" is a JDialog containing some JButtons.
    How do I call the repaint method from the class "C.java".
    Thank you in advance!!

  • Is it possible to call methods from another class from within an abstract c

    Is it possible to call methods from another class from within an abstract class ?

    I found an example in teh JDK 131 JFC that may help you. I t is using swing interface and JTable
    If you can not use Swing, then you may want to do digging or try out with the idea presented here in example 3
    Notice that one should refine the abstract table model and you may want to create a method for something like
    public Object getValuesAtRow(int row) { return data[row;}
    to give the desired row and leave the method for
    getValuesAt alone for getting valued of particaular row and column.
    So Once you got the seelcted row index, idxSelctd, from your table
    you can get the row or set the row in your table model
    public TableExample3() {
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    // Take the dummy data from SwingSet.
    final String[] names = {"First Name", "Last Name", "Favorite Color",
    "Favorite Number", "Vegetarian"};
    final Object[][] data = {
         {"Mark", "Andrews", "Red", new Integer(2), new Boolean(true)},
         {"Tom", "Ball", "Blue", new Integer(99), new Boolean(false)},
         {"Alan", "Chung", "Green", new Integer(838), new Boolean(false)},
         {"Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true)},
         {"Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false)},
         {"Brian", "Gerhold", "Green", new Integer(0), new Boolean(false)},
         {"James", "Gosling", "Pink", new Integer(21), new Boolean(false)},
         {"David", "Karlton", "Red", new Integer(1), new Boolean(false)},
         {"Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false)},
         {"Peter", "Korn", "Purple", new Integer(12), new Boolean(false)},
         {"Phil", "Milne", "Purple", new Integer(3), new Boolean(false)},
         {"Dave", "Moore", "Green", new Integer(88), new Boolean(false)},
         {"Hans", "Muller", "Maroon", new Integer(5), new Boolean(false)},
         {"Rick", "Levenson", "Blue", new Integer(2), new Boolean(false)},
         {"Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false)},
         {"Chester", "Rose", "Black", new Integer(0), new Boolean(false)},
         {"Ray", "Ryan", "Gray", new Integer(77), new Boolean(false)},
         {"Georges", "Saab", "Red", new Integer(4), new Boolean(false)},
         {"Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false)},
         {"Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false)},
         {"Arnaud", "Weber", "Green", new Integer(44), new Boolean(false)}
    // Create a model of the data.
    TableModel dataModel = new AbstractTableModel() {
    // These methods always need to be implemented.
    public int getColumnCount() { return names.length; }
    public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {return data[row][col];}
    // The default implementations of these methods in
    // AbstractTableModel would work, but we can refine them.
    public String getColumnName(int column) {return names[column];}
    public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
    public boolean isCellEditable(int row, int col) {return (col==4);}
    public void setValueAt(Object aValue, int row, int column) {
    data[row][column] = aValue;
    };

  • How do you call a method from  another class without extending as a parent?

    How do you call a method from another class without extending it as a parent? Is this possible?

    Why don't you just create an instance of the class?
    Car c = new Car();
    c.drive("fast");The drive method is in the car class, but as long as the method is public, you can use it anywhere.
    Is that what you were asking or am I totally misunderstanding your question?
    Jen

  • How to call a method from another class

    I have a problem were i have to call a method from another class. What is the command line that i have to use. Thanks.

    Here's one I wipped up in 10 minutes... Cool!
    package forums;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import krc.utilz.io.Filez;
    import java.io.FileNotFoundException;
    class FileDisplayer extends JFrame
      private static final long serialVersionUID = 0L;
      FileDisplayer(String filename) {
        super(filename);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(600, 800);
        JTextArea text = new JTextArea();
        try {
          text.setText(Filez.read(filename));
        } catch (FileNotFoundException e) {
          text.setText(e.toString());
        this.add(text);
      public static void main(String args[]) {
        final String filename = (args.length>0 ? args[0] : "C:/Java/home/src/forums/FileDisplayer.java");
        try {
          java.awt.EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                new FileDisplayer(filename).setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
    Filez.read
       * reads the given file into one big string
       * @param String filename - the name of the file to read
       * @return the contents filename
      public static String read(String filename) throws FileNotFoundException {
        return Filez.read(new FileReader(filename));
       * Reads the contents of the given reader into one big string, and closes the reader.
       * @param java.io.Reader reader - a subclass of Reader to read from.
       * @return the whole contents of the given reader.
      public static String read(Reader in) {
        try {
          StringBuffer out = new StringBuffer();
          try {
            char[] bfr = new char[BFRSIZE];
            int n = 0;
            while( (n=in.read(bfr,0,BFRSIZE)) > 0 ) {
              out.append(bfr,0,n);
          } finally {
            if(in!=null)in.close();
          return out.toString();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
      }Edited by: corlettk on Dec 16, 2007 1:01 PM - dang [code [/tags][                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need to call a repaint from another class

    I need to call a repaint from another class, but since I can't make the paint() method a static one, it will not let me access the repaint method, any ideas? thanks guys
    Conor

    ok here's a very basic idea of whats goin on...
    <code>
    MainFrame class (in which the paint method resides)
    public void paint()
    // draw lines
    // opens an instance of the settings window
    void procSettings_actionPerformed(ActionEvent e)
    if(procRunning)
    procRunning = false;
    timer.stop();
    procPaused = true;
    procSettings s = new procSettings();
    s.setSize(370, 467);
    s.setLocationRelativeTo(null);
    s.setResizable(false);
    s.setVisible(true);
    ProcSettings class
    if(certain condition)
    // reset the lines of the graph
    // REPAINT <--- I want to know how to call this repaint, MainFrame.repaint() does not work
    thanks

  • Calling a class method from another class

    how can i call a method / function of one class without extending that class in another class.
    and one thing more i want want o check wether any Swing gui is open or closed.

    how can i call a method / function of one class without extending that class in another class.What?... Umm... You just call it... as in Foo.bar("doe ray me");
    i want want to check if any Swing gui is open or closed.Ummm, what? I don't understand the question. Do you mean find out if a particular java programming is allready running, of do you mean is the JPanel visible, or something else?

  • Problem getting arraylist from another class

    I am trying to call information about an arraylist from another class. I am using this code to call the size of an arraylist:
    import java.io.*;
    public class Test
        public static void main(String argv[]) throws IOException
    Echo03 thing = new Echo03();
    int y=thing.value();
    System.out.println(y);
    Echo03 thing2 = new Echo03();
    int x=thing2.percent.size();
    System.out.println(x);
    }from another file which starts like this:
    public class Echo03 extends DefaultHandler
    static ArrayList<String> percent = new ArrayList<String>();
    static ArrayList<String> text = new ArrayList<String>();
      int a;
    public int value(){
         return percent.size();
      public static void main(String argv[]) throws IOException
        {The second file is based on an example piece of code from the Java website. I havent posted the whole thing, but if it is relevant then please ask.
    Anyway when I run Echo03 by itself, the arraylist has a size of 2. But when I run it from the Test file, it says a size of 0. Is this because the data is not being transferred between the classes? Or is the Echo03 program not executing (and hence the arraylist is not filling up)?
    How can I fix this? I have tried 2 ways of calling the data (As seen in my Test file). Neither work.

    I didnt post the full bit of the code for the second one. Here it is:
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import java.util.ArrayList;
    import java.awt.*;
    import javax.swing.*;
    public class Echo03 extends DefaultHandler
    static ArrayList<String> percent = new ArrayList<String>();
    static ArrayList<String> text = new ArrayList<String>();
      int a;
      public static void main(String argv[]) throws IOException
            if (argv.length != 1) {
                System.err.println("Usage: cmd filename");
                System.exit(1);
            // Use an instance of ourselves as the SAX event handler
            DefaultHandler handler = new Echo03();
            // Use the default (non-validating) parser
            SAXParserFactory factory = SAXParserFactory.newInstance();
            try {
                // Set up output stream
       out = new OutputStreamWriter(System.out, "UTF8");
                // Parse the input
                SAXParser saxParser = factory.newSAXParser();
                saxParser.parse( new File(argv[0]), handler);
    for (int b=0; b<percent.size();b++){
         System.out.println(percent.get(b+1));
            } catch (Throwable t) {
            System.exit(0);
        static private Writer  out;
        public void startElement(String namespaceURI,
                                 String lName, // local name
                                 String qName, // qualified name
                                 Attributes attrs)
        throws SAXException
            if (attrs != null) {
    StringBuffer sb = new StringBuffer (250);        
    for (int i = 0; i < attrs.getLength(); i++) {
                    nl();
                    emit(attrs.getValue(i));
              sb.append (attrs.getValue(i));
    String sf = sb.toString ();
    percent.add(sf);
    System.out.println(" String: "+sf); a++;
        public void characters(char buf[], int offset, int len)
        throws SAXException
             emit(" ");
            String s = new String(buf, offset, len);
            if (!s.trim().equals("")) {text.add(s); emit(s);}
    //===========================================================
        // Utility Methods ...
        //===========================================================
        // Wrap I/O exceptions in SAX exceptions, to
        // suit handler signature requirements
        private void emit(String s)
        throws SAXException
            try {
                out.write(s);
                out.flush();
            } catch (IOException e) {
                throw new SAXException("I/O error", e);
        // Start a new line
        private void nl()
        throws SAXException
            String lineEnd =  System.getProperty("line.separator");
            try {
                out.write(lineEnd);
            } catch (IOException e) {
                throw new SAXException("I/O error", e);
    }

  • Getting a variable value from another class

    Is there any way to get the value of a variable from another class? I have a file that calls another that does some checking then gives a true or false. The place the checking is done is inside an ActionListener I want to use that value in the file that calls the second. Any help would be great.

    in 'another class', implement a method,
    public boolean isCheckedOutOK( Object obj )
    do the comparison in that method (use a suitable argument)

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

Maybe you are looking for