views:

37

answers:

2

This is my main class code:

public static void main(String[] args) {

 JFrame f= new JFrame ("My Frame");
 f.setDefaultCloseOperation (JFrame .EXIT_ON_CLOSE);

 JTabbedPane tp = new JTabbedPane();
 tp.addTab("Pane1", new PaneFirst());
 tp.addTab("Pane2", new PaneSecond());

 f.add(tp);
 f.pack();
 f.setVisible(true);
 }

In PaneFirst, I have a list of user-entered-value(textfields), lets say I have 5. And I store each of the value into an array(or maybe arraylist). How do I pass those 5 values from PaneFirst to PaneSecond?

(Sorry, I am new to Java and Object Oriented Programming language)

A: 

You could provide a reference to the second pane to the first pane. Something like:

 PaneSecond pane2 = new PaneSecond();
 JTabbedPane tp = new JTabbedPane();
 tp.addTab("Pane1", new PaneFirst(pane2));
 tp.addTab("Pane2", pane2);

The first pane could then storr this and use it later to call methods from the second pane.

DrDipshit
Why this answer being down voted?
javaIsTheBest
I believe the reason it was down voted is that it shows a very bad practice in UI development (although it would work).In other words, we could say this is a "quick and dirty hack".
jfpoilpret
+3  A: 

You really shouldn't store the values on the pane object ("view") but create a separate class that holds the values ("model").

Then you can pass the reference to the model to both panes and if one pane changes values on model class, the other one will see the changes too. The follwing simple example is to show the idea in code. Your Model will look different but it should give an idea on how to implement, create and use it.

public class Model {
   private List<String> values = new ArrayList<String>();
   public void add(String s) {
      values.add(s);
   }
   public void remove(String s) {
      values.remove(s);
   }
   public void get(i) {
      values.get(i);
   }
   // ...

}   

public static void main(String[] args) {

 JFrame f= new JFrame ("My Frame");
 f.setDefaultCloseOperation (JFrame .EXIT_ON_CLOSE);

 JTabbedPane tp = new JTabbedPane();
 Model model = new Model();
 tp.addTab("Pane1", new PaneFirst(model));
 tp.addTab("Pane2", new PaneSecond(model));

 f.add(tp);
 f.pack();
 f.setVisible(true);
}
Andreas_D
This is a good recommendation!
Jonas
Is this a MVC model? I have this stupid question, "Must I separate the model class file and the main class file?"
javaIsTheBest
It provides model-view seperation, which tends to make code more maintainable in large projects. In general its a better design, but for small projects < 1000 lines of code or so I don't always bother with it.
DrDipshit
@javaIsTheBest - technically spoken, you can mix model an view, but if you separate those parts, you'll see pretty soon, that developing, maintaining and communicating the software becomes *much* easier.
Andreas_D