javacodex.com
Java Examples
Java Examples
memu home questions

JButton

A JButton is also known as a push button or a command button. The user presses or clicks a JButton to perform an action. Typically, it displays text that describes the action it performs when it is clicked.

This example demonstrates how to add an ActionListener to a JButton.

Source: (JButtonExample.java)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
 
public class JButtonExample {
 
  public static void main(String[] arguments) {
 
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("JButton Example");
    f.setSize(400,150);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout(new GridLayout(2,1));
 
 
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());
 
    final JLabel text = new JLabel("Click a button.", JLabel.CENTER);
 
    JButton b1 = new JButton("B1");
    b1.setToolTipText("The B1 button");
 
    JButton quit = new JButton("Quit");
    quit.setToolTipText("The quit button");
 
    quit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        System.exit(0);
      }
    });
 
    b1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        text.setText("B1 Pushed");
      }
    });
 
    buttonPanel.add(b1);
    buttonPanel.add(quit);
    f.add(buttonPanel);
    f.add(text);
 
    f.setVisible(true);
  }
}
 

Output:

$ java JButtonExample
Output



Contact: javacodex@yahoo.com