首页javajbuttonJava Swing - 如何更改JButton的标签对齐方式

Java Swing - 如何更改JButton的标签对齐方式

我们想知道如何更改JButton的标签对齐方式。
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);
  }
}