Introducere în JButton în Java
Clasa JButton din Java este utilizată pentru a crea butoane care pot fi utilizate pentru a efectua orice ActionEvent ori de câte ori este dat clic. Pentru a realiza acțiunea evenimentului, trebuie implementată interfața ActionListener. Componenta Butoane din Swing este similară cu cea a componentei butonului AWT, cu excepția faptului că poate conține text, imagine sau ambele. Clasa JButton extinde clasa JComponent și poate fi utilizată într-un container.
Declarația de clasă JButton
Declarația clasei javax.swing.JBtonton este mai jos:
public class JButton extends AbstractButton implements Accessible
Tipuri de constructori folosiți în clasa JButton
Există cinci tipuri de constructori utilizați practic în clasa JButton:
1. JButton ()
Acest constructor va crea un buton în componentă fără pictogramă sau text.
Exemplu
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);
)
)
ieşire:
2. JButton (text cu șiruri)
Acest constructor va crea un buton în componentă, cu textul specificat în parametri.
Exemplu
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);
)
)
ieşire:
3. JButton (pictograma img)
Acest constructor va crea un buton în componentă cu imaginea img dată în parametri.
Exemplu
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.webp"));
frame.add(b);
frame.setSize(500, 500);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
)
)
ieşire:
4. JButton (acțiunea a)
Acest constructor va crea un buton în componentă cu proprietățile furnizate de Action an în parametru.
Exemplu
importawt.*;
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);
)
)
ieşire:
5. JButton (text cu șiruri, pictogramă img)
Acest constructor va crea un buton în componentă cu textul și imaginea specificată în parametri.
Exemplu
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.webp"));
frame.add(b);
frame.setSize(500, 500);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
)
)
ieşire:
Metode de clasă JButton
Mai jos sunt metodele utilizate în mod obișnuit în clasa JButton:
- Void setText (text text): Această metodă este utilizată în principiu pentru a seta textul specificat pe butonul componentei.
- String getText (): această metodă este utilizată pentru a returna textul butonului în componenta specificată.
- Void setEnabled (boolean b): Această metodă este utilizată pentru a activa sau dezactiva un buton trecând valoarea corespunzătoare în parametru.
- Void setIcon (pictograma i): Această metodă este utilizată pentru a seta pictograma „I” specificată pe buton.
- Pictograma getIcon (): Această metodă este utilizată pentru a returna pictograma butonului specificat.
- Void setHorizontalTextPosition (int hpos): Această metodă este utilizată pentru a seta poziția orizontală a mesajului butonului în raport cu pictograma sa.
- Void stVerticalTextPosition (int vpos): Această metodă este utilizată pentru a seta poziția verticală a mesajului butonului în raport cu pictograma sa.
Exemplu de clasă JButton
Mai jos este exemplul clasei JButton:
Operațiunea CRUD pe JTable
package jbuttonapplication;
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
)
ieşire:
Concluzii - JButton în Java
Clasa JButton poate fi utilizată pentru a crea o componentă de buton pentru a efectua modificările componentei într-un mod dinamic precum exemplul de mai sus.
Articole recomandate
Acesta este un ghid pentru JButton în Java. Aici discutăm tipurile de constructori folosiți în clasa JButton împreună cu Metode și Exemplu. Puteți parcurge și alte articole sugerate pentru a afla mai multe -
- JTextField în Java
- JDialog în Java
- BorderLayout în Java
- CardLayout în Java
- JPanel în Java (Constructori)
- GroupLayout în Java
- Exemple de JFrame în Java
- JLabel în Java
- Ghid complet pentru Flowlayout în Java
- Metode și programe JTable în Java