I'm just starting out with Swing - I'm sorry if this question is hard to follow, but I feel like this is a very simple thing but it seems surprisingly hard in Swing.
I have a panel with two text fields and a submit button.
I've added a listener on the submit button, when it's clicked I validate the data and such.
开发者_开发技巧Now, I want the frame to display a new panel - get rid of the current panel with the text fields and submit button, and instantiate a new one based on the data entered in the text fields.
How can I send this data back to the frame, so the frame can remove the current panel and replace it with a new, different panel, created with the data from the first panel.
Though it's not what I'm doing, it could be thought of like a login.
Display login panel Panel gets username and password, validates (validation could be done higher up, too) If validated, replace login panel with real content panel
This is surprisingly hard to figure out in Swing. Should I be defining my own event type and making the frame a listener for that event?
If I understood your question, you can use callback logic like this;
MyLoginPanel login = new MyLoginPanel(new IMyCallback(){
public void processLogin(){
//frame can remove the current panel and replace it with a new
}
});
- MyLoginPanel extended from Jpanel with Constructor
public MyLoginPanel(IMyCallback callback)
- IMyCallback is an interface which has
public void processLogin()
method.
You could call callback.processLogin();
from LoginPanel
Does it work for you?
You should look at the java.awt.CardLayout. This Layout can handle multiple panels which are stacked on top of each other. And you can choose which panel should be the topmost and therefore visible.
The following code shows the relevent parts from the tutorial mentioned above:
//Where instance variables are declared:
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
//Create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
and to switch the visible panel:
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, TEXTPANEL);
精彩评论