Pages

Set JButton icon

Complete source code below will show you, how to set icon on JButton.

************************************************************************
COMPLETE SOURCE CODE FOR : SetJButtonIcon.java
************************************************************************


import javax.swing.*;

public class SetJButtonIcon
{
public static void main(String[]args)
{
//Create an image icon from png file named ( callme.png )
//You can download this image below
//This file is locate at same location with this java file.
//If your file locate at other location,
//you must put it's full location address. For example :
//C:\\Documents and Settings\\evergreen\\Desktop\\callme.png
ImageIcon iconForButton=new ImageIcon("callme.png");

//Create a button from JButton with text ( Call me ) and image icon ( callme.png )
JButton button=new JButton("Call me",iconForButton);

//set button horizontal text position to center
//You can select one of the following SwingConstants:
//SwingConstants.CENTER
//SwingConstants.RIGHT
//SwingConstants.LEFT
//SwingConstants.LEADING
//SwingConstants.TRAILING (the default)
button.setHorizontalTextPosition(SwingConstants.CENTER);

//set vertical text position to bottom
//It make our text button locate under button icon
//You can select one of the following SwingConstants:
//SwingConstants.CENTER (the default)
//SwingConstants.TOP
//SwingConstants.BOTTOM
button.setVerticalTextPosition(SwingConstants.BOTTOM);

//Create a window from JFrame with title ( Set JButton icon )
JFrame frame=new JFrame("Set JButton icon");

//Add created button into JFrame
frame.add(button);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(300,150);

//Make JFrame locate at center on screen
frame.setLocationRelativeTo(null);

//Makr JFrame visible
frame.setVisible(true);
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************



callme.png
Related Posts Plugin for WordPress, Blogger...