我写了一个返回 JLabel 的函数,另一个函数将它添加到 JFrame,但是,似乎没有将 JLabel 添加到它。我在 JLabel 上测试了不同的东西,例如颜色和文本,但它没有显示出来。我只是正常地向 JFrame 添加了一个 JLabel,并且成功了。我真的很想能够将我的函数添加到 JFrame 中。
我有一个创建新框架的 JButton,下面是代码:
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() 是返回 JLabel 的函数。 这是该函数的代码:
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;
}
我想不出我可能做错了什么。任何帮助将不胜感激。
最佳答案
1) realSim2.add(Planet.createPlanet(1));
2) Planet.createPlanet(1).setBounds(100, 100, 20, 20);
3) Planet.createPlanet(1).setText("Ello, just testing!");
在第一行。您向 JPanel 添加了一个新标签。但是那个标签没有任何文字。由于它只是由函数创建的,因此它也没有任何大小。
在第二行,您创建了一个新的 JLabel 并设置了一个大小,仅此而已。您不会将其添加到面板。
在第三行中,您正在执行与第二行相同的操作。创建一个新的 JLabel 但您没有添加它。
试试这个代码:
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
关于java - 让函数返回 JLabel 并将其添加到 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28238198/