Question

I have a Swing application using Card Layout which basically changes the displayed panel depending on what the user selects from a drop-down menu.

One of my panels has a form. I would need for when the submit buton is pressed for all the inputs to be collected and the Panel to be switched to another one. (This second panel is defined in a separate class) I would also need for all the input to be somehow passed to a method in the new panel.

Any suggestions? Dario

Was it helpful?

Solution

If you look at the <--s in the following code, each should solve each different question you have in your post. I figured you should know how to make a submit button, so I didn't include that. (Note: this is not running code, just suggestions);

public class MainPanel entends JPanel {
    CardLayout layout = new CardLayout(); <-- card layout
    JPanel panel = new JPanel(layout);    <-- set layout to main panel
    NewPanel newPanel = new NewPanel();   <-- you new panel
    JPanel p1 = new JPanel();             <-- random panel
    JTextField text = new JTextField()    <-- text field in form
    JButton button = new JButton();

    JComboBox cbox = new JComboBox(new String[] {"newPanel", "p1"});  <-- hold panel names

    public MainPanel(){
        panel.add(newPanel, "newPanel");       <-- name associated with panel
        panel.add(p1, "p1");

        ...

        cbox.addAItemListener(new ItemListener(){
            public void itemStateChnaged(ItemEvent e){

                layout.show(panel, (string).getItem());     <-- show Panel from combobox
            }
        });

        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String txt = text.getText();
                newPanel.printText(txt);             <-- Using method from other class    
            }
        });
    }
}  

public class NewPanel extends JPanel {

    public void printText(String text){             <-- method from other class
        System.out.println(text);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top