开发者

How to share array(list)/variables between tabbed pane in Java swing?

开发者 https://www.devze.com 2023-01-12 09:04 出处:网络
I been trying to do \"the question title\". Here is my current code: Main.java import java.awt.*; import javax.swing.*;

I been trying to do "the question title". Here is my current code:

Main.java

import java.awt.*;
import javax.swing.*;

public class Main {

public static void main(String[] args) {

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

JTabbedPane tp = new JTabbedPane();
User user = new User();
tp.addTab("Register", new Register(user));
tp.addTab("Process", new Process(user));

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

}

Register.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Register extends JPanel {
/*
    The code too long, but what this class does is, display textfields:
    username, password and email address
    And there is a submit button, when press, it will update the process pane
    */
}

How 开发者_如何学Pythonto pass the username password and email to Process.java(Jpanel)?

[I am new to java and no programming background]


As I can see, you share user between Register and Process. So the problem is how to refresh Process when data in user are updated. You could create listener on User, or on 'Register'. IMHO listener on 'Register' is more elegant.

RegisterListener:

public interface RegisterListener {
  void userRegistered(User user);
}

Register:

public void addRegisterListener(RegisterListener listener) {
  //add listener to some collection.
}

//Call this method on Submit button press
protected void fireRegistered() {
  //iterate over collection of listeners and on each do:
    listener.userRegistered(user);
}

Process:

Process implements RegisterListener {
  public void userRegistered(User user) {
    refreshView();
  }
}

And in main:

Register register = new Register(user);
Process process = new Process();
register.addRegisterListener(process);

So Process should be informed when user is registered, and it should receive all the necessary data in user parameter of listener method.

0

精彩评论

暂无评论...
验证码 换一张
取 消