i have 2 class for example class a and class b. i need the string store at class a pass and use by class b, here is my code for class a and class b.

class a

public void actionPerformed(ActionEvent arg0) {
                 JFileChooser fileChooser = new JFileChooser();

                 fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
                 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                 fileChooser.setAcceptAllFileFilterUsed(false);
                 int returnValue = fileChooser.showOpenDialog(null);
                 if (returnValue == JFileChooser.APPROVE_OPTION) {
                     String test;
                      File selectedFile = fileChooser.getSelectedFile();
                     test=fileChooser.getSelectedFile().toString();

                    }

class b

try{
            a path = new a();

            FileInputStream fis = new FileInputStream(path.test);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

           while((line = br.readLine()) != null) 
           {

           tableModel.addRow(line.split("___")); 
           }
           br.close();
        }
       catch(IOException e){
           JOptionPane.showMessageDialog(null, "Error");
   e.printStackTrace();
       }

im check using System.out.print for String value test for both class. in class a, i can get the correct value, but in class b, i only get null.

Dani AI

Generated

A quick diagnosis and a safer pattern to follow.

As noted, the original problem came from scope and instance mismatch: the file path was set in one context (a local variable or in the visible GUI instance) but class B tried to read it from a different context (a newly constructed object or an uninitialized field). Declaring the field as static (as later did) made the value globally visible, which explains why it appeared to “work.” ’s question about why static was used is valid: static hides the real problem and creates global mutable state.

Recommended approaches (prefer in this order)

  • Pass the selected path directly to the consumer that needs it (constructor or method parameter). This keeps dependencies explicit and testable.
  • Keep the path as a private instance field and expose a getter on the same GUI instance that performed the selection. Avoid creating a fresh GUI instance just to read fields from it.
  • Use a callback/listener: when the file is chosen, call a method on the reader class or fire an event with the path.
  • Perform I/O off the Event Dispatch Thread (SwingWorker or another background thread) and update the Swing model on the EDT to keep the UI responsive.

Minimal example of constructor injection (illustrative, not a repeat of earlier code):

public class FileLoader {
  private final Path p;
  public FileLoader(String path) { p = Paths.get(path); }
  public List<String> readAll() throws IOException {
    try (BufferedReader r = Files.newBufferedReader(p)) {
      List<String> L = new ArrayList<>();
      String s;
      while ((s = r.readLine()) != null) L.add(s);
      return L;
    }
  }
}

Checklist: ensure the same instance that set the value is the one exposing it; avoid static mutable fields for app state; run file I/O off the EDT and marshal any table updates back onto the EDT.

Recommended Answers

All 4 Replies

You declare String test on line 9 of a. When you declare a variable in Java its scope if from the preceeding '{' to the following '}'. In this case that test variable exists just from line 8 to line 13, after which it is discarded. You presumably have another String test declared somewhere else, and that's the one the b uses.

ps If you are no longer waiting for replies to your previous topic, please mark it "solved". Thank you.

ok, i got it now so i make some changes. but still i cant get the value from class testgui String test value to class b.

public class testgui {


    private JFrame pu;

    String test;

    public static void main(String [] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    testgui window = new testgui();
                    window.pu.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }

    /**
     * Create the application.
     */
    public testgui() {

        initialize();
    }

i also had try the getter setter method but it still not working. i still cant get the value.

ok, i find out the solution already.

class a
    static String test="testing";

and you can get the String test value from other class by

class b
    "your class name"."the String name"

for example

System.out.println(a.test);

then it will show the value inside that String.

Member Avatar for Member #46692

Why did you declare the String in class 'a' as static?

Be a part of the DaniWeb community

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