简体   繁体   English

Swing中的切换面板

[英]Switching Panels in Swing

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. 我有一个使用Card Layout的Swing应用程序,该应用程序基本上根据用户从下拉菜单中选择的内容来更改显示的面板。

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 达里奥

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM