I want to add a componet to a container(suppose Jframe)in runtime. I tried with the following code but it didnt work. I wanted to add a JLabel to a JFrame in run time but it didnt work.Actually I want to add several JLabels in runtime Pls anybody tell me when ,how and where(in a class)to call repaint method and differece between repaint/revalidate/paint method. Pls help me. My code is give below- import java.awt.*; import javax.swing.*;
public class GantChart extends JFrame { JLabel jLabel1 = new JLabel(); JPanel jPanel1 = new JPanel();
public static void main(String[] args) { GantChart gantChart = new GantChart(); gantChart.getContentPane().setLayout(null); gantChart.setSize(new Dimension(422, 331)); gantChart.setBackground(Color.cyan);
You DO know that you created 4 new labels? You have to add jLabel1 to the frame, and should not create a new label for every step.
At the end you added one new label without any formatting or displaying text. It's just not visible, that's all. You should also define where you want to put it (depending on the layout manager).
btw: EVERY component is added during runtime, there's just no other way to do it.
One more thing: You used the CODE tag to display your program code below. That's more than many of the other users here do, but for Java code it's better if you use the JAVA tag. This way you get syntax highlighting and all the leading space characters in your code.
What actually I want to say is dat- How can I add a number of components in a loop(for/while)Like the following- for(int a =1;a<10;a++) { add(new JLabel();) } It will only create some objets .But what if I want to set the background color,text,size,location(setBounds) and anything else for each instance of dat component and add it to the container during runtime.I hope u get me now.
Well, you have to access the EXISTING label, in your example you created a new label for every step.
There are two ways:
for(int a =1;a<10;a++)
{
JLabel tempLabel= new JLabel();
tempLabel.set ...
add(tempLabel);
}
The other way would be just adding all the labels to the frame, then accessing them using the getComponent() method of the frame. Way 1 is clearly better.