Make an added JPanel visible inside a parent JPanel

前端 未结 3 408
面向向阳花
面向向阳花 2020-12-06 22:01

How to make an added JPanel visible inside a parent JPanel?

I am using Netbeans for designing my UI.

I have a MainFrame.java<

3条回答
  •  旧时难觅i
    2020-12-06 22:27

    your requirement truely full filled by CARD LAYOUT see this example link

    and below example Link

    enter image description here

    the perfect code for your problem case is

    package panels.examples;
    
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class MainFrame extends JFrame implements ActionListener
    {
    JPanel headerPanel;
    JPanel bodyPanel;
    JPanel panel1,panel2,panel3;
    JButton button1,button2,button3;
    Container con;
    CardLayout clayout;
    public MainFrame() 
    {
        //con=getContentPane();
        clayout=new CardLayout();
        headerPanel=new JPanel();
        bodyPanel=new JPanel(clayout);
    
        button1=new JButton("button1");
        button2=new JButton("button2");
        button3=new JButton("button3");
    
        //add three buttons to headerPanel
        headerPanel.add(button1);
        headerPanel.add(button2);
        headerPanel.add(button3);
    
        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);
    
        panel1=new JPanel();
        panel1.add(new JLabel("Panel1"));
        panel1.setBackground(Color.pink);
        panel2=new JPanel();
        panel2.add(new JLabel("Panel2"));
        panel2.setBackground(Color.gray);
        panel3=new JPanel();
        panel3.add(new JLabel("Panel3"));
    
        //add above three panels to bodyPanel
        bodyPanel.add(panel1,"one");    
        bodyPanel.add(panel2,"two");    
        bodyPanel.add(panel3,"three");  
    
    
        setLayout(new BorderLayout());
        setSize(600,450);
        add(headerPanel,BorderLayout.NORTH);
        add(bodyPanel,BorderLayout.CENTER);
    //  headerPanel.setBounds(0,0,600,100);
        bodyPanel.setBounds(0,100, 600, 500);
        setVisible(true);
    
    }
    
    public static void main(String args[])
    {
        new MainFrame();
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
        if(e.getSource()==button1)
        {
            clayout.show(bodyPanel, "one");
        }
        else if(e.getSource()==button2)
        {
            clayout.show(bodyPanel, "two");
        }
        else if(e.getSource()==button3)
        {
            clayout.show(bodyPanel, "three");
        }
    
    }
    
    }
    

    out put

    out put

提交回复
热议问题