Home Java Example Java Swing Create Multiple Buttons
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Create Multiple Buttons

Advertisement
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].setActionCommand(b[i]);
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 DisplayButtonMessage.java

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",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++) {
buttons[inew JButton(b[i]);
buttons[i].setSize(8080);
buttons[i].setActionCommand(b[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
  String choice = e.getActionCommand();
 JOptionPane.showMessageDialog(null, "You have clicked: "+choice);
  }
});
panel.add(buttons[i]);
}
}
public static void main(String[]args){
DisplayButtonMessage frame=new DisplayButtonMessage();
frame.add(panel);
frame.pack();
frame.setVisible(true);
 }
}

Output will be displayed as:

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

Download  Source Code:

Advertisement

Liked it!  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.

Posted on: October 15, 2009

Ask Questions?    Discuss: Create Multiple Buttons  

Post your Comment


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

this website is very useful for us to learn more thing.
figen
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 :(
imran
December 14, 2012
jdfsd

thnx you for sharing information
DMCA.com