Java JButton
To use JButton first you need to import it as a swing component.
Java JButton class declaration Syntax
[public class JButton extends AbstractButton implements Accessible]
JButton Common used Constructors
Below are some of the commonly used JButton constructors.
- JButton()-create empty button with no text or icon.
- JButton(String s)-create button with a string
- JButton(Icon icon)-create button with icon.
Common used JButton AbstractButton class methods.
- void setToolTipText(String s)-sets a strings that is displayed whenever user hovers mouse cursor over the button.
- String getText()-returns JButton string.
- void setEnabled(boolean)-enables or disables the JButton.
- void setIcon(Icon icon)-adds icon to JButton.
- Icon getIcon()-retrieves icon used in JButton.
- void setMnemonic(int a)-used to set JButton mnemonic.
- void addActionListener(ActionListener listener)-used to add action listener to the JButton.
Java JButton Example
[
import javax.swing.JFrame; import javax.swing.JButton; public class JavaJButton { public static void main(String args[]) { JFrame frame=new JFrame("Jbutton Example"); JButton button=new JButton("Save"); button.setBounds(50,100,95,30); frame.add(button); frame.setSize(400,400); frame.setLayout(null); frame.setVisible(true); } }
]
Example to Display Icon to the JButton.
[
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.ImageIcon; public class JavaJButton { public static void main(String args[]) { JFrame frame=new JFrame("Jbutton Example"); JButton button=new JButton(); button.setIcon(new ImageIcon(JavaJButton.class.getResource("save.png"))); button.setBounds(100,100,95,30); frame.add(button); frame.setSize(400,400); frame.setLayout(null); frame.setVisible(true); } }
]
Result
Adding ActionListener to JButton
[
Output:
import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.ImageIcon; import javax.swing.JTextField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class JavaJButton { public static void main(String args[]) { JFrame frame=new JFrame("Jbutton Example"); JButton button=new JButton("Save"); JTextField field=new JTextField(); field.setBounds(50,50, 150,20); frame.add(field); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { field.setText("I Love Java"); } }); button.setBounds(100,100,95,30); frame.add(button); frame.setSize(400,400); frame.setLocationRelativeTo(null); frame.setLayout(null); frame.setVisible(true); } }]
Output:
When button is clicked below code is executed that set text in the JTextField to I love Java
[
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { field.setText("I Love Java"); } });
]