Question

So I'm just creating a simple game screen and I want to lay out my two buttons like this:

hello

I was advised to use CardLayout (I've not worked with layouts before) so I read up on the java docs and created this:

canvas.setLayout(new CardLayout());
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();

//buttons
final JButton btn1 = new JButton(play);
btn1.setBorder(BorderFactory.createEmptyBorder());
btn1.setContentAreaFilled(false);
final JButton btn2 = new JButton(instructions);
btn2.setBorder(BorderFactory.createEmptyBorder());
btn2.setContentAreaFilled(false);
card1.add(btn1);
card2.add(btn2);    

canvas.add(card1);
canvas.add(card2);          

However, it produces this:

enter image description here

I can't seem to find any information about positioning with card layout. My guess is that I shouldn't be using this layout at all, so what layout should I use?

Was it helpful?

Solution

Card layout is used to show only one of multiple components in the layout. You can select programmatically which card to show and the rest will be hidden from view.

If you add two buttons in card layout, you can see only one. You shouldn't be using it for your specific situation. you can use Box layout with X axis

The BoxLayout manager is constructed with an axis parameter that specifies the type of layout that will be done. There are four choices:

X_AXIS - Components are laid out horizontally from left to right.

Y_AXIS - Components are laid out vertically from top to bottom.

LINE_AXIS - Components are laid out the way words are laid out in a line, based on the container's ComponentOrientation property. If the container's ComponentOrientation is horizontal then components are laid out horizontally, otherwise they are laid out vertically. For horizontal orientations, if the container's ComponentOrientation is left to right then components are laid out left to right, otherwise they are laid out right to left. For vertical orientations components are always laid out from top to bottom.

PAGE_AXIS - Components are laid out the way text lines are laid out on a page, based on the container's ComponentOrientation property. If the container's ComponentOrientation is horizontal then components are laid out vertically, otherwise they are laid out horizontally. For horizontal orientations, if the container's ComponentOrientation is left to right then components are laid out left to right, otherwise they are laid out right to left. For vertical orientations components are always laid out from top to bottom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top