0

I intend to take the elements of an integer list and add it to a label and print them in downward fashion one after another. I wrote the following code for it.

public static JFrame ListDraw(JFrame frame , ArrayList<Integer> e)
{
    for(int i= 0;i<e.size();i++)
    {
        JLabel j = new JLabel(e.get(i).toString(),JLabel.CENTER); 
        frame.add(j);
    }
    return frame;
}

But it just prints the last array element in the label. What am I doing wrong here?

---------------------(update)

This is just a query that I have regarding the same thing. Therefore I am going to ask it here only. Is there any way to print the label items in a stack as in vertical alignment. Right now I get all the values printed in the horizontal fashion.

3
  • Not answering your question, but if I may rant about your API a bit... why are is your method returning a JFrame? If your method is intended to modify one of the arguments, then just modify it. Returning a JFrame implies that it is somehow different than the one supplied by the client; in this case it is not true. You should be returning void or, if you absolutely must return something, some indicator of success/failure. Also, use a lowercase letter to start your method names. Commented Nov 26, 2010 at 21:34
  • Thanks for the rant :) And yes it is actually because I am still a novice programmer. You get to learn new things everyday. Thanks... Commented Nov 26, 2010 at 22:09
  • 1
    Try to use BoxLayout to print the labels vertically or GridLayout if you want the labels to be the same width. Take a look at this manual macs.hw.ac.uk/guidebook/?name=Layouts&page=1 Commented Nov 26, 2010 at 23:01

3 Answers 3

3

I guess you need to set layout for your frame, f.ex: frame.setLayout(new FlowLayout());.

Sign up to request clarification or add additional context in comments.

4 Comments

All fram have an implicit FlowLayout if they haven't been given a different one.
Nope, they have custom layout by default, AFAIK; and yes, setting layout manager would help
Setting layout helps - for me, it appears to be defaulting to BorderLayout...which is why only his last component displays
For reference, the default layout of JFrame is BorderLayout download.oracle.com/javase/6/docs/api/javax/swing/JFrame.html
1

Your frame isn't adapting to the new group of elements- the LayoutManager isn't getting a chance to resize the window. At the end of your function, add frame.pack().

1 Comment

Yep, just tried on my Mac and simply adding frame.pack() call isn't enough.
0

You should use setBounds() to define the size of your frame and give it a LayoutManager of your choice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.