简体   繁体   中英

Displaying a string variable from one window into another window Java Swing

Apologies if the question is a little ambiguous. Essentially, I have two separate windows. One is the main window which takes in a String of numbers into a JTextField . I then assign those numbers to a variable (take as a given that all variables are already declared) eg

xxxx = textField.getText(); 

In my second window, which opens up after a button is pushed, I need the number that was entered in the first window's textField to be automatically displayed in a textField in the second window.

for this I use:

textField_1 = new JFormattedTextField();
textField_1.setEditable(false);
panel_4.add(textField_1);

textField_1.setText(dbMain.xxxx);
System.out.println(dbMain.xxxx);

textField_1.setFont(productFont);
textField_1.setColumns(10);

I can't seem to get this to work as everything I have tried just gives me a blank textField or if I try print the variable in the console, I get null .

dbMain is the main class in the program from which I'm calling xxxx from

If you call the getText() method and assign the return value to an attribute at the very beginning, in this case xxxx, it must be null before user entered any text.

I recommend you provide a method to dbMain and return the getText() value at the moment the 2nd window appears, like:

(inside Main class)

public String getTextFromTextField() {
  return this.textField.getText();
}

Then in 2nd window call dbMain.getTextFromTextField() should return the most current value entered by user.

Putting aside whether having 2 frames are good. What you want to achieve can be done in a few ways:

  1. MVC (Model View Controller) where you keep all your data in the model. So both your frames will be accessing the same model (data). Update from one side will be reflected on the other.

  2. Observer pattern. Create an observer and an observable interface. Let your frames implement these interfaces. When one made any changes, it will "automatically" notify the other.

  3. Pass a reference of current frame to the other frame. (This is the simplest to implement)

Example

class WindowOne extends JFrame{
    private JFrame windowTwo;
}
class WindowTwo extends JFrame{
    private JFrame windowOne;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM