Switching Panels in Swing

元气小坏坏 提交于 2019-12-12 00:27:44

问题


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


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/20624403/switching-panels-in-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!