Selasa, 04 Oktober 2011

Program ComboBox Java

Contoh program Java berikut ini mendemonstrasikan bagaimana membuat inputan combo box (select box) serta penerapan listener di dalam object Combo Box. Untuk membuat combo box kita dapat menggunakan class JComboBox. Program akan menampilkan pilihan combo box berisi nama-nama file gambar dan jika dipilih maka gambar yang bersangkutan akan ditampilkan.
Berikut ini tampilannya:


01import java.awt.*;
02import java.awt.event.*;
03import javax.swing.*;
04
05public class ComboBoxTest extends JFrame {
06
07    private JComboBox cmbImage;
08    private JLabel label;
09    private String arrGambar[] = {"Blushing.png", "Cool.png", "Happy.png","Smile.png","Winking.png"};
10    private Icon arrIcon[] = { new ImageIcon(arrGambar[0]),
11                   new ImageIcon(arrGambar[1]),
12                   new ImageIcon(arrGambar[2]),
13                   new ImageIcon(arrGambar[3]),
14                   new ImageIcon(arrGambar[4])
15                 };
16
17    public ComboBoxTest() {
18
19        super ("Mencoba Combo Box");
20        Container container = getContentPane();
21        container.setLayout(new FlowLayout());
22        cmbImage = new JComboBox (arrGambar);
23        cmbImage.setMaximumRowCount(3);
24
25        cmbImage.addItemListener(
26            new ItemListener() {
27                public void itemStateChanged (ItemEvent e) {
28                    if (e.getStateChange() == ItemEvent.SELECTED)
29                        label.setIcon(arrIcon[cmbImage.getSelectedIndex()]);
30                }
31            } //end anonimous inner class
32        );
33
34        container.add(cmbImage);
35        label = new JLabel (arrIcon[0]);
36        container.add(label);
37
38        setSize (350,400);
39        setLocationRelativeTo(null);
40        setVisible(true);
41    }
42
43    public static void main (String args[]) {
44        ComboBoxTest test = new ComboBoxTest ();
45        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
46    }
47
48} //end of class



source : google

0 komentar:

Posting Komentar