Java JButton with image and text
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Main extends JFrame { private final JButton okButton; // button with just text private final JButton fancyJButton; // button with icons // Main adds JButtons to JFrame public Main() { super("Testing Buttons"); setLayout(new FlowLayout()); okButton = new JButton("OK"); add(okButton); // add okButton to JFrame Icon bug1 = new ImageIcon(getClass().getResource("1.gif")); Icon bug2 = new ImageIcon(getClass().getResource("2.gif")); fancyJButton = new JButton("Button", bug1); fancyJButton.setRolloverIcon(bug2); // set rollover image add(fancyJButton); // add fancyJButton to JFrame // create new ButtonHandler for button event handling ButtonHandler handler = new ButtonHandler(); fancyJButton.addActionListener(handler); okButton.addActionListener(handler); }//from w ww. j a v a 2s . c o m // inner class for button event handling private class ButtonHandler implements ActionListener { // handle button event @Override public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(Main.this, String.format("You pressed: %s", event.getActionCommand())); } } public static void main(String[] args) { Main Main = new Main(); Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main.setSize(275, 110); Main.setVisible(true); } }