java中下拉列表控件中的属性值,如何实现用户可以编辑?有源代码最好,菜鸟在此先谢谢啦

2024-11-29 17:39:35
推荐回答(1个)
回答(1):

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Demo10 extends JFrame implements ItemListener,
KeyListener
{
String s[] = { "吉林", "辽宁", "黑龙江" };

JComboBox jb1 = new JComboBox(s);
JLabel jla = new JLabel("吉林");
JPanel panel = new JPanel();
String defaultMessage="请输入城市名";
Component cmp;

public Demo10() {
jb1.setEditable(true);
panel.add(jb1);
panel.add(jla);
this.getContentPane().add(panel);
this.setBounds(100, 100, 300, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);

jb1.addItemListener(this);
cmp = jb1.getEditor().getEditorComponent();
cmp.addKeyListener(this);
}

public static void main(String[] args) {
new Demo10();
}
public void itemStateChanged(ItemEvent e){
jla.setText(e.getItem().toString());
}

public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
jla.setText(jb1.getEditor().getItem().toString());
repaint();
}
public void keyTyped(KeyEvent e)
{
}

}

已经测试过了。可以实现用户在编辑item时,获取编辑后的值