Search code examples
javafunctionjframejlabel

Have a function return a JLabel and add it to a JFrame


I wrote a function that returns a JLabel and another function adds it to a JFrame, however, there does not seem to be a JLabel being added to it. I tested different things on the JLabel, such as colors and text, but it did not show up. I added a JLabel to the JFrame just normally, and that worked. I would really like to be able to add my function into the JFrame.

I have a JButton that creates a new frame, here is the code for that:

inputButton.addActionListener(new ActionListener()
    {   
        public void actionPerformed(ActionEvent e)
        {
            JFrame realSim = new JFrame();
            JPanel realSim2 = new JPanel();
            newFrame(realSim, realSim2);
            realSim2.add(Planet.createPlanet(1));
            Planet.createPlanet(1).setBounds(100, 100, 20, 20);
            Planet.createPlanet(1).setText("Ello, just testing!");
        }
    }
    );

Planet.createPlanet() is the function that returns a JLabel. Here is the code for that function:

public static JLabel createPlanet(int planetNum)
{
    JLabel planetRep = new JLabel();
    switch (planetNum) 
    {
    case 1: planetColor = Color.WHITE;
            break;
    case 2: planetColor = Color.RED;
            break;
    case 3: planetColor = Color.ORANGE;
            break;
    case 4: planetColor = Color.YELLOW;
            break;
    case 5: planetColor = Color.GREEN;
            break;
    case 6: planetColor = Color.CYAN;
            break;
    case 7: planetColor = Color.BLUE;
            break;
    case 8: planetColor = Color.MAGENTA;
            break;
    case 9: planetColor = Color.PINK;
            break;
    default: planetColor = Color.BLACK;
            break;
    }
    planetRep.setBackground(planetColor);
    planetRep.setOpaque(true);
    return planetRep;
}

I can't think of what I might be doing wrong. Any help would be greatly appreciated.


Solution

  • 1) realSim2.add(Planet.createPlanet(1));
    2) Planet.createPlanet(1).setBounds(100, 100, 20, 20);
    3) Planet.createPlanet(1).setText("Ello, just testing!");
    

    On the first line. You add a new label to the JPanel. But that label doesn't have any text. As it is just created by the function, it doesn't have any size either.

    On the second line you create a new JLabel and set up a size, but that's it. You don't add it to the panel.

    One the third line you are doing the same as the second. Creating a new JLabel but you are not adding it.

    Try this code instead:

    JLabel label = Planet.createPlanet(1);
    label.setBounds(100, 100, 20, 20);
    label.setText("Ello, just testing!");
    realSim2.add(label); //rememebr to add the object to the panel