Java How to Use a Variable From Another Class

Member Avatar

Please help me =(

I'm not native english speaker, therefore some things might be not clear here

I have 2 separate files: Main.java and Open.java

inside main.java there is a GUI and it has a JTextArea) where i want to show text (variable) called from open.java

in Main.java i have (i took out only important codes, real one is much longer):

                      //textarea final JTextArea textarea = new JTextArea(); textarea.setEditable(false); JScrollPane textScrollPane = new JScrollPane(textarea); textScrollPane.setPreferredSize(new Dimension(800, 100));  //open function  private void actionPerformedOnOpen(ActionEvent evt, JTextArea textarea) { javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();         chooser.addChoosableFileFilter(new FileFilter());         int option = chooser.showOpenDialog(this);         if (option == javax.swing.JFileChooser.APPROVE_OPTION) {  String text = new String(); //text = (String)(Open.get(parsedFile));              java.io.File file = chooser.getSelectedFile();             if (file == null) return;             Open readPDBFile = new Open(file.getAbsolutePath());              textarea.append("Opening: " + file.getName());              textarea.setText("Testing..."+text);           }     }                    

in Open.java i have a variable which contains some text. i want it to be shown inside the textarea in Main.java like textarea.setText("Testing..."+text); and call variable from Open.java instead of text

i looked all over internet, but couldnt find it helpful.

please please please help meee...

Thank you very much ^^

  • 7 Contributors
  • forum 10 Replies
  • 3,034 Views
  • 5 Months Discussion Span
  • comment Latest Post Latest Post by adams161

Recommended Answers

How have you declared your variables in what context, by this i mean either declared as local, instance or class etc?

See this website to understand what i mean by this: http://www.leepoint.net/notes-java/data/variables/45local-inst-class.html

Would need to see more code of your variables and their location more specifically, …

Jump to Post

