1

I am not getting it the way I want it to be. I want all the 10 labels to be arranged in a grid fashion, but I don't get it. Please help me.enter image description here

    JFrame jf=new JFrame("Test me");
    GridLayout gl=new GridLayout(5,5,20,20);
    jf.setLayout(gl);
    jf.setSize(500, 500);
    jf.setVisible(true); 
    JLabel jp =new JLabel("ab");
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
    jf.add(jp);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Aditya Kiran
  • 251
  • 1
  • 4
  • 12
  • 5
    Don't add the same component multiple times . – Arnaud Feb 15 '16 at 16:21
  • @Berger so I have to add different components? – Aditya Kiran Feb 15 '16 at 16:22
  • Yes, add different components . – Arnaud Feb 15 '16 at 16:22
  • yup Thanks A lot... But can I know why it wont work? @Berger – Aditya Kiran Feb 15 '16 at 16:26
  • 2
    You just can' t add one component several times, it will be removed and re-added to its container. If you want several components with the same properties, you have to construct them the same way, but you have to build different objects. The following topic has some more discussion, dealing about two different containers but the logic is the same : http://stackoverflow.com/questions/19697996/adding-the-same-components-to-multiple-panels – Arnaud Feb 15 '16 at 16:31
  • 1
    And call `setVisible` AFTER you've established the UI, otherwise you need to use `revaldiate` and `repaint` – MadProgrammer Feb 15 '16 at 22:23

2 Answers2

3

Firstly,

You cant add same component multiple times because you are referring to the same object... In this case jp always refers to the same object .. Adding the same object multiple times makes the same object to have different properties (i.e. different x and y coordinates) at the same time.. Which wont happen..

As stated by @null saint you need to add JLabel to frame itself.. I was wrong when I told you need to add JLabel to gridlayout..

Vaibhav G
  • 627
  • 5
  • 13
2

Based on your code :-

    JFrame jf=new JFrame("Test me");
    GridLayout gl=new GridLayout(5,5,20,20);
    jf.setLayout(gl);

    jf.setSize(500, 500);
    jf.setVisible(true);

    // create 10 new JLabel
    JLabel jp =new JLabel("ab");
    JLabel jp1 =new JLabel("ab");
    JLabel jp2 =new JLabel("ab");
    JLabel jp3 =new JLabel("ab");
    JLabel jp4 =new JLabel("ab");
    JLabel jp5 =new JLabel("ab");
    JLabel jp6 =new JLabel("ab");
    JLabel jp7 =new JLabel("ab");
    JLabel jp8 =new JLabel("ab");
    JLabel jp9 =new JLabel("ab");

    // add all 10
    jf.add(jp);
    jf.add(jp1);
    jf.add(jp2);
    jf.add(jp3);
    jf.add(jp4);
    jf.add(jp5);
    jf.add(jp6);
    jf.add(jp7);
    jf.add(jp8);
    jf.add(jp9);

    // Packs all components neatly in the Frame
    jf.pack();