简体   繁体   中英

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

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM