Rot*_*thX 1 java function jlabel jframe
我编写了一个返回JLabel的函数,另一个函数将它添加到JFrame中,但是,似乎没有添加JLabel.我在JLabel上测试了不同的东西,比如颜色和文字,但它没有显示出来.我正常地将JLabel添加到JFrame,这很有用.我真的希望能够将我的功能添加到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!");
}
}
);
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我想不出我可能做错了什么.任何帮助将不胜感激.
小智 5
1) realSim2.add(Planet.createPlanet(1));
2) Planet.createPlanet(1).setBounds(100, 100, 20, 20);
3) Planet.createPlanet(1).setText("Ello, just testing!");
Run Code Online (Sandbox Code Playgroud)
在第一行.您向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
Run Code Online (Sandbox Code Playgroud)