Switch panels and transfer data to Swing

I'm just starting out with Swing - I'm sorry if this question is hard to understand, but I feel it is a very simple thing, but in Swing it seems surprisingly difficult.

I have a panel with two text fields and a submit button.

I added a listener to the submit button when he clicked. I check data etc.

Now I want the frame to display a new panel - get rid of the current panel with text fields and the submit button and create a new instance based on the data entered in the text fields.

How can I send this data back to the frame, so that the frame can delete the current panel and replace it with a new, different panel created using data from the first panel.

Although this is not what I am doing, it could be called as a login.

Show login panel The panel receives a username and password, verifies (verification can be performed above) If this is confirmed, replace the login panel with the real content panel

This is unexpectedly hard to understand in Swing. Should I define my own type of event and make the frame a listener for this event?

+4
source share
2 answers

If I understand your question, you can use the callback logic as follows:

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 by constructor public MyLoginPanel(IMyCallback callback)
  • IMyCallback is an interface that has a public void processLogin() method.

You can call callback.processLogin(); from LoginPanel

Does it work for you?

+1
source

You should look at java.awt.CardLayout . This layout can handle multiple panels that 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 relevant parts from the above manual:

 //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); 
+1
source

Source: https://habr.com/ru/post/1332189/


All Articles