Java Swing How to - Change label alignments for JButton








Question

We would like to know how to change label alignments for JButton.

Answer

/*from  w  w  w  . jav a2  s.c o  m*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;

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

    JButton b;
    Icon icon = new PieIcon(Color.red);
    b = new JButton("Default", icon);
    contentPane.add(b, BorderLayout.NORTH);
    b = new JButton("Text Left", icon);
    b.setHorizontalTextPosition(JButton.LEFT);
    contentPane.add(b, BorderLayout.SOUTH);
    b = new JButton("Text Up", icon);
    b.setHorizontalTextPosition(JButton.CENTER);
    b.setVerticalTextPosition(JButton.TOP);
    contentPane.add(b, BorderLayout.EAST);
    b = new JButton("Text Down", icon);
    b.setHorizontalTextPosition(JButton.CENTER);
    b.setVerticalTextPosition(JButton.BOTTOM);
    contentPane.add(b, BorderLayout.WEST);
    b = new JButton("Align Bottom Left", icon);
    b.setHorizontalAlignment(JButton.LEFT);
    b.setVerticalAlignment(JButton.BOTTOM);
    contentPane.add(b, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.show();
  }
}

class PieIcon implements Icon {
  Color color;

  public PieIcon(Color c) {
    color = c;
  }

  public int getIconWidth() {
    return 20;
  }

  public int getIconHeight() {
    return 20;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(color);
    g.fillArc(x, y, getIconWidth(), getIconHeight(), 45, 270);
  }
}