在面板内加载面板

时间:2015-12-21 13:49:44

标签: java swing panel

我有一个主框架,在这个框架内,我正在展示其他面板。 但其中一个面板包含按钮,其目的是显示另一个面板 - 类似于面板内的显示面板。

这是我需要加载另一个面板的面板代码:

public class PnlConnectionType extends JPanel {

private JPanel cardPanel;
private CardLayout cl;

/**
 * Create the panel.
 */
public PnlConnectionType() {

    cardPanel = new JPanel();
    cardPanel.setBounds(new Rectangle(10, 11, 775, 445));

    cl = new CardLayout();
    cardPanel.setLayout(cl);

    setBounds(new Rectangle(10, 11, 774, 465));
    setLayout(null);

    JButton btnRS485 = new JButton("CONNECTION BY RS485");
    btnRS485.setBounds(20, 23, 266, 107);
    add(btnRS485);

    JButton btnNoConnectionoffline = new JButton("NO CONNECTION (OFFLINE)");
    btnNoConnectionoffline.setBounds(20, 159, 266, 107);
    add(btnNoConnectionoffline);

    final settingsPanel2 settPnl2 = new settingsPanel2();
    settPnl2.setBounds(new Rectangle(10, 11, 774, 465));
    settPnl2.setSize(775,465);
    settPnl2.setBounds(10, 11, 775, 445);

    cardPanel.add(settPnl2, "1");

    btnRS485.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            cl.show(cardPanel, "1");                
        }
    });           
}   
}

当我点击按钮面板时没有显示。我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的cardPanel从未添加到PclConnectionType面板中。因此,尽管它正确设置了您想要的内容,但它不属于任何顶级窗口的组件层次结构。

您应该做的是在CardLayout面板上设置PnlConnectionType,并设计两个布局;一个是您想要显示的面板,另一个是没有它的面板。然后,使用这些布局将面板添加到PnlConnectionType面板,并显示没有settingsPanel2的面板。

或者,或者,将空JPanel添加到CardLayout面板,并最初显示。然后将其添加到PnlConnectionType。一开始,它只会显示一个空白空间,可以通过调用show来填充您想要的内容。

这是一个如何实现这样的代码的例子:

//Create the card layout, and add a default empty panel
final CardLayout cardLayout = new CardLayout();
final JPanel cardPanel = new JPanel();
cardPanel.setLayout(cardLayout);
cardPanel.add(new JPanel(), "Empty");

//Create and add the contents which is initially hidden
JPanel contents = new JPanel();
contents.setBackground(Color.BLUE);
contents.setOpaque(true);
cardPanel.add(contents, "Contents");

//Add the button and card layout to the parent
setLayout(new BorderLayout());
final JButton toggle = new JButton("Show");
toggle.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            if(toggle.getText().equals("Show")){
                //Show contents
                cardLayout.show(cardPanel, "Contents");
                toggle.setText("Hide");
            } else{
                //Hide Contents
                cardLayout.show(cardPanel, "Empty");
                toggle.setText("Show");
            }
        }
    });
add(toggle, BorderLayout.SOUTH);
add(cardPanel, BorderLayout.CENTER);

查看我想要展示的所有内容是如何在开始时添加的,然后在我希望显示时使用show显示。

相关问题