GeeCON Prague 2014*
The moose likes Swing / AWT / SWT and the fly likes Layouts Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Layouts" Watch "Layouts" New topic
Author

Layouts

josephine chen
Ranch Hand

Joined: Oct 29, 2002
Posts: 216
<pre>
import java.awt.*;
import java.awt.event.*;
class btn {
public static void main(String s[]){
Frame w = new Frame();
Panel p = new Panel();
Panel p1 = new Panel();
Panel p2 = new Panel();
Button b = new Button("ok");
Button b1 = new Button("cancel");
Button b2 = new Button("exit");

li l= new li();
b.addActionListener(l);
w.setLayout(new GridLayout(3,1));
w.add(p);
w.add(p1);
w.add(p2);
p2.setBackground(Color.blue);
p2.setLayout(new FlowLayout());
p2.add(b);
p2.add(b1);
p2.add(b2);

p1.setBackground(Color.green);
p1.setLayout(new FlowLayout());
p1.add(b);
p1.add(b1);
p1.add(b2);

p.setBackground(Color.red);
p.setLayout(new FlowLayout());
p.add(b);
p.add(b1);
p.add(b2);
w.setVisible(true);
w.setSize(200,200);

}
}
class li implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("hai");
}
}
</pre>
I just want to dispaly three panels horizontally with diff colors
and each panel must have three btns arranged left to right.
But i am getting in only one panel ie last one.How to rectify it??
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
This is really a Swing / AWT question, so I'm moving the post to that topic.


"I'm not back." - Bill Harding, Twister
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
If you want three different sets of buttons to appear, you need to create three different sets of buttons using new Button(). Right now you're only creating one set of buttons and trying to add it to three different panels, which doesn't work. Each component you create should only be added once to a container. If you want nine buttons, there should be nine new Button() statements. (And nine button.addActionListener() statements.)
Since all three of you panels are nearly identical except for color, you may also want to create them using a loop, or even define a separate class ColoredPanel which you create three times. In that case you'd only write three new Button() statements (one for each button), but those statements would be executed three times, for nine total.
Also, the setVisible() still isn't quite the last statement in the constructor, so you've still got display problems until the user resizes the Frame. Make setVisible() the very last thing in the constructor; it will work better.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Layouts