Java JButton :-
In our previous post, we learned how to create a JFrame in Java. In this article, we will learn how we can create a JButton in java and add it to our JFrame.
The JButton is the class that is used to create a button in a JavaSE application. Use JButton to send actions to your application whenever a user interacts with the button by clicking it.
The class JButton is an implementation of a push button, which can generate an ActionEvent when it is clicked. In order to handle a button click event, the ActionListener interface should be implemented. JButton is a component which extends the JComponent class and it can be added to a container.
Constructors of JButton :
Constructor | Description |
---|---|
public JButton() | Creates a button with no text on it.. |
public JButton(String text) | Creates a button with a text on it. |
public JButton(Icon image) | Creates a button with an icon on it. |
public JButton(String text, Icon image) | Creates a button with a text and an icon on it. |
Methods of JButton class :-
Constructor | Description |
---|---|
public void setText(String text) | Sets a String message on the JButton. |
public String getText() | Gets a String message of JButton. |
public void setIcon(Icon icon) | Sets an icon or image over the JButton. |
void setHorizontalTextPosition(int textPosition). | Sets the button message on the LEFT/RIGHT of its icon or image . |
public Icon getIcon() | Gets the icon or image of the JButton. |
void setVerticalTextPosition(int textPosition) | Sets the button message on the TOP/BOTTOM of its icon or image. |
Class Declaration :-
Following is the declaration for javax.swing.JButton class :
public class JButton
extends AbstractButton
implements Accessible
Methods Inherited
This class inherits methods from the following classes −
- javax.swing.AbstractButton
- javax.swing.JComponent
- java.awt.Container
- java.awt.Component
- java.lang.Object
Java JButton Example :-
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* @author Saurabh
*/
public class buttonex {
public static void main(String[] args) {
JFrame f=new JFrame("Button Frame");
JButton b=new JButton("Button ");
b.setBounds(80,100,97,70);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output :-