下拉列表常用方法:
*JComboBox(): 创建一个没有选项的下拉列表
*addItem():增加选项
*getSelectedIndex():返回选中的下拉列表选项的索引
*getSelectedItem():返回选中的下拉列表选项
*removeItemAt(index):删除索引值为index的选项
*removeAllItem():删除全部选项
*addItemListener():注册事件的监视器
package example_java; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.naming.InitialContext; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; class windowChoice extends JFrame implements ItemListener, ActionListener{ JComboBox choice; JTextField text; JTextArea area; JButton add, del; public windowChoice() { init(); setSize(400, 400); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void init(){ setLayout(new FlowLayout()); choice = new JComboBox(); text = new JTextField(8); area = new JTextArea(6,25); choice.addItem("音乐天地"); choice.addItem("武术天地"); choice.addItem("象棋乐园"); choice.addItem("交友聊天"); add = new JButton("添加"); del = new JButton("删除"); add.addActionListener(this); text.addActionListener(this); del.addActionListener(this); choice.addActionListener(this); add(choice); add(del); add(text); add(add); add(new JScrollPane(area)); } 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 void itemStateChanged(ItemEvent e) { String name =choice.getSelectedItem().toString(); int index = choice.getSelectedIndex(); area.setText("\n"+index+":"+name); } }
时间: 2024-10-11 04:36:01