Java JButton set button label text position

Description

Java JButton set button label text position


import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Graphics;

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

public class Main extends JFrame {
  public Main() {
    super("JButton");

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    Icon icon = new SquareIcon();
    JButton bn = new JButton("Close Button", icon);
    bn.setVerticalTextPosition(AbstractButton.CENTER);
    bn.setHorizontalTextPosition(AbstractButton.LEADING); // aka LEFT, for left-to-right locales

    getContentPane().add(bn);/*  w  w  w .  j  a  v  a2  s.  com*/
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

class SquareIcon implements Icon {
  private static final int SIZE = 10;

  public void paintIcon(Component c, Graphics g, int x, int y) {
    if (c.isEnabled()) {
      g.setColor(Color.RED);
    } else {
      g.setColor(Color.GRAY);
    }

    g.fillRect(x, y, SIZE, SIZE);
  }

  public int getIconWidth() {
    return SIZE;
  }

  public int getIconHeight() {
    return SIZE;
  }
}



PreviousNext

Related