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:
02 | import java.awt.event.*; |
05 | public class ComboBoxTest extends JFrame { |
07 | private JComboBox cmbImage; |
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 ]) |
17 | public ComboBoxTest() { |
19 | super ( "Mencoba Combo Box" ); |
20 | Container container = getContentPane(); |
21 | container.setLayout( new FlowLayout()); |
22 | cmbImage = new JComboBox (arrGambar); |
23 | cmbImage.setMaximumRowCount( 3 ); |
25 | cmbImage.addItemListener( |
27 | public void itemStateChanged (ItemEvent e) { |
28 | if (e.getStateChange() == ItemEvent.SELECTED) |
29 | label.setIcon(arrIcon[cmbImage.getSelectedIndex()]); |
34 | container.add(cmbImage); |
35 | label = new JLabel (arrIcon[ 0 ]); |
39 | setLocationRelativeTo( null ); |
43 | public static void main (String args[]) { |
44 | ComboBoxTest test = new ComboBoxTest (); |
45 | test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
0 komentar:
Posting Komentar