Friday, June 15, 2012

Create Dynamic JButton with Image and ActionListener - Java Swing

0 comments
In this tutorial you will learn how to create JButton dynamically with Image and the ActionListener . You will be able to change the button height , width horizontal gap and vertical gap in one place.

I have create dummy database class which will return the Main menu items and the Sub menu items.You will see the Main menu item in your JFrame. If you select main Item (FOOD) from the button panel it will load Sub Items from the dummy database class (sub items of the FOOD)


Here are the screen shots

Main menu items


Sub menu items


Create Main Frame


Open NetBeans and create New Project, name it as
DynamicButton

  • Add New JFrame Form give class name as DynamicSwingButton
  • Add these code to your DynamicSwingButton class and import relevant classes and interfaces
  private final static int button_width   =   145;        // button width
private final static int button_height = 140; // button height
private final static int horizontalGap = 10; // horizontal gap in button
private final static int verticalGap = 10; // verticle gap in button
private final static int numberOfColumns= 4; // number of colums in the button panel
private final static int fontSize = 11; // font size of button name
private final static int fontType = Font.BOLD; // font type
private final static String fontName = "Thoma"; // font name
private final static Color fontColor = new Color(0, 51, 255); // font colot

  • Add Scroll Pane to your Frame from the palette and set the height and width to Scroll Pane
  • Add JPanel to the Scroll Pane and change the panel variable name as pnl_button
  • Add bellow function to your DynamicSwingButton class
    private void addMainMenue() {

pnl_button.removeAll();
repaint();

Image img, sub;
ImageIcon icon;
String imagePath,imag = "/com/images/";

ArrayList menue = new ArrayList();
ArrayList itemName = new ArrayList();

for (int size = 0 ; size<ItemDB.mainMenuCodes.length; size++) {
menue.add(ItemDB.mainMenuCodes[size]);
itemName.add(ItemDB.mainMenuDesc[size]);
}

JButton[] buttons = new JButton[menue.size()];

for (int i = 0; i < buttons.length; i++) {

imagePath = imag+menue.get(i).toString()+".jpeg";

URL url = getClass().getResource(imagePath);
// System.out.println(imagePath +" Get Res : " +getClass().getResource(imagePath));

if(url!=null){
img = Toolkit.getDefaultToolkit().getImage(url);
sub = img.getScaledInstance(button_width - 8, button_height - 30, Image.SCALE_FAST);
icon = new ImageIcon(sub);
}
else
icon = new ImageIcon();

buttons[i] = new JButton(itemName.get(i).toString(), icon);
buttons[i].setVerticalTextPosition(AbstractButton.BOTTOM);
buttons[i].setHorizontalTextPosition(AbstractButton.CENTER);

buttons[i].setBorder(javax.swing.BorderFactory.createEtchedBorder());
buttons[i].setFont(new java.awt.Font("Tahoma", 1, 13));
buttons[i].setForeground(new java.awt.Color(0, 51, 255));

buttons[i].setActionCommand(menue.get(i).toString());
buttons[i].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
addSubmenue(choice);
}
});
}

int b = 0;
int vGap = verticalGap;
int hGap = horizontalGap;
int bLength = buttons.length;
int bRows = bLength/numberOfColumns +1;

L1: for (int j = 0; j <bRows; j++) {
vGap = 10;
for (int k = 0; k < numberOfColumns; k++) {

pnl_button.add(buttons[b], new org.netbeans.lib.awtextra.AbsoluteConstraints(vGap, hGap, button_width, button_height));
repaint();
vGap +=button_width+verticalGap;
b++;
if(b>=bLength){
break L1;
}
}
hGap +=button_height+horizontalGap;
}
pack();
}

private void addSubmenue(String choice) {
pnl_button.removeAll();
repaint();

Image img, sub;
ImageIcon icon;
String imagePath,imag = "/com/images/";

ArrayList menue = new ArrayList();
ArrayList itemName = new ArrayList();

ArrayList list = ItemDB.getSubMenu(choice);
String subCode[] = (String[]) list.get(0);
String subDesc[] = (String[]) list.get(1);

for (int size = 0 ; size<subCode.length; size++) {
menue.add(subCode[size]);
itemName.add(subDesc[size]);
}

JButton[] buttons = new JButton[menue.size()];

for (int i = 0; i < buttons.length; i++) {

imagePath = imag+menue.get(i).toString()+".jpeg";

URL url = getClass().getResource(imagePath);
// System.out.println(imagePath +" Get Reso : " +getClass().getResource(imagePath));

if(url!=null){
img = Toolkit.getDefaultToolkit().getImage(url);
sub = img.getScaledInstance(button_width - 8, button_height - 30, Image.SCALE_FAST);
icon = new ImageIcon(sub);
}
else
icon = new ImageIcon();



buttons[i] = new JButton(itemName.get(i).toString(), icon);
buttons[i].setVerticalTextPosition(AbstractButton.BOTTOM);
buttons[i].setHorizontalTextPosition(AbstractButton.CENTER);

buttons[i].setBorder(javax.swing.BorderFactory.createEtchedBorder());
buttons[i].setFont(new java.awt.Font("Tahoma", 1, 13));
buttons[i].setForeground(new java.awt.Color(0, 51, 255));


buttons[i].setActionCommand(menue.get(i).toString());
buttons[i].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
addItems(choice);
}
});
}
int b = 0;
int vGap = verticalGap;
int hGap = horizontalGap;
int bLength = buttons.length;
int bRows = bLength/numberOfColumns +1;

L1: for (int j = 0; j <bRows; j++) {
vGap = 10;
for (int k = 0; k < numberOfColumns; k++) {

pnl_button.add(buttons[b], new org.netbeans.lib.awtextra.AbsoluteConstraints(vGap, hGap, button_width, button_height));
repaint();
vGap +=button_width+verticalGap;
b++;
if(b>=bLength){
break L1;
}
}
hGap +=button_height+horizontalGap;
}
pack();
}

private void addItems(String choice) {

if(choice.equals("P"))
choice = "PIZZA";
else if(choice.equals("B"))
choice = "BURGER";
else if(choice.equals("FJ"))
choice = "FRUIT JUICE";
else if(choice.equals("HB"))
choice = "HOT BEVERAGES";
JOptionPane.showMessageDialog(this, "You have select "+choice);
}


  • Go to Window->Navigating-> Inspector, Right Click your Frame and add window open event



  • Add this function to windows opened event
    addMainMenue();

  • Add tow buttons and name one as Back and another as Exit
  • Select Back button and add Action performed event with addMainMenue(); function
  • Select Exit button and add Action performed event with System.exit(0);
  • Add this dummy database class to your project



import java.util.ArrayList;

/**
*
* @author JSupport
*/
class ItemDB {

public static String mainMenuCodes[] = {"FOOD","BEVE","FOOD","BEVE","FOOD","BEVE"};
public static String mainMenuDesc[] = {"FOOD","BEVERAGES","FOOD","BEVERAGES","FOOD","BEVERAGES"};
private static ArrayList list;

public static ArrayList getSubMenu(String mainMenuCodes){

list = new ArrayList();
if(mainMenuCodes.equals("FOOD")){
String subCode[] = {"P","B"};
String subDesc[] = {"PIZZA","BURGER"};

list.add(subCode);
list.add(subDesc);

}else if(mainMenuCodes.equals("BEVE")){
String subCode[] = {"FJ","HB"};
String subDesc[] = {"Fruit Juice","Hot Beverages"};

list.add(subCode);
list.add(subDesc);
}
return list;
}
}

  • Run the DynamicSwingButton frame.

0 comments:

Post a Comment