Button Label : Label « Swing Components « Java

Button Label

//package com.towel.swing;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractButton;
import javax.swing.UIManager;

public class ButtonLabel extends AbstractButton {
  private String text;
  private int height;

  public ButtonLabel(String text) {
    addMouseListener(new MouseClick());

  public void paintComponent(Graphics g) {
    try {
      Graphics2D g2d = (Graphics2D) g.create();
      g2d.drawString(text, 0, (height + 6) / 2);
    } catch (Exception e) {

  public String getText() {
    return text;

  public void setText(String text) {
    this.text = text;

  private void updateSize() {
    FontMetrics metrics = getFontMetrics(UIManager
    height = metrics.getHeight();
    setPreferredSize(new Dimension(metrics.stringWidth(getText()), height));

  private class MouseClick extends MouseAdapter {
    public void mouseClicked(MouseEvent evnt) {
      for (ActionListener listener : getActionListeners())
        listener.actionPerformed(new ActionEvent(ButtonLabel.this, 0,

    public void mouseEntered(MouseEvent evnt) {
      if (getActionListeners().length == 0)
      setCursor(new Cursor(Cursor.HAND_CURSOR));

    public void mouseExited(MouseEvent evnt) {
      setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

  private Color getColor() {
    return UIManager.getColor("TitledBorder.titleColor");


Related examples in the same category

1.MultiLine Label
2.Multi Line Label extends JComponent
3.Multi Line Label extends JPanel
4.Link Label
5.Vertical Label UI
6.Label with large font and ANTIALIAS paint
7.Label 3D
8.URL Label
9.Hyperlink Label
10.Bevel TextBevel Text
11.A JLabel that can be underlined, implements Scrollable
12.Gradient Label
13.Hyperlink Label 2
14.Computes a reasonable set of labels for a data interval and number of labels.
15.Multi-label Label
16.Shadow Label