• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why the button doesn't appear in th frame?

 
Gong James
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.awt.*;
public class TestFrame extends Frame
{
Button bNorth = new Button("North");
Button bSouth = new Button("South");
Button bEast = new Button("East");
Button bWest = new Button("West");
Button bCenter = new Button("Center");
public TestFrame()
{
setLayout(new FlowLayout());
add(bNorth);
add(bSouth);
add(bWest);
add(bEast);
add(bCenter);
setLayout(new BorderLayout());
validate();
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
TestFrame tf = new TestFrame();
}
}
When I compile and run the code above , but no component is visible,Why?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you start out using FlowLayout, add components, then change to BorderLayout and re-validate. You shouldn't do this... stick to one layout manager per container.

-Nate
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gong,
Nathan gave you the short answer, now I will explain to you why.
If you look at the FlowLayout and BorderLayout classes you can see that each one implements a slightly different LayoutManager interface (i.e., BorderLayout implements LayoutManager2 while FlowLayout implements LayoutManager). The main difference between LayoutManager and LayoutManager2 is that LayoutManager2 requires component to be added with constraints. No constraints, no component layout! Knowing this we can see by your code that you are adding components into FlowLayout without constraints. That is the correct way because FlowLayout implements LayoutManager. Then you change your layout to BorderLayout. Since no components have constraints, the LayoutManager2 ignores them, hence no components show up.
It is good programming practice to set your layout manager at the beginning and add the components correctly with regard to the layout manager.
Regards,
Manfred.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!