Search code examples
javaswingjlabellayout-managerboxlayout

How canI make a JLabel be right justified in a box container?


I have a vertical Box I call parent. I add a JLable, then a JTextArea. Next Next I create two vertical Box containers called right and left Next I add 2 JLables to them and put the two box containers in a horizontal Box called Bot. Bot gets added to the parent box I first created

These two labels are drawn next to each other, in the center. The first one is drawn left justified, the second one is right justified.

I want them both right justified so they wont be next to each other code CODE

Box boxParent = Box.createVerticalBox();
      String indName="test";
      String indDescription="Description";

      Box boxTitle = Box.createHorizontalBox();
      boxTitle.add(new JLabel(" Indicater:"));
      boxTitle.add(new JLabel(in    dName));
      boxParent.add(boxTitle);

      JTextArea description = new JTextArea(indDescription,5,2);
      boxParent.add(description);

      Box bot= Box.createHorizontalBox();
      Box right = Box.createVerticalBox();
      right.add(new JLabel("right"));
      right.setAlignmentX(Component.LEFT_ALIGNMENT);
      Box left = Box.createVerticalBox();
      left.setAlignmentX(Component.LEFT_ALIGNMENT);
      left.add(new JLabel("left"));
      bot.add(right);
      bot.add(left);

      boxParent.add(bot);   

Solution

  • I want them both right justified so they wont be next to each other code CODE

    Not sure I understand your requirement. They both can't be right justified since they are on the same line.

    If you want space between the two components maybe you want:

      bot.add(right);
      bot.add(Box.createHorizontalGlue());
      bot.add(left);