简体   繁体   中英

Change Background and size of panels in card layout

I have some panels in a card layout container (no idea if that is correct terminology). I can't find a way to set the location, or size of these panels inside the container. I tried setBounds and setLayout(null) and I still can't get anything to change. These are my fields and the constructor. I've gotten my frame working and I can see and use the buttons to change cards, but I really can't change much else about the cards. I set the two card panels two have different backgrounds, but they only make a small boarder of color around the button and leave it in the centre of the screen.

I also don't understand why this isn't pasting my code properly... So sorry!

public class TestPanel extends JPanel implements ActionListener {

CardLayout cl = new CardLayout();

private JPanel panelCont = new JPanel();

private JPanel panel1 = new JPanel();

private JPanel panel2 = new JPanel();

private static JButton but1 = new JButton("Change panels");

private static JButton but2 = new JButton("Change back");

public TestPanel() {

    panelCont.setLayout(cl);
    panel1.add(but1);
    panel2.add(but2);
    panel1.setBackground(Color.black);
    panel2.setBackground(Color.blue);
    panelCont.add(panel1, "1");
    panelCont.add(panel2, "2");
    cl.show(panelCont, "1");
    but1.addActionListener(this);
    but2.addActionListener(this);
    add(panelCont);
}
}

Thanks. I apologise in advance. I'm finding it hard to understand card layout.

A CardLayout respects the preferred size of the panels added to the layout. That is the size will be the size of the largest panel added to the layout.

I set the two card panels two have different backgrounds, but they only make a small boarder of color around the button and leave it in the centre of the screen.

The default layout for a panel is the FlowLayout. A FlowLayout by default has a 5 pixel horizontal/vertical gap around each component. So the preferred size of your panel is the size of the button plus the 5 pixel gap.

The panel is displaying correctly. When you add other components to the panel the size will change as required.

It's not clear where you pack() the enclosing Window . By default, pack() causes a panel having CardLayout to adopt the the size of the largest panel's preferred size, which is determined by the size of its contents. This example uses setPreferredSize() to specify an arbitrary size, but you can override getPreferredSize() as shown here .

图片

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