J p.
J p.

Reputation: 25

JPanel only showing one component when added to container

Hello all I am having a bit of an issue with this. I created a JPanel and added components to it and then added the JPanel to container. Now when I call this class from main a window pops up but it only displays the first component of the JPanel. Why is it only showing the first item and not all of them? Thanks.

Note: this code is not complete, I am simply trying to figure out why my components are not showing up before moving on to other things, please just address the components issue.

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;


public class Player extends JFrame implements ActionListener
{
       private CardLayout playerCard;
       private JPanel cardPanel;
       public String player1;
       public String player2;

      // Constructor:
      public Player()
      {

        setTitle("Game");
        setSize(300,200);
        setLocation(10,200); 
        Container contentPane = getContentPane();
        contentPane.setLayout(new FlowLayout());

                //set up the panel
        cardPanel = new JPanel();
        playerCard = new CardLayout();
        cardPanel.setLayout(playerCard);

                //get player one name
        JLabel p1Name = new JLabel("Player 1 Name:");
        JTextField oneName = new JTextField();

                //get the name for player 2
        JLabel p2Name = new JLabel("Player 2 Name:");
        JTextField twoName = new JTextField();

                //the button to start the game
        JButton start = new JButton("Start");

        //add the components << Why is only the first component shown??
        cardPanel.add(start);
        cardPanel.add(p1Name);
        cardPanel.add(oneName);
        cardPanel.add(p2Name);
        cardPanel.add(twoName);

        contentPane.add("startCard",cardPanel);
        }

    @Override
    public void actionPerformed(ActionEvent arg0) 
    {
        // TODO Auto-generated method stub

    } 
}

Upvotes: 1

Views: 1010

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You're not using your layouts correctly. You use the String constant when adding components to the CardLayout using component, not the FlowLayout using component. And the String constant goes after the component in the add method. Please read the layout manager tutorial since this is all explained quite well there. It looks like you're using CardLayout where it shouldn't be used, and this is why you're only seeing one component. In other words, your program is using layouts completely bass ackwards.

In other words, the container that uses CardLayout can only show one component at a time, meaning, since cardPanel uses CardLayout, it can only display one component, here twoName will likely be the only thing showing on it.

Upvotes: 3

Related Questions