Share on Google+Share on Google+

Create Multiple Buttons

In this section, you will learn how to create multiple buttons labeled with the letters from A to Z respectively.

Create Multiple Buttons using Java Swing


In this section, you will learn how to create multiple buttons labeled with the letters from A to Z respectively. To display them, we have created an array of letters. Using this array, we have labeled the buttons. Now to perform an action on these buttons, we have used the following code:

buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
JOptionPane.showMessageDialog(null, "You have clicked: "+choice);

Here is the code of

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class DisplayButtonMessage extends JFrame {
int i=0;
static JPanel panel;
public DisplayButtonMessage(){
JButton[] buttons = new JButton[26];
panel=new JPanel(new GridLayout(4,6));
String  b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
for(i = 0; i < buttons.length; i++) {
buttons[inew JButton(b[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
  String choice = e.getActionCommand();
 JOptionPane.showMessageDialog(null, "You have clicked: "+choice);
public static void main(String[]args){
DisplayButtonMessage frame=new DisplayButtonMessage();

Output will be displayed as:

On clicking the button 'A', it will show a message:

Download  Source Code:



Posted on: October 15, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Create Multiple Buttons  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
selvin jayakumar
March 15, 2013
java swing

this website is very useful for us to learn more thing.
May 22, 2012
images on button arrays

Hi, Can I ask a question? How can load images on button array instead of letters(A,B,C...). However; different images can be on different buttons like a puzzle. Can you give a link or example code to try out my problem.
Sana Bukhari
May 23, 2012
Not working

hey your code isn't working. It runs but no button is displayed :(
December 14, 2012

thnx you for sharing information