Java Swing How to - Put text on top of a image in a button








Question

We would like to know how to put text on top of a image in a button.

Answer

import java.awt.Graphics;
/*from   ww w.ja v a  2s .  c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel pnl = new JPanel();
    pnl.add(new MyButton());
    frame.add(pnl);
    frame.setSize(600, 600);
    frame.setVisible(true);
  }

}

class MyButton extends JButton {
  public void paint(Graphics g) {
    // draw image
    // the draw text
  }
}