Friday, 1 August 2014

JAVA - JComboBox aka the java dropdown

We gonna have two images in drop down menu to select , the slected pic icon would be visible in JLabel image



Dont forget to put all pics crap in yours workplace directory to be accessible by the getClass().getResource("pic_name") function

 To add argument to itemSelectListener() or addActionListener()  as object reference  of class implementing respective interfaces , we  made  an  Inner Anonymous class to handle listners 


Main class

import javax.swing.JFrame;

public class Main {
public static void main(String args[]) {

comboBoxes guiB = new comboBoxes();
guiB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set size and visibility of window
guiB.setSize(300, 100);
guiB.setVisible(true);

}

}


ComboBox class -

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class comboBoxes extends JFrame {

// picture
private JLabel picture;
private JComboBox dropDownBox;

// string array for file name
private static String[] filename = { "Capture.PNG", "Untitled.png" };

// icons array for pics
private Icon[] pics = { new ImageIcon(getClass().getResource(filename[0])),
new ImageIcon(getClass().getResource(filename[1])) };

// constructor
public comboBoxes() {
// title of window
super("dropown combo box");

// set layout
setLayout(new FlowLayout());

// initialise dropdown box with option names to be displayed
dropDownBox = new JComboBox(filename);

// add item listener as an object via anonymous class
dropDownBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {

// The object that implements the ItemListener interface ( here
// thru ours anonymous class)
// gets this ItemEvent when the event occurs
if (e.getStateChange() == ItemEvent.SELECTED) {
// change the JLabel icon picture
picture.setIcon(pics[dropDownBox.getSelectedIndex()]);
}

}
}

);


//set default value for JLabel pic icon
picture = new JLabel(pics[0]);

//add dropdown combobox and Jlabel picture to window

add(picture) ; add(dropDownBox);

}



}




No comments:

Post a Comment