0

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

Francesco Taioli
  • 2,687
  • 1
  • 19
  • 34
  • grid or gridbag layout... grid: all cells have same dimension, one child in one cell, one child max per cell. gridbag: slightly more complex. Use grid, 2x2, with one panel at (1,0), the other at (0,1). – Jean-Baptiste Yunès May 23 '16 at 18:27
  • but the number of pane are undefined, they can be 14 or 100 – Francesco Taioli May 23 '16 at 18:30
  • Then create a gridlayout accordingly at the time you know the number of panes, what is the problem? – Jean-Baptiste Yunès May 23 '16 at 18:32
  • it's a chat app, I can't know the number of message :) – Francesco Taioli May 23 '16 at 18:33
  • Hey, now you begin to give us some good information about your needs... The trick is that you also need some scrolling... Use a scrollpane with a panel that use a gridlayout, and change the gridlayout when you need, you can start with say 100 lines (don't worry if ending lines are unused, and when construct another gridlayout when it grows... But I think you need to create your own layout/component to handle these more properly... – Jean-Baptiste Yunès May 23 '16 at 19:07
  • can you help me?can you give me an example of code for my own layout? – Francesco Taioli May 23 '16 at 19:54

1 Answers1

3

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.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288