0

I am trying to add buttons to a Frame which I am trying in two ways.

  1. Changing the Layout of JPanel and then adding buttons directly to the panel. (Commented section in below code). Then I am adding the panel to a frame. This approach worked and it shows buttons in a JFrame.

  2. Creating a BorderLayout, adding buttons using addLayoutComponents() method. Then adding this bl (BorderLayout reference) to the panel and then JFrame. Why is this approach not showing buttons in the frame? Where did I go wrong?

Can anyone help me in learning AWT components? I mean what to read first and sequence of concepts .

jf = new JFrame();
jp= new JPanel(new BorderLayout());

 /*jp.add(new JButton("North"), BorderLayout.NORTH);
 jp.add(new JButton("South"), BorderLayout.SOUTH);
 jp.add(new JButton("East"), BorderLayout.EAST);
 jp.add(new JButton("West"), BorderLayout.WEST);
 jp.add(new JButton("Center"), BorderLayout.CENTER);
 jf.add(jp);
 */

 BorderLayout bl = new BorderLayout();

 bl.addLayoutComponent(new JButton("North"), BorderLayout.NORTH);
 bl.addLayoutComponent(new JButton("South"), BorderLayout.SOUTH);
 bl.addLayoutComponent(new JButton("East"), BorderLayout.EAST);
 bl.addLayoutComponent(new JButton("West"), BorderLayout.WEST);
 bl.addLayoutComponent(new JButton("Center"), BorderLayout.CENTER);
 jp.setLayout(bl);
 jf.add(jp);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • *"Can anyone help me in learning AWT **components**?"* While the AWT is still useful for things like layouts, colors and fonts, leave the AWT based components alone. They have been entirely replaced by (better) Swing equivalents. Or as I put it in one of my common copy/paste comments: Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT components in favor of Swing. – Andrew Thompson Feb 11 '17 at 04:46

1 Answers1

3

The second way is not working because it's wrong. You shouldn't be adding components directly to the layout manager but rather to the container that uses the layout manager as is well outlined in the layout manager tutorial here: Layout Manager Tutorial. Per the BorderLayout API, you the coder shouldn't directly call the addLayoutComponent method, but rather it is called indirectly by the container itself when components are added to the container. The method adds the component to the layout but not to the container itself, and that's a key difference.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thanks Hovercraft Full Of Eels. But what is the purpose of addLayoutComponent . If this should not be used explicitly by coder. – Elisetty Narendra Feb 11 '17 at 03:46
  • Again, it is used by the container that has been assigned that layout manager. Since it is used by an outside class, it must be public. But again, the tutorials explain well how to use the layouts, why not start there? – Hovercraft Full Of Eels Feb 11 '17 at 03:54