Working with Component Alignments : Alignment « Swing JFC « Java






Working with Component Alignments

Working with Component Alignments
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class AlignX {

  private static Container makeIt(String labelChar, float alignment) {
    JPanel container = new JPanel();
    BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
    container.setLayout(layout);

    for (int i = 1; i < 6; i++) {
      String label = makeLabel(labelChar, i * 2);
      JButton button = new JButton(label);
      button.setAlignmentX(alignment);
      container.add(button);
    }
    return container;
  }

  private static String makeLabel(String s, int length) {
    StringBuffer buff = new StringBuffer(length);
    for (int i = 0; i < length; i++) {
      buff.append(s);
    }
    return buff.toString();
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame("X Alignment");
    Container contentPane = frame.getContentPane();

    Container panel1 = makeIt("R", Component.RIGHT_ALIGNMENT);
    Container panel2 = makeIt("C", Component.CENTER_ALIGNMENT);
    Container panel3 = makeIt("L", Component.LEFT_ALIGNMENT);

    contentPane.setLayout(new FlowLayout());
    contentPane.add(panel1);
    contentPane.add(panel2);
    contentPane.add(panel3);

    frame.pack();
    frame.show();
  }
}
           
       








Related examples in the same category

1.Laying Out a Screen with Different Component AlignmentsLaying Out a Screen with Different Component Alignments