if you have

                        class mainclass{  stuff mystuff; open myopen;  mainclass() { mystuff = new stuff(); myopen = new open(mystuff);// we pass a copy of mystuff, its an object so passed by reference.  } class stuff {  int a; int b; int c; stuff() { a=b=c=5; } }//end …                      

Jump to Post

Please help me =(

I'm not native english speaker, therefore some things might be not clear here

I have 2 separate files: Main.java and Open.java

inside main.java there is a GUI and it has a JTextArea) where i want to show text (variable) called from open.java

in Main.java i …

Jump to Post

All 10 Replies

Member Avatar

How have you declared your variables in what context, by this i mean either declared as local, instance or class etc?

See this website to understand what i mean by this: http://www.leepoint.net/notes-java/data/variables/45local-inst-class.html

Would need to see more code of your variables and their location more specifically, since the solution to your problem depends on this.


Kind regards.

Edited by kevndcks because: n/a

Member Avatar

Oh yes, this is what i have in Open.java :

                          package pdbviewer;  import org.biojava.bio.structure.io.PDBFileReader; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.GroupIterator; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.AminoAcid; import org.biojava.bio.structure.Chain; import java.util.Map;  import javax.swing.*;  /**  *  * @author ginger  */ public class Open extends javax.swing.JTextArea{       public Open(String filename) {     PDBFileReader pdbreader = new PDBFileReader();     pdbreader.setParseSecStruc(true);   pdbreader.setAlignSeqRes(true);   pdbreader.setParseCAOnly(false);   pdbreader.setAutoFetch(false);     try{      Structure struc = pdbreader.getStructure(filename); //i want this       System.out.println(struc);       GroupIterator gi = new GroupIterator(struc);       while (gi.hasNext()){             Group g = (Group) gi.next();//this             if ( g instanceof AminoAcid ){                AminoAcid aa = (AminoAcid)g;                Map sec = aa.getSecStruc();//and this to be viewed in the textarea in Main.java                Chain  c = g.getParent();                System.out.println(c.getName() + " " + g + " " + sec);                      }       }   } catch (Exception e) {      e.printStackTrace();  }        } }                        

There are some texts are being printed out in console, i want them to be called into the textarea in Main.java

Thanks a lot ^^

Member Avatar

if you have

                          class mainclass{  stuff mystuff; open myopen;  mainclass() { mystuff = new stuff(); myopen = new open(mystuff);// we pass a copy of mystuff, its an object so passed by reference.  } class stuff {  int a; int b; int c; stuff() { a=b=c=5; } }//end stuff  } // end main class   and open is  class open { stuff mystuff;  open() { }  open(stuff mystuffpassed) { mystuff = mystuffpassed;  // mystuff in open is now linked to stuff } }// end class                        

it has to do with how stuff is passed.

i have a variable like int i=1;

and i pass mystuff(i);

changes to i wont duplicate between teh copies. its pass by value.

pass an object, and you pass by reference so if in one class i do
mystuff.a=6; both copies see this. they share.

Mike

Edited by adams161 because: n/a

Member Avatar

You can use Observer-Pattern, i made a quite simple sample which will printing current datetime to console and within relatively same time append same current datetime to an JTextArea, scheduled every 5 seconds, infinitely (till program closed).

                          /*  * MyFrame.java  *  * Created on Jan 7, 2010, 10:40:13 AM  */ import java.util.Observable; import java.util.Observer;  /**  *  * @author jaka  */ public class MyFrame extends javax.swing.JFrame implements Observer {      /** Creates new form MyFrame */     public MyFrame() {         initComponents();     }      /** This method is called from within the constructor to      * initialize the form.      * WARNING: Do NOT modify this code. The content of this method is      * always regenerated by the Form Editor.      */     @SuppressWarnings("unchecked")     // <editor-fold defaultstate="collapsed" desc="Generated Code">     private void initComponents() {          jLabel1 = new javax.swing.JLabel();         jScrollPane1 = new javax.swing.JScrollPane();         outputArea = new javax.swing.JTextArea();          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);          jLabel1.setText(org.openide.util.NbBundle.getMessage(MyFrame.class, "MyFrame.jLabel1.text")); // NOI18N          outputArea.setColumns(20);         outputArea.setRows(5);         jScrollPane1.setViewportView(outputArea);          javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());         getContentPane().setLayout(layout);         layout.setHorizontalGroup(             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGroup(layout.createSequentialGroup()                 .addContainerGap()                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                     .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)                     .addComponent(jLabel1))                 .addContainerGap())         );         layout.setVerticalGroup(             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)             .addGroup(layout.createSequentialGroup()                 .addContainerGap()                 .addComponent(jLabel1)                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)                 .addContainerGap())         );          pack();     }// </editor-fold>      public void update(Observable o, Object obj) {         String text = (String) obj;         outputArea.append(text);     }      /**     * @param args the command line arguments     */     public static void main(String args[]) {         java.awt.EventQueue.invokeLater(new Runnable() {             public void run() {                 new MyFrame().setVisible(true);             }         });     }      // Variables declaration - do not modify     private javax.swing.JLabel jLabel1;     private javax.swing.JScrollPane jScrollPane1;     private javax.swing.JTextArea outputArea;     // End of variables declaration   }                        

and the Main.java

                          import java.util.Calendar; import java.util.Date; import java.util.Observable; import java.util.Timer; import java.util.TimerTask;  /**  *  * @author jaka  */ public class Main extends Observable {      private Timer timer = new Timer();     private String currentTimeString = null;      public Main() {     }      public void startInfiniteTimer() {         TimerTask task = new TimerTask() {              @Override             public void run() {                 Date current = Calendar.getInstance().getTime();                 currentTimeString = "Current date: " + current.toString() + "\n";                 System.out.print(currentTimeString);                 setChanged();                 notifyObservers(currentTimeString);             }         };         timer.schedule(task, 0, 5000); //every 5 seconds     }      public static void main(String[] args) {         java.awt.EventQueue.invokeLater(new Runnable() {             public void run() {                 Main main = new Main();                 MyFrame frame = new MyFrame();                 frame.setVisible(true);                 main.addObserver(frame);                 main.startInfiniteTimer();             }         });     }  }                        

See how easy it is, just make the Class/Object you want to observe extends Observable, and another Class as it's observer.

p.s:
Sorry it the MyFrame.java is too long, i am using Netbeans GUI builder to build the frame.

Member Avatar

Please help me =(

I'm not native english speaker, therefore some things might be not clear here

I have 2 separate files: Main.java and Open.java

inside main.java there is a GUI and it has a JTextArea) where i want to show text (variable) called from open.java

in Main.java i have (i took out only important codes, real one is much longer):

                            //textarea final JTextArea textarea = new JTextArea(); textarea.setEditable(false); JScrollPane textScrollPane = new JScrollPane(textarea); textScrollPane.setPreferredSize(new Dimension(800, 100));  //open function  private void actionPerformedOnOpen(ActionEvent evt, JTextArea textarea) { javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();         chooser.addChoosableFileFilter(new FileFilter());         int option = chooser.showOpenDialog(this);         if (option == javax.swing.JFileChooser.APPROVE_OPTION) {  String text = new String(); //text = (String)(Open.get(parsedFile));              java.io.File file = chooser.getSelectedFile();             if (file == null) return;             Open readPDBFile = new Open(file.getAbsolutePath());              textarea.append("Opening: " + file.getName());              textarea.setText("Testing..."+text);           }     }                          

in Open.java i have a variable which contains some text. i want it to be shown inside the textarea in Main.java like textarea.setText("Testing..."+text); and call variable from Open.java instead of text

i looked all over internet, but couldnt find it helpful.

please please please help meee...

Thank you very much ^^

hi i have gone through u r code its good but not the best u can declare the variable in main instead of another n use it as an global and more often access specifiers are differently used in this n if u want u can look at dynamic billboard

Member Avatar

Thanks everyone, i figured it out thanks to your help ^^

Member Avatar

glad we were of help. maybe mark it as solved?

Mike

Member Avatar

hi i have gone through u r code its good but not the best u can declare the variable in main instead of another n use it as an global and more often access specifiers are differently used in this n if u want u can look at dynamic billboard

No, just no. Suggesting the use of a "global variable" from main.java is probably the worst way possible to go about it. And you need to read this as well: http://www.daniweb.com/forums/faq.php?faq=daniweb_policies#faq_keep_it_clean

All that is needed is a public method on the "open" class that returns the data you want to display: open.getTheText()

Member Avatar

hi please say the output for this pseudo
employee
{
int empid;
}
class A
{
public static void main(String args[])
{
Hashset s=new Hashset();
for(int i=0;i<10;i++)
{
for(intj=0;j<10;j++)
emp(1);
s.add(empid);
}
}
s.o.p("count"+empid);

Member Avatar

This topic is 6 months old and maybe you meant to start a new post. I think its at the bottom of the forum page, start new post/topic.

Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.

Java How to Use a Variable From Another Class

Source: https://www.daniweb.com/programming/software-development/threads/250774/how-to-access-variable-from-another-class

0 Response to "Java How to Use a Variable From Another Class"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel