Francesco Taioli
Francesco Taioli

Reputation: 2856

add JPanel to right or left into JPanel

i work with java swing I've tried witj some layout but they didnt'work. I have a mainPanel that contains some panel,or to the right or to the left ,One below other,obviously.

anyone knows how to do ? thanks to all

enter image description here

Upvotes: 0

Views: 1421

Answers (1)

camickr
camickr

Reputation: 324108

it's a chat app,

If you are just displaying text in the panel you might be able to use a JTextPane with right/left aligned text as shown here: Java Swing JTextArea write both left and right

Or you want can use a GridBagLayout with one component per column. You would then need to use:

  1. the fill constraint on each component so that is fills the width available in the row.
  2. then for each component you would use the anchor constraint so the component is either on the LINE_START or LINE_END.

Read the section from the Swing tutorial on Using a GridBagLayout for more information on each of these constraints.

Or, you could use the Relative Layout which also allows for vertical layout of panels. In this case the code would be something like:

RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setFill(true);
setLayout( rl );

JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT) );
left.add(new JLabel("left"));
add(left);

JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT));
right.add(new JLabel("right"));
add(right);

So you just need to manage the alignment of FlowLayout of each panel.

Upvotes: 3

Related Questions