SETTING FIELD IN ANOTHER CLASS

I have 3 classes: class1 extends Jpanel, class2 extends Jpanel, class3 extends JFrame. What I am trying to do is set the textfields in class1 from class2 according to user input: user enters an ID and presses a button (in another frame: class4) and data relating to that ID e.g. name, number... is retrieved from the server and then the fields in class1 are set to these values from class2. I have the following coding
class 1
JTextfield nameField = new JTextField()
class1 constructor(
panel.add(nameField)
class2
class1 c1 = new class1()
c1.clTextField.setText(...)
panel.add(c1)
class 3 constructor
panel.add(class2Object);
when the user enters an ID (in class4)and presses enter the correct data is displayed. However when I close down the class3 frame and enter another ID the frame gets displayed but all the textFields have gone missing????????
p.s. what is the difference between creating a new object and invoking it on the textfield e.g.(in class1)
class2 c2 = new class2
c2.textFieldInClass2
and stating the textfield as a static string in class2 and then just invoking class2Name on it in class1 e.g.
class2Name.textfield

import java.util.Date;
public class Time {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss")
Date utilDate;
java.sql.TimeStamp sqlDate;
String stringDate;
public Time(){
utilDate = new Date();
stringDate = formatter.format(utilDate)
sqlDate = new java.sql.TimeStamp(utilDate.getTime)
stringDate can be displayed in frame. sqlDate is entered into the server. you can have the simpledateformat according to the format date you require

Similar Messages

  • Set fields of derived class in base class constructor via reflection?

    Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
    Many thanks for your feedback!
    Norman
    public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
    abstract static class A {
        A() {
            try {
                getClass().getDeclaredField("x").setInt(this, 42);
            } catch (Exception e) {
                throw new RuntimeException(e);
    static class B extends A {
        int x;
        B() {
        B(int x) {
            this.x = x;
    public void testThatItWorks() {
        assertEquals(42, new B().x);
        assertEquals(99, new B(99).x);
    }

    why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
    Framework:
    public abstract class Operator {
        public abstract void initialize();
    }Plug-In:
    public class SomeOperator extends Operator {
        @Parameter(defaultValue="42", interval="[0,100)")
        double threshold;
        @Parameter(defaultValue="C", valueSet="A,B,C")
        String mode;
        public void setThreshold(double threshold) {this.threshold = threshold;}
        public void setMode(String mode) {this.mode = mode;}
        // called by the framework after default values have been set
        public void initialize() {
    }On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance.

  • SETTING TEXTFIELD IN ANOTHER CLASS

    I have 2 classes: class1, class2. In class2 I have a textfield. In class1 I am trying to set the textfield in class2 with text: class2.textField_name.setText(string). This does not work - null pointer exception???

    Is this what you want???.
    import javax.swing.*;
    import java.awt.*;
    public class class1 extends JFrame {
       //Class1;
       class2 ji = new class2();//class2
      public junk() {
        super();
        setSize(400,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container pane = getContentPane();
        pane.setLayout(new FlowLayout());
        String hello = "hello";
        ji.field.setText(hello);
        pane.add(ji.field);
        setVisible(true);
      public static void main(String[] args) {
        class1 j = new class1();
    class class2 {
    //class2
    JTextField field = new JTextField(20);
    public class2() {}
    }

  • Creating a Set  containing instances of another Class, which type?

    Hi All,
    I'm stuck trying to create a set which contains instances of another Class.
    When I created my instance method, it takes an argument which is the instance of another Class.
    It errors as I've used the Class as the type rather than String> or Integer.
    Can someone point my in the right direction?
    WebPageData wpd1 = new WebPageData("this is a sentence for a test", "www.test.com");
    WebPageData wpd2 = new WebPageData("this sentence is shorter", "www.short.com");
    WebPageData wpd3 = new WebPageData("this is very short", "www.very.com");
    Finder f1 = new Finder();
    f1.addsite(wpd1);
    f1.addsite(wpd2);
    f1.addsite(wpd3);
    f1.searchFor("a sentence test");
    Edited by: geedoubleu on Mar 16, 2008 9:03 AM

    The error message is "Semantic error: line 5. Message addsite( WebPageData ) not understood by class'Finder'"
    * Adds the argument of WebPageData instances to to a collection scannedSites.
    public void addSite(WebPageData theWebPage)
    this.scannedSites.add(theWebPage);
    }

  • Is it possible to set a field in another item/list in a workflow?

    I've created a list workflow to add a task after a new client is added to my client list. I am trying to create a pre-determined due date, so that the workflow works out the due date so that it's 2 days from today. So I decided to use the 'Add time to date'
    function and selected two days. I then figured that I could add these 2 days to the due date field in the task list by using the set field in current item to the 'add time to date' variable. However as this is a list workflow using my 'Cllients list' and not
    my events list when I select 'field' in the hope that due date from my events list pops up to select, obviously only the fields in my clients list come up. Therefore is there a way to set the field in another list to a value?
    Thanks in advance!

    Hi,
    According to your post, my understanding is that you want to make the Workflow Tasks work out with a pre-determined due date that it's 2 days from today in your client list workflow.
    I recommend that you can create this client list workflow as below in your environment.
    Then, you can go to “Start Options” to check “Start workflow automatically when an item is created”, publish this workflow and test if it works.
    When an new item is added in the client list, its corresponding Workflow Task is shown as below:
    Best Regards,
    Yumi Fu

  • 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;
    }

  • Stop a method from executing until another class does its bit

    Hi all,
    For my app I have a login screen where to get login success the user must first register. I therefore have two class LoginDialog and Register which is a dialog.
    In LoginDialog if the user clicks on Register it brings up a new instance of the Register dialog but continues to process the calling method (which happens to return to another class processing the login). What I require is that when I create a new Register object, the creating method does nothing until the Registration form is completed. I'm not at all au fait with threads so was wondering if there is an easy way to do it.
    I have thought of passing the LoginDialog as an argument in the Register constructor and having an empty while loop running in the invoking method (i.e. while (false) do nothing) and creating public access to that boolean variable so that at completion of the registration it sets the boolean variable to true in LoginDialog so it should break out of the while loop and continue. Is that a satisfactory way of pausing and restarting a method?
    Cheers,
    Chris

    Hi,
    I have a MainFrame class which calls processLogin which creates a new LoginDialog which houses the Register button. When I click on the register button it opens a new Registration screen but LoginDialog returns to MainFrame in the background and says that no user has logged in. What I require is that when the Register object is created after clicking the Register button that LoginDialog waits until the Registration is complete.
    Maybie the code will help (sorry if it is a bit lengthy).
    Snippet of LoginDialog
    public void actionPerformed(ActionEvent event)
            if(event.getSource() == ok) {
                 _username = user.getText();
                   _password = new String(password.getPassword());
                   _server = server.getText();
                   //ensure port number is an integer
                   try{
                        _port = Integer.parseInt(port.getText());
                   catch(NumberFormatException e){
                        JOptionPane.showMessageDialog(this,
                        "Please use an integer value only for the port number","Error",
                        JOptionPane.WARNING_MESSAGE);
                   //checks username and password length
                   if((_username.length()==0) || (_password.length() == 0)){
                        JOptionPane.showMessageDialog(this,
                             "Please enter a valid username and password","Error",
                                  JOptionPane.WARNING_MESSAGE);
                        return;
                   //checks server length
                   if(_server.length()== 0){
                        JOptionPane.showMessageDialog(this,
                             "Invalid server host","Error",
                                  JOptionPane.WARNING_MESSAGE);
                        return;
                   try{
                        db = new DatabaseConnection();
                        boolean exists = db.doesUserExist(_username, _password);
                        db.close();
                        if(exists){
                             //System.out.println("User exists on database");
                             this.dispose(); //get rid of login screen now user is confirmed
                        if(!exists){
                                  _username = null;
                                  _password = null;
                                  this.dispose();
                   catch(java.sql.SQLException e){
                        JOptionPane.showMessageDialog(this,
                             "Unable to connect to database. Please try again.","Error",
                                  JOptionPane.WARNING_MESSAGE);
              else if(event.getSource() == cancel) {
                   //NOTHING
              else if(event.getSource() == register){
                   Register register = new Register();
                   //while (processRegistration){
              this.setVisible(false);
         }and Register
    //import classes
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JFrame implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFirstName;
         JLabel lblLastName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblEmail;
         JLabel lblSex;
         String userName;
         char[] userPwd;
         char[] cnfPwd;
         String strUserPwd;
         String strCnfUserPwd;
         String firstName;
         String lastName;
         String age;
         String empid;
         String email;
         String sexStr;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox comboSex;
         JTextField txtUserName;
         JPasswordField txtUserPwd;
         JPasswordField txtCnfUserPwd;
         JTextField txtFirstName;
         JTextField txtLastName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         DatabaseConnection db;
         boolean exists, entrySuccess;
         public Register() {
              this.setTitle("Register");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Registration Info");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUserPwd = new JPasswordField(15);
              panel.add(txtUserPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUserPwd=new JPasswordField(15);
              panel.add(txtCnfUserPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFirstName=new JLabel("First Name");
              panel.add(lblFirstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFirstName=new JTextField(15);
              panel.add(txtFirstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLastName=new JLabel("Last Name");
              panel.add(lblLastName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLastName=new JTextField(15);
              panel.add(txtLastName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sexArr = {"Male", "Female"};
              comboSex = new JComboBox(sexArr);
              comboSex.setSelectedIndex(0);
              panel.add(comboSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setVisible(true);
              setSize(450,400);
         }//end or Register()
         public void actionPerformed(ActionEvent ae) {
              Object o = ae.getSource(); //get the source of the event
              if(o == btnCancel)
                   this.dispose();
              if(o == btnSubmit){
                   userName = txtUserName.getText();
                   userPwd = txtUserPwd.getPassword();
                   strUserPwd = new String(userPwd);
                   cnfPwd = txtCnfUserPwd.getPassword();
                   strCnfUserPwd = new String(cnfPwd);
                   firstName = txtFirstName.getText();
                   lastName = txtLastName.getText();
                   age = txtAge.getText();
                   empid = txtEmpId.getText();
                   email = txtEmail.getText();
                   sexStr = (String)comboSex.getItemAt(0);
                   db = new DatabaseConnection();
                   //Now check to see if username and password combination have been
                   //taken
                   try{
                        exists = db.doesUserExist(userName.trim(), strUserPwd.trim());
                   catch (java.sql.SQLException e){
                        System.out.println(e);
                   //Checks that each field has been filled in.
                   if(userName.length() == 0 ||  strUserPwd.length() == 0 ||
                   strCnfUserPwd.length() == 0 || firstName.length() == 0 ||
                   lastName.length() == 0 || age.length() == 0 || empid.length() == 0
                   || email.length() == 0){
                        JOptionPane.showMessageDialog(this,
                        "One or more entry has not been filled in. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);     
                   //Ensures that passwords match
                   if(!strUserPwd.equals(strCnfUserPwd)){
                        JOptionPane.showMessageDialog(this,
                        "Passwords do not match. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);
                   if(exists){
                        JOptionPane.showMessageDialog(this,
                        "Username and password combination already exists. Please go back and try again",
                        "Message", JOptionPane.ERROR_MESSAGE);
                   if(!exists) {
                        String userDetails = (userName.trim() + " " + strUserPwd.trim()
                        + " "  + firstName.trim() + " "
                        + lastName.trim() + " " + age.trim() + " " + empid.trim() + " "
                        + email.trim() + " " + sexStr.trim());
                        //System.out.println(userDetails);
                        //Try to connect to the database and insert the user details.
                        //If successful then user will be alerted and the registration page
                        //should be disposed automatically. If for some reason the insert
                        //was not successful then user is prompted to try again.
                        try{
                             entrySuccess = db.registerUser(userDetails);
                             if(entrySuccess){
                                  JOptionPane.showMessageDialog(this,
                                  "Congratulations, you have successfully registered for the Instant Messenger service!",
                                  "Message", JOptionPane.INFORMATION_MESSAGE);
                                  this.dispose();     
                             if(!entrySuccess){
                                  JOptionPane.showMessageDialog(this,
                                  "There was a problem entering your details. Please try again.",
                                  "Message", JOptionPane.ERROR_MESSAGE);
                        catch(java.sql.SQLException e){
              }//end of else
              db.close();
         }//end of actionPerformed()
    }//end of classCheers,
    Chris

  • How to call methods defined in another class ? is it possible?

    Hi all,
    I am new to using JNI, was wondering if this is possible and how I might be able to do this. I'm trying to call some set/get functions defined in a class that is not part of the class where I have my native code defined and called...
    Let me explain a bit, I have a class JobElement (singular Job) that stores all the data associated with a Job, such as job name, job id, etc.
    Another class JobsElement (plural Jobs) contains all the Jobs that are currently running.
    The code is set up something like this...
    class JobElement {
         String jobID;
         String jobName;
         public void setJobId(String newJobID) { jobID = newJobID; }
         public void setJobName(String newJobName) { jobName = newJobName; }
    class JobsElement {
         Date timeDateStamp;
         JobElement job;
    class AppRoot {
         JobsElement allJobs = null;
         JobElement _currentJob = null;
         public native getAllJobs();
    }In my native method, getAllJobs(), I essentially want to call the set functions that are defined for JobElement when filling in the information of the Job. (then finally add the JobElement to the JobsElement list)
    In summary, I basically want to know if it's possible to call the equivilent of this java code from the native code??
         _currentJob.setJobName(newJob)
    In the native code I tried to find the setJobID method but got a NoSuchMethodError. (which is what I expected)
    Thanks in advance.

    Hi,
    In your getAllJobs(), the JNI Equiv would be JNIEnv_ClassName_getAllJobs(JNIEnv** anEnv, jobject jAppRootobj)
    Since you are calling the AppRoot object's method, the jobj in the native method call will be jAppRootobj-AppRoot's instance.
    What you can do is
    Get the field id of _currentJob.
    Get the <jobject-value of currentJob> of JobElement i.e. currentJob.
    Then get the method ids of setJobID and setJobName.
    Call these non-static methods on <jobject-value of _currentJob> to set the values.
    I hope I made a try to help you. Please correct me if I am wrong.

  • Passing several fields to various classes and methods?

    Passing several fields to various classes and methods?
    Hi there.
    I have an application that allows a user to define a configuration and save it.
    The user can edit an existing configuration, add a new one, or delete an existing one.
    Once a configuration is selected the user then starts an application that relies on the selected configuration data. Each configuration holds around 60 fields.
    The configuration information is mixed between integers and strings. Around 25 are hidden from the user, and 35 can be modified by the user. The number of fields is not a fixed amount. For example the configuration contains an email-to list and the list for one configuration can have 1 address, and for another could have 10 addresses.
    I have decided to redesign using the Model View Controller concept. I am creating the model to hold the configuration information. I am trying to decide if I should have single get and set methods for each field or if I should create some kind of Object that holds all of one configuration and pass this back.
    The configuration that is selected does not really require the fields to be sorted in any particular order.
    What would you suggest is a good structure to use to pass the configuration information around?
    I have been using the Properties class with an .ini file that can be read and updated.
    Is this efficient? Doesn�t this impact the speed of processing if I have to read a file every time I want to determine what a particular configuration field is?
    Could I just create a class that reads the profile, stores the configuration information for one specific selected config, and then passes the class back to the calling procedure. This would consolidate all the file reading into one class and after that it is held in memory.
    Would it be better to read the configuration information into a collection of some sort , or a vector and pass this back to calling routine?
    public class MyModel {
         //read information to load the field of
         Private MyConfig selectedConfiguration = new MyConfig;
            Private int     selectedField1 = 0;
            /** Constructor */
         MyModel() {
              // open profile, read profile fields the
              selectedConfiguration.field1 = profileField1;  //assume this is 5
                    selectedConfiguration.field2 = profileField2;  //assume this is 10
              selectedConfiguration.field3 = �Test�;
                    field4ArrayOfStrings  = new String[selectedConfiguration.field1 ]
                                                                 [selectedConfiguration.field2];
              selectedConfiguration.field3ArrayOfStrings [0][0] = �First String�
         public class MyConfig(){
         int field1;
         int field2;
         String field3;
         String[][] field4ArrayOfStrings;
         // more stuff here �.
         // selectedConfiguration
         public void setConfiguration(MyConfig p_config) {
              String selectedConfiguration = p_config;
         public String getConfiguration() {
              return selectedConfiguration;
         //The other option is to have get and set for each field
         public void setField1(int field1) {
              String selectedField1 = field1;
         public String getField1() {
              return selectedField1;
    }Slight correction: reference to field3ArrayOfStrings changed to field4ArrayOfStrings.
    Message was edited by:
    tkman

    johndjr wrote:
    I think the term you want is "cross reference".
    Back in the olden days of green bar paper listings and linker maps they used to be quite common. At least they were where I worked.
    I have not seen any cross references in some time.
    java.lang.Object grr_argh_why_I_oughta_you_dirty_rat; // a pretty cross reference

  • Getting values from a JTextField on a JPanel in another class

    I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
      int val;
      public TextFieldChooser(String str){
        val = 0;     
        setLayout(new FlowLayout());
        add(new JLabel(str));
        JTextField txtf = new JTextField(5);
        txtf.addActionListener(new TextFieldListener());
        add(txtf);
      }//end constructor     
      private class TextFieldListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
           val = Integer.parseInt(e.getActionCommand());
      }//end text field listener
      public int getValue(){
        return val;     
    }//class

    The problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
    I have created a class which extends a JPanel and
    added a JTextField to it, which has an
    addActionListener for getting the values typed in the
    JTextField. I want to use the class created in
    another class and retrieve the values typed in the
    JTextField, so how do i go about that? I have the
    class created below so the problem is how to retrieve
    content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
    int val;
    public TextFieldChooser(String str){
    val = 0;
    setLayout(new FlowLayout());
    add(new JLabel(str));
    JTextField txtf = new JTextField(5);
    txtf.addActionListener(new TextFieldListener());
    add(txtf);
    }//end constructor
    private class TextFieldListener implements
    s ActionListener{
    public void actionPerformed(ActionEvent e) {
    val = Integer.parseInt(e.getActionCommand());
    }//end text field listener
    public int getValue(){
    return val;
    }//class

  • 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);
    }

  • Easy question: Give access to a class in another class.

    Stupid title, but dont know how to express myself :P Sorry for that.
    To the problem. Never had this problem before, and I know its a really easy solution to this.
    I have my Main class, which creates a MyView class. Inside this class, I make to new classes(or instances of classes i've already made), MyPanel and MyToolsPanel. Now I want to add buttons inside the MyToolsPanel class, and add actionlisteners to these buttons inside MyPanel.
    What I'v always done to grant access to MyToolsPanel inside of MyTools, is to simply add a
    //this is the MyPanel class
    MyToolsPanel mtp;
    public void setMtp(MyToolsPanel mtp){
    this.mtp = mtp;
    }and then in the MyView class which create these to classes, I put a command: mp.setMtp(mtp);
    When I run this it doesnt work.. Why? Should be easy to solve, since it obviously is a stupid problem that I just dont see. :P Feeling kind of stupid to ask this question, but this is how it is...
    EDIT: I might have to implement actionListener inside the MyToolsPanel class?
    Edited by: Stianbl on Sep 28, 2008 4:59 PM

    one way:
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    * Subclasses JPanel, can send text out via the getText() method
    * can hook into button press via addActionListener
    * @author Pete
    public class PanelCommSender extends JPanel
      private JTextField sendingField = new JTextField(12);
      private JButton sendButton = new JButton("Send");
      public PanelCommSender()
        add(sendingField);
        add(sendButton);
      public void addActionListener(ActionListener al)
        // attach this listener to the button
        sendButton.addActionListener(al);
       * call this to get the text currently in the textfield
       * @return String text
      public String getText()
        return sendingField.getText();
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    * Subclasses JPanel, receives text from another class
    * @author Pete
    public class PanelCommReceiver extends JPanel
      private JTextField showResultsField = new JTextField(12);
      public PanelCommReceiver()
        showResultsField.setEditable(false);
        add(new JLabel("Results from other panel: "));
        add(showResultsField);
       * call this to set text of textField
       * @param text
      public void setText(String text)
        showResultsField.setText(text);
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    public class PanelCommControl
      private static void createAndShowUI()
        // create new instances of the receiving and sending panels:
        final PanelCommReceiver receivePanel = new PanelCommReceiver();
        final PanelCommSender sendPanel = new PanelCommSender();
        // let the communicate w/ each other
        sendPanel.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            receivePanel.setText(sendPanel.getText());
        // place the receiving JPanel into a JFrame
        JFrame frame = new JFrame("Receiving Panel");
        frame.getContentPane().add(receivePanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(300, 300)); // make it bigger so it can be seen
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        // place the sending JPanel into a JDialog
        JDialog dialog = new JDialog(frame, "Sending Panel", false);
        dialog.getContentPane().add(sendPanel);
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            // run the whole show in a thread-safe manner
            createAndShowUI();
    }

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • Using an int from one class in another class

    I am a student writing a java program on renewable energy. Simply I have a power output which is a variable called PowerOutPut. declared as (public int PowerOutPut) I have another class which is a graphics class where I display the variable PowerOutPut on a graph, but i dont know how to call this variable in my graphics class.
    if anyone can help, I would be very grateful.
    Chris

    But bear in mind that it is good practice to declare your variables private (unless you need otherwise) and to provide get and set methods to access and change them.
    private int myVariable = 0;
    public int getMyVariable(){
        return myVariable;
    public void setMyVariable(int newValue){
        myVariable = newValue;
    }Also, class names should start with upper case and variables should start with lower case.
    Good luck.

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

Maybe you are looking for

  • How can I use my iPod touch as a camera to broadcast to twitch?

    I am really having fun doing twitch.tv broadcasts, but is there any way i can use my iPod touch 5th gen as a camera, so i can aim it at something and thats what my viewers see? I broadcast using OBS (Open Broadcasting Software) on my windows (Yea, wi

  • How to set textField.Background alpha?

    Is there a way to set the alpha of textField.Background to say 30? I already have the following: txtField.background = true; txtField.backgroundColor = 0xEE9A00; All I need is a way to set the background so that it's not 100% opaque?

  • Microsoft enterprice library logging in ssis

    Hi All, Could anybody help me and let me know if we can make use of microsoft enterprice library logging feature in SSIS. I have to create a POC and submitt it to client if it is worth and possible. I know we can handle ssis logging in no. of ways bu

  • Error no WBS billing element found while substituting WBS element 00050923

    Hi, Please give me some quick solution to overcome this error in my IDES. I have seen the note, sap help and othe rsuggession . could not get rid of this error. Quick response is requested.The earlier thread was also unanswered. Zinni

  • Hardware isn't recognized

    Trying to load a new nano. Updated with iTunes 7 but when I connect the nano to the computer I get a message that the USB device has not passed Windows Logo testing to be compatible with XP. I select continue anyway and then I receive a message an er