Perdorimi i klases JComboBox

Nje JComboBox eshte nje komponent qe shfaq nje osion default dhe nj liste me opsione nese klikohet ne butonin djathtas.

 

Hierarkia e klasave:

|_ java.lang.Object

   |_ java.awt.Component

       |_ java.awt.Container

           |_ javax.swing.JComponent

               |_ javax.swing.JComboBox

 

Deklarimi dhe shtimi i elementeve:

Menyra 1:

JComboBox majorChoice = new JComboBox();

majorChoice.addItem("English");

majorChoice.addItem("Math");

majorChoice.addItem("Sociology");

Menyra 2:

String[] majorArray = {"English", "Math", "Sociology"};

JComboBox majorChoice = new JComboBox(majorArray);

 

Metoda te perdorimit te JComboBox:

void addItem(Object) Shton nje njesi ne liste

void removeItem(Object) Heq nje njesi nga lista

void removeAllItems()  Heq gjithe njesite nga lista

Object getItemAt(int) Kthen njesine e listes ne indeksin e caktuar

 

int getItemCount() Kthen  numrin e njesive ne liste

 

int getMaximumRowCount()  Kthen numrin maksimal te elementeve qe duhet te mbaje nje combo box pa perdorur scroll bar

int getSelectedIndex() Kthen pozicionin e elementit te zgjedhur

 

Object getSelectedItem() Kthen elementin aktual te zgjedhur

 

Object[] getSelectedObjects() Kthen nje vektor me objektet e zgjedhur

 

void setEditable(boolean) E ben te editueshem ose jo fushen ne combo box

 

void setMaximumRowCount(int) Vendos numrin e rreshtave ne combo box qe mund te shfaqen ne nje kohe.

 

void setSelectedIndex(int) Zgjedh indeksin ne pozicionin e caktuar.

 

void setSelectedItem(Object) Vendos elementin e zgjedhur ne zonen e afishimit combo box  te jete ne argumentin object.

 

Perdorimi:

p.sh:

int positionOfSelection = historyChoice.getSelectedIndex();

Shembull:


     import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class ComboBoxDemo extends JFrame implements ActionListener

{

FlowLayout flow = new FlowLayout();

String[] lendet = {"English", "Math", "Sociology"};

JComboBox combo = new JComboBox(lendet);

 

public ComboBoxDemo()

{

super("ComboBox Demonstration");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

 

add(combo);

combo.addActionListener(this);

}

public void actionPerformed(ActionEvent e)

{

                int index = combo.getSelectedIndex();

                Object o = combo.getSelectedItem();

    JOptionPane.showMessageDialog(null,"Ju zgjodhet "+lendet[index]);

        String s = ""+o;

        System.out.println("U zgjodh "+s);

}

public static void main(String[] arguments)

{

final int FRAME_WIDTH = 350;

final int FRAME_HEIGHT = 120;

ComboBoxDemo frame =new ComboBoxDemo();

frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

frame.setVisible(true);

}

}