JButton in Java Swing

The JButton class is used to create a labeled button that has a platform-independent implementation. The application results in some action when the button is pushed. It inherits AbstractButton class.

Constructors

ConstructorDescription
JButton()Creates a button with no set text or icon.
JButton(Action a)Creates a button where properties are taken from the Action supplied.
JButton(Icon i)Creates a button with an icon.
JButton(String s)Creates a button with text.
JButton(String s, Icon i)Creates a button with initial text and an icon.

Common inherited methods from AbstractButton

MethodDescription
void setText(String s)Sets the text for the button.
String getText()Returns the button text.
void setEnabled(boolean b)It determines whether to enable or disable the button.
void setIcon(Icon i)Sets the button’s default icon.
Icon getIcon()Returns the default icon.
void setMnemonic(int i)Sets the keyboard mnemonic on the current model. The mnemonic is the key which when combined with the look and feel’s mouseless modifier (usually Alt) will activate this button if focus is contained somewhere within this button’s ancestor window.
void addActionListener(ActionListener a)Adds a ActionListener to the button.

Example

public class JButtonDemo {
	public static void main(String[] args) {
		JFrame frame = new JFrame("JButton Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 300);
		frame.setVisible(true);
		frame.setLayout(null);
		
		JButton button = new JButton();
		button.setText("Click me");
		button.setBounds(100, 100, 100, 20);
		frame.add(button);
		
	}
}

Output

Swing JButton
Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments