-1

I have 2 frames each with 1 textfield, I want to capture in the first frame textfield of one a string and pass it to another frame in the textfield, but save the data in a global variable type String.

(Sorry for my english)

dbmz
  • 1
  • 2
  • 1
    make your frames public – Madhawa Priyashantha Sep 18 '14 at 16:09
  • 2
    Show us what you tryed to do... – Marcello Davi Sep 18 '14 at 16:12
  • 1
    @HovercraftFullOfEels why? – Madhawa Priyashantha Sep 18 '14 at 16:16
  • 1
    @madhawapriyashantha: because as your program scales up larger, making fields public allows for possibility of unwanted side effects and increases the number of connections and complexity, increasing the risk of bugs. This goes to the core of Java and OOP principles, something I would assume that you know if you're answering Java questions here. – Hovercraft Full Of Eels Sep 18 '14 at 16:19
  • 2
    I put down a small part readable code – dbmz Sep 18 '14 at 16:22
  • 2
    ///frame send "principio" ////////////// here i have txtingress ///////////frame receives "date_1" /////////// principio obj = new principio(); String fin2 = obj.txtingress.getText(); – dbmz Sep 18 '14 at 16:23
  • 1
    @HovercraftFullOfEels i found this method from stackoverflow but it's about c# and concept was same. – Madhawa Priyashantha Sep 18 '14 at 16:24
  • 1
    Look up the singleton pattern, and how it may be applicable to your case. Singleton's have their drawbacks, but there are (much as some people like to oppose it) times when a single registry of global-style variables is a good idea... the trick is to understand your particular scenario and the implications. – Jon Story Sep 18 '14 at 16:26
  • jFrame2.textfield1.setText(jFrame1.textfield1.gettext()); ///////i tried with this code and not working – dbmz Sep 18 '14 at 16:33
  • @dbmz make your textfield1 in jframe1 public – Madhawa Priyashantha Sep 18 '14 at 16:39
  • ready, not working in public, in frame 2 i have a global variable String receive; in the frame 1 a textfield call send, the textfield send must send data to frame 2 in the variable receive. NOTE: my textfield are public. – dbmz Sep 18 '14 at 16:55
  • dbmz, although @madhawapriyashantha means well, his recommendations are misleading and potentially dangerous. The solution is almost definitely not to make anything public. I again implore him not to mislead newbies by giving recommendations on subjects that he is not very familiar with such as object oriented programming and sharing of information as it pertains to Java. – Hovercraft Full Of Eels Sep 18 '14 at 19:25
  • @HovercraftFullOfEels every frames are public in netbeans by default and your recommendation surely far and far better than mine but op doesn't use your suggestion at that time .see op's answer and op have status that "I RESOLVE THE PROBLEM". – Madhawa Priyashantha Sep 19 '14 at 03:11

2 Answers2

1

Java doesn't have "global" variables, and you will not want to use this. Rather you will want to structure your code somewhat along the M-V-C model (model-view-control), and hold the key text String in your model. Then you can have any GUI window you wish listen to the model for changes to this variable, and they can then react accordingly.

If all you want to do is to have your two JTextFields share the exact same text, another thing you can do is have them share the same model -- Document for JTextFields.

On a side, note, you will rarely want your GUI to have more than one JFrame displaying at the same time. If you need a second dependent window, go for a dialog such as a JDialog.


Edit
For example

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;

public class SharedData {
   private static void createAndShowGui() {
      SimpleModel model = new SimpleModel();
      MyPanel1 panel1 = new MyPanel1(model);
      MyPanel2 panel2 = new MyPanel2(model);

      JFrame frame = new JFrame("SharedData");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(panel1);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

      JDialog dialog = new JDialog(frame, "Dialog", false);
      dialog.getContentPane().add(panel2);
      dialog.pack();
      dialog.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class MyPanel2 extends JPanel {
   private JTextField field = new JTextField(10);
   private UpdateAction updateAction = new UpdateAction("Update");
   private JButton updateDataBtn = new JButton(updateAction);
   private SimpleModel model;

   public MyPanel2(SimpleModel model) {
      this.model = model;
      field.addActionListener(updateAction);

      add(field);
      add(updateDataBtn);
   }

   private class UpdateAction extends AbstractAction {
      public UpdateAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         if (model != null) {
            model.setMyText(field.getText());
         }
      }
   }

}

class MyPanel1 extends JPanel {
   private JTextField field = new JTextField(10);
   private SimpleModel model;

   public MyPanel1(SimpleModel model) {
      field.setFocusable(false);
      this.model = model;
      add(field);

      model.addPropertyChangeListener(new ModelListener());
   }

   private class ModelListener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
         if (SimpleModel.MY_TEXT.equals(evt.getPropertyName())) {
            field.setText(model.getMyText());
         }
      }
   }

}

class SimpleModel {
   public static final String MY_TEXT = "my text";
   private SwingPropertyChangeSupport support = new SwingPropertyChangeSupport(this);
   private String myText = "";

   public String getMyText() {
      return myText;
   }

   public void setMyText(String myText) {
      String oldValue = this.myText;
      String newValue = myText;
      this.myText = myText;
      support.firePropertyChange(MY_TEXT, oldValue, newValue);
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      support.addPropertyChangeListener(listener);
   }

   public void removePropertyChangeListener(PropertyChangeListener listener) {
      support.removePropertyChangeListener(listener);
   }

}

Edit 2
If you want both JTextFields to share the same data as the user types it in, then have them share models (Documents for JTextFields). For example

import javax.swing.*;

public class SharedData2 {
   private static void createAndShowGui() {
      JTextField field1 = new JTextField(10);
      JTextField field2 = new JTextField(10);

      // ******** key below
      field2.setDocument(field1.getDocument());

      JPanel panel1 = new JPanel();
      JPanel panel2 = new JPanel();

      panel1.add(field1);
      panel2.add(field2);

      JFrame frame = new JFrame("SharedData2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(panel1);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

      JDialog dialog = new JDialog(frame, "Dialog", false);
      dialog.add(panel2);
      dialog.pack();
      int x = frame.getLocation().x + 200;
      int y = frame.getLocation().y + 200;

      dialog.setLocation(x, y);
      dialog.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
-1

I RESOLVE THE PROBLEM.

////frame 1(principio.java) send /// this frame send the content

private void txtingresaKeyPressed(java.awt.event.KeyEvent evt) {                                      
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
        fecha_1 obj = new fecha_1();
        obj.setVisible(true);
        fecha_1.txtfin.setText(txtingresa.getText());
        this.setVisible(false);
        }
    } 

///////frame 2(fecha_1.java) receive the content//////////

private void txtfinKeyPressed(java.awt.event.KeyEvent evt) {                                  
    if(evt.getKeyCode()==KeyEvent.VK_ENTER){
        periodo();
        txtini.setText(null);
        String fu = principio.txtingresa.getText();
        txtfin.setText(fu);//INGRESA REPETIDAMENTE EL VALOR INGRESADO EN PRINCIPIO CAJA TXTINGRESA

    }
} 

//code repeats but never delete the default content that gave him the first form (principio.java)

dbmz
  • 1
  • 2
  • You should never use a KeyListener in a JTextField as it will mess up the JTextField's processing of text (which goes through key bindings). Better to add an ActionListener to your JTextField as this will be activated on pressing the enter key. – Hovercraft Full Of Eels Sep 18 '14 at 19:33