日期:2014-05-20 浏览次数:20645 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class WindowChoice extends JFrame implements ItemListener,ActionListener{ JComboBox choice; JTextField text; JTextArea area; JButton add,del; public WindowChoice(){ init(); setLocation(300,300); setSize(800,600); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void init(){ setLayout(new FlowLayout()); choice = new JComboBox(); text = new JTextField(); area = new JTextArea(10,10); choice.addItem("音乐天地"); choice.addItem("网络游戏"); choice.addItem("单机游戏"); choice.addItem("聊天室"); add = new JButton("添加"); del = new JButton("删除");//这里有修改过 add.addActionListener(this); text.addActionListener(this); del.addActionListener(this); choice.addItemListener(this); add(choice); add(text); add(add); add(new JScrollPane(area)); } public void itemStateChanged(ItemEvent e){ String name = choice.getSelectedItem().toString(); int index = choice.getSelectedIndex(); area.setText("\n"+index+":"+name); //这里修改过 } public void actionPerformed(ActionEvent e){ if(e.getSource() == add || e.getSource() == text){ String name = text.getText(); if(name.length()>0){ choice.addItem(name); choice.setSelectedItem(name); area.append("\n列表添加:"+name); } } else if(e.getSource() == del){ area.append("\n列表删除:"+choice.getSelectedItem()); choice.remove(choice.getSelectedIndex()); } } public static void main(String[] args) { new WindowChoice(); } }
------解决方案--------------------