Nesne Tabanlı Programlama-2 (Bahar-2016) Hafta-5/2
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class combo extends JFrame implements ActionListener { JComboBox jcb; public combo() { this.setTitle("ComboBox"); this.setLayout(new FlowLayout()); this.setSize(150,100); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String[] icerik = {"Seçiniz","Deneme","XYZ","ABC"}; jcb = new JComboBox(icerik); jcb.setPreferredSize(new Dimension(140, 30)); JButton jbtn = new JButton("Göster"); jbtn.setPreferredSize(new Dimension(120, 30)); jbtn.addActionListener(this); this.add(jcb); this.add(jbtn); this.setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { if(jcb.getSelectedIndex()>0) { //int index = jcb.getSelectedIndex(); //String secilenbilgi = jcb.getItemAt(index)+""; JOptionPane.showMessageDialog(this, jcb.getSelectedItem()); jcb.setSelectedIndex(0); } } /** * @param args */ public static void main(String[] args) { new combo(); } }
import java.awt.*; import java.awt.event.*; import java.util.Vector; import javax.swing.*; public class combo1 extends JFrame implements ActionListener, ItemListener { JComboBox jcb; //Vector<String> v; JTextField jtf; public combo1() { this.setTitle("ComboBox 2"); this.setLayout(new FlowLayout()); this.setSize(150,150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); /*v = new Vector<String>(); v.add("Deneme"); v.add("abc"); v.add("xyz");*/ //jcb = new JComboBox(v); jcb = new JComboBox(); jcb.addItem("Seçiniz"); jcb.setPreferredSize(new Dimension(140, 30)); //jcb.addItemListener(this); jtf = new JTextField(); jtf.setPreferredSize(new Dimension(140, 30)); JButton jbtn1 = new JButton("Ekle"); jbtn1.setPreferredSize(new Dimension(140, 30)); jbtn1.addActionListener(this); jbtn1.setActionCommand("ekle"); JButton jbtn2 = new JButton("Sil"); jbtn2.setPreferredSize(new Dimension(140, 30)); jbtn2.addActionListener(this); jbtn2.setActionCommand("sil"); this.add(jcb); this.add(jtf); this.add(jbtn1); this.add(jbtn2); this.setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { switch(arg0.getActionCommand()) { case "ekle": ekle(); break; case "sil": sil(); break; } } @Override public void itemStateChanged(ItemEvent e) { // JOptionPane.showMessageDialog(this, jcb.getSelectedItem()); } public void ekle() { if(jtf.getText().length()>0) { jcb.addItem(jtf.getText()); jtf.setText(""); } } public void sil() { int secilen = jcb.getSelectedIndex(); if(secilen>0){ jcb.removeItemAt(secilen); jcb.setSelectedIndex(0); } } /** * @param args */ public static void main(String[] args) { new combo1(); } }