[post-views]
In this lesson, you will learn.
JButton
represents a push button that can trigger an action when clicked. It is used for handling events such as clicking or pressing the button.
Constructor | Description |
---|---|
JButton() |
Creates a button with no set text or icon. |
JButton(String text) |
Creates a button with the specified text. |
JButton(Icon icon) |
Creates a button with the specified icon. |
JButton(String text, Icon icon) |
Creates a button with the specified text and icon. |
package jbutton;
import javax.swing.*;
import java.awt.*;
public class JButtonExample1 {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("JButton Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new FlowLayout());
// JButton with no text or icon
JButton button1 = new JButton();
button1.setText("Submit");
button1.setToolTipText("This is Submit Button");
frame.add(button1);
// JButton with text
JButton button2 = new JButton("Reset");
button2.setToolTipText("This is a Reset Button");
frame.add(button2);
// Configure JButton using various methods
button1.setVerticalTextPosition(SwingConstants.BOTTOM);
button1.setHorizontalTextPosition(SwingConstants.CENTER);
button1.setMargin(new Insets(10, 10, 10, 10));
button1.setEnabled(true);
button1.setContentAreaFilled(true);
button1.setBorderPainted(true);
// Make the frame visible
frame.setVisible(true);
}
}
Output
Method | Description |
---|---|
void setText(String text) |
Sets the text of the button. |
String getText() |
Returns the text of the button. |
void setIcon(Icon defaultIcon) |
Sets the icon for the button. |
Icon getIcon() |
Returns the icon of the button. |
void setEnabled(boolean b) |
Enables or disables the button. |
boolean isEnabled() |
Returns the enabled state of the button. |
void setAction(Action a) |
Sets the Action for the button. |
Action getAction() |
Returns the Action for the button. |
void setVerticalTextPosition(int textPosition) |
Sets the vertical position of the text relative to the icon. |
int getVerticalTextPosition() |
Returns the vertical position of the text relative to the icon. |
void setHorizontalTextPosition(int textPosition) |
Sets the horizontal position of the text relative to the icon. |
int getHorizontalTextPosition() |
Returns the horizontal position of the text relative to the icon. |
void setMargin(Insets m) |
Sets the margin between the button’s border and the label. |
Insets getMargin() |
Returns the margin between the button’s border and the label. |
void setToolTipText(String text) |
Sets the tooltip text for the button. |
String getToolTipText() |
Returns the tooltip text for the button. |
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.