Updated March 28, 2023
Introduction to JButton in Java
JButton class in Java is used to create push buttons that can be used to perform any ActionEvent whenever it is clicked. In Order to achieve event action, the ActionListener interface needs to be implemented. The Buttons component in Swing is similar to that of the AWT button component except that it can contain text, image or both. The JButton class extends the JComponent class and can be used in a container.
JButton Class Declaration
The Declaration of javax.swing.JButton class is below:
public class JButton extends AbstractButton implements Accessible
Types of Constructors Used in JButton Class
There are five types of constructors basically used in JButton Class:
1. JButton()
This constructor will create a button in the component with no icon or text.
Example
import java.awt.*;
import javax.swing.*;
public class JButtonExample {
public static void main(String[] args) {
JFrame frame=new JFrame("Button Example");
JButton b=new JButton();
b.setPreferredSize(new Dimension(100,30));
frame.add(b);
frame.setSize(500,500);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Output:
2. JButton(String text)
This constructor will create a button in the component with the specified text in the parameters.
Example
import java.awt.*;
import javax.swing.*;
public class JButtonExample {
public static void main(String[] args) {
JFrame frame=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setPreferredSize(new Dimension(100,30));
frame.add(b);
frame.setSize(500,500);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Output:
3. JButton(Icon img)
This constructor will create a button in the component with the image img given in the parameters.
Example
import java.awt.*;
import javax.swing.*;
public class JButtonExample {
public static void main(String[] args) {
JFrame frame=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("C:\\custom.png"));
frame.add(b);
frame.setSize(500,500);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Output:
4. JButton(Action a)
This constructor will create a button in the component with the properties supplied by the Action an in the parameter.
Example
import awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class JButtonExample extends JFrame{
private JButton reg;
private Action action = new buttonAction();
public JButtonExample() {
super("JButton Demo example");
setLayout(new FlowLayout());
reg = new JButton(action);
reg.setPreferredSize(new Dimension(100,30));
add(reg);
}
public class buttonAction extends AbstractAction{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"Button click");
}
}
public static void main(String[] args) {
JButtonExample jb = new JButtonExample();
jb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jb.setSize(300, 300);
jb.setVisible(true);
}
}
Output:
5. JButton(String text, Icon img)
This constructor will create a button in the component with the text and specified image in the parameters.
Example
import java.awt.*;
import javax.swing.*;
public class JButtonExample {
public static void main(String[] args) {
JFrame frame=new JFrame("Button Example");
JButton b=new JButton("Click here",new ImageIcon("C:\\custom.png"));
frame.add(b);
frame.setSize(500,500);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Output:
Methods of JButton Class
Below are the commonly used methods in JButton Class:
- Void setText(string text): This method is basically used to set specified text on the button in the component.
- String getText( ): This method is used to return the text of the button in the specified component.
- Void setEnabled(boolean b): This method is used to enable or disable a button by passing the appropriate value in the parameter.
- Void setIcon(icon i): This method is used to set the specified icon “I” to the button.
- Icon getIcon( ): This method is used to return the icon of the specified button.
- Void setHorizontalTextPosition(int hpos): This method is used to set the horizontal position of the button message with respect to its icon.
- Void stVerticalTextPosition(int vpos): This method is used to set the vertical position of the button message with respect to its icon.
Example of JButton Class
Below is the example of the JButton class:
CRUD Operation on JTable
package jbutton application;
import javax.swing.table.DefaultTableModel;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
rno = new javax.swing.JTextField();
fname = new javax.swing.JTextField();
lname = new javax.swing.JTextField();
add = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jbtable = new javax.swing.JTable();
jbnew = new javax.swing.JButton();
jbadd = new javax.swing.JButton();
jbupdate = new javax.swing.JButton();
jbdelete = new javax.swing.JButton();
label = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Roll No");
jLabel2.setText("First Name");
jLabel3.setText("Last Name");
jLabel4.setText("Address");
jbtable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Roll No", "First Name", "Last Name", "Address"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jbtable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jbtableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(jbtable);
jbnew.setText("New");
jbnew.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbnewActionPerformed(evt);
}
});
jbadd.setText("Add");
jbadd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbaddActionPerformed(evt);
}
});
jbupdate.setText("Update");
jbupdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbupdateActionPerformed(evt);
}
});
jbdelete.setText("Delete");
jbdelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbdeleteActionPerformed(evt);
}
});
label.setForeground(new java.awt.Color(204, 0, 0));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(136, 136, 136)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jbnew))))
.addGap(37, 37, 37)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(rno, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
.addComponent(fname)
.addComponent(lname)
.addComponent(add))
.addGap(32, 32, 32)
.addComponent(label, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jbadd)
.addGap(46, 46, 46)
.addComponent(jbupdate)
.addGap(74, 74, 74)
.addComponent(jbdelete))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(177, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(117, 117, 117)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(label))
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(fname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(lname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(46, 46, 46)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jbnew)
.addComponent(jbadd)
.addComponent(jbupdate)
.addComponent(jbdelete))
.addGap(52, 52, 52)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(328, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}
private void jbnewActionPerformed(java.awt.event.ActionEvent evt) {
rno.setText("");
fname.setText("");
lname.setText("");
add.setText("");
}
private void jbaddActionPerformed(java.awt.event.ActionEvent evt) {
label.setText("");
DefaultTableModel model = (DefaultTableModel)jbtable.getModel();
if(!rno.getText().isEmpty()&&!fname.getText().isEmpty()
&&!lname.getText().isEmpty()&&!add.getText().isEmpty())
{
model.addRow(new Object[]{rno.getText().trim(),fname.getText().trim(),
lname.getText().trim(),add.getText().trim()});
}
else
{
label.setText("All the fields should be filled");
}
}
private void jbtableMouseClicked(java.awt.event.MouseEvent evt) {
DefaultTableModel model = (DefaultTableModel)jbtable.getModel();
rno.setText(model.getValueAt(jbtable.getSelectedRow(), 0).toString());
fname.setText(model.getValueAt(jbtable.getSelectedRow(), 1).toString());
lname.setText(model.getValueAt(jbtable.getSelectedRow(), 2).toString());
add.setText(model.getValueAt(jbtable.getSelectedRow(), 3).toString());
}
private void jbupdateActionPerformed(java.awt.event.ActionEvent evt) {
label.setText("");
DefaultTableModel model = (DefaultTableModel)jbtable.getModel();
if(jbtable.getSelectedRow()==-1)
{
if(jbtable.getRowCount()==0)
{
label.setText("Table is Empty");
}
else
{
label.setText("No Row Selected to Update");
}
}
else
{
model.setValueAt(rno.getText(), jbtable.getSelectedRow(), 0);
model.setValueAt(fname.getText(), jbtable.getSelectedRow(), 1);
model.setValueAt(lname.getText(), jbtable.getSelectedRow(), 2);
model.setValueAt(add.getText(), jbtable.getSelectedRow(), 3);
}
}
private void jbdeleteActionPerformed(java.awt.event.ActionEvent evt) {
label.setText("");
DefaultTableModel model = (DefaultTableModel)jbtable.getModel();
if(jbtable.getSelectedRow()==-1)
{
if(jbtable.getRowCount()==0)
{
label.setText("Table is Empty");
}
else
{
label.setText("No Row Selected to Update");
}
}
else
{
model.removeRow(jbtable.getSelectedRow());
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField add;
private javax.swing.JTextField fname;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton jbadd;
private javax.swing.JButton jbdelete;
private javax.swing.JButton jbnew;
private javax.swing.JTable jbtable;
private javax.swing.JButton jbupdate;
private javax.swing.JLabel label;
private javax.swing.JTextField lname;
private javax.swing.JTextField rno;
// End of variables declaration
}
Output:
Conclusions – JButton in Java
JButton class can be used to create a button component to perform the changes to the component in a dynamic way like the above example.
Recommended Articles
This is a guide to JButton in Java. Here we discuss the types of constructors used in JButton Class along with Methods and examples. You can also go through our other suggested articles to learn more –