简体   繁体   中英

how to put components in the center in a CardLayout panel

I have a frame that has couple of panels and they change by CardLayout. Inside each panel i will have different components. To design the GUI of the panel I used GridBagLayout. But the problem is any component or Layout I use for these paneles, they all stay at the top of the page. So basically the panel size of the CardLayout is some small amount of the frame. I want to make the sub panel size as large as the main CardLayout size.

Code for main CardLayout:

public class MainPanel extends JPanel {
    private CardLayout cl = new CardLayout();
    private JPanel panelHolder = new JPanel(cl);

    public MainPanel() {
        NewSession session = new NewSession(this);
        ChooseSource chooseSource = new ChooseSource(this);

        panelHolder.add(session, "1");
        panelHolder.add(chooseSource, "2");

        cl.show(panelHolder, "dan");
        add(panelHolder);
    }
    public void showPanel(String panelIdentifier){
        cl.show(panelHolder, panelIdentifier);
    }
}

A sub panel:

public class ChooseSource extends JPanel {
    MainPanel ob2;
    JButton btn;
    JLabel label;
    JTextField field;

    public ChooseSource(MainPanel mainPanel){
        this.ob2 = mainPanel;


        btn = new JButton("Browse");
        label = new JLabel("Folder ");
        field = new JTextField();

        btn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                ob2.showPanel("1");

            }
        });


        GridBagLayout layout = new GridBagLayout();
        setLayout(layout);

        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        c.ipady = 20;
        c.gridheight = 2;
        add(btn, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 0;
        c.ipady = 10;
        c.gridheight = 1;
        c.insets = new Insets(0,10,0,0); 
        add(label, c);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 1;
        c.ipady = 0;
        c.gridheight = 1;
        c.insets = new Insets(0,10,0,0); 
        add(field, c);
    }
}

The left image shows how it is not, and right one is the one I am trying to make. basically I want to have access to all the available space of the panel.

Any idea?

在此处输入图片说明

MainPanel的布局管理器更改为BorderLayoutGridBagLayout东西

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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