import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Combo extends JFrame implements ActionListener,ItemListener{
JPanel panel=new JPanel();
JComboBox list=new JComboBox();
JButton butnDel=new JButton("删除"),butnAdd=new JButton("增加新词");
JTextField text=new JTextField(10);
JTextArea area=new JTextArea(10,10);
DefaultListModel listModel=new DefaultListModel();
public Combo(String title) {
super(title);
setBounds(100,100,400,400);
setVisible(true);
panel.add(list);
panel.add(butnDel);
panel.add(text);
panel.add(butnAdd);
add(panel,BorderLayout.NORTH);
add(new JScrollPane(area),BorderLayout.CENTER);
list.addItemListener(this);
butnDel.addActionListener(this);
butnAdd.addActionListener(this);
text.addActionListener(this);
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
Object o=e.getSource();
if(o==text||o==butnAdd){
String s=text.getText().trim();
if(s.length()==0){
area.append("输入为空或空格\n");
return;
}
if(check(s)){
int count=list.getItemCount();
list.addItem(s);
area.append(count+":"+s+" 列表添加"+s+'\n');
text.setText("");
}
else {
area.append("该项已经存在于列表中请另行选择\n");
text.setText("");
}
}
else if(o==butnDel){
int index=list.getSelectedIndex();
if(index>=0){
String str=(String)list.getSelectedItem();
list.removeItemAt(index);
//if(index>0)
//list.setSelectedIndex(index-1);
area.append(index+":"+str+" 列表删除"+str+'\n');
}
else area.append("没有选择上列表项或列表为空\n");
}
}
public void itemStateChanged(ItemEvent e){
if(e.getItemSelectable()==list){
if(e.getStateChange()==ItemEvent.SELECTED){
area.append(list.getSelectedIndex()+":"+list.getSelectedItem()+
" 列表选择"+list.getSelectedItem()+'\n');}
}
}
boolean check(String s){
int count=list.getItemCount();
for(int i=0;i
return false;
return true;
}
public static void main(String[] args) {
new Combo("字典");
}
}