0

The only way, as far as I know, to put a JButton or a JLabel is via creating the GUI structure through Containers and placing those components on it.

Are there other methods to add components randomly into the frame and resize accordingly ,as can be done in Visual C# for example? What is the method to do it?

paisanco
  • 4,098
  • 6
  • 27
  • 33
Nipun Alahakoon
  • 2,772
  • 5
  • 27
  • 45
  • 1
    `Are there other methods to add components randomly into the frame and resize accordingly` - That is the point of using layout managers. The layout managers will automatically resize the components as the size of the frame changes. You can use nested layout managers to get your desired layout. Read the Swig tutorial on [Layout Managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) for more information and working examples. – camickr Nov 29 '15 at 18:54
  • 1
    For [example](http://stackoverflow.com/questions/11819669/absolute-positioning-graphic-jpanel-inside-jframe-blocked-by-blank-sections/11822601#11822601) and [example](http://stackoverflow.com/questions/21247833/how-to-prevent-jlabel-positions-from-resetting/21248274#21248274) – MadProgrammer Nov 29 '15 at 20:10
  • yes i can nesting layouts .i was just wondering how to use components without containers on plain frame. thank for the comments though :) – Nipun Alahakoon Nov 30 '15 at 16:42

1 Answers1

0

Yes.
You could use a null Layout and then place components using setBounds().
For example:

JPanel panel = new JPanel(null);
for (int i = 0; i < 4; i++) {
    JButton b = new JButton("JButton-"+i);
    b.setBounds(50+i*10, 50+i*10, 100, 100);
    panel.add(b);
}

If you want random placing, you could random the first 2 (x,y) values.
You will need to provide on your own valid values to be placed inside the parent container.

Leet-Falcon
  • 2,107
  • 2
  • 15
  • 23
  • 2
    Don't use a null layout. The components will NOT resize automatically, that is the job of the layout manager. Swing was designed to be used with layout managers. – camickr Nov 29 '15 at 18:55
  • 1
    That's true, use of null layout is not recommended, but it's one possilbe answer to the OP – Leet-Falcon Nov 29 '15 at 19:03
  • 2
    Yes, well Swing is not Visual C# so we should encourage people to use Swing the way it was designed which means using layout managers. Don't try to force a language to be like another language. If you like the other language so much then use the other language. – camickr Nov 29 '15 at 19:12
  • I took C# just an example. i just wanted to freely handle the controls . otherwise its more of GUI Restricted and sometimes we have to give up on some features because of it – Nipun Alahakoon Nov 30 '15 at 16:40