怎样用代码触发JComboBox的ItemEvent事情

Yanbin_Q 2007-09-30 02:51:39
我的JComboBox,想像 Button.doClick()那样触发,代码应该是怎么写
我试图用
firePropertyChange()但不知道应该改变什么属性

对刚添加了一项的JComboBox用setSelectedIndex(0)方法也会出错
...全文
228 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuyu622 2007-10-04
  • 打赏
  • 举报
回复
顶了....
qybao 2007-10-03
  • 打赏
  • 举报
回复
可以不用继承,用反射就行了
for example
public void eventTest() {
try {
Class cls = JComboBox.class;
Method method = cls.getDeclaredMethod("fireItemStateChanged", new Class[]{ItemEvent.class});
method.setAccessible(true);
JComboBox cmb = new JComboBox(new String[]{"aa", "bb"});
ItemEvent event = new ItemEvent(cmb, 0, "aa", ItemEvent.SELECTED);
method.invoke(cmb, new Object[]{event}); //触发ItemEvent事件
} catch (Throwable e) {
e.printStackTrace();
}
}
Yanbin_Q 2007-10-03
  • 打赏
  • 举报
回复
也是个办法,为了使用JComboBox的受保护的fireItemStateChanged(ItemEvent)必须继承自JComboBox
mq612 2007-10-01
  • 打赏
  • 举报
回复
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestMain extends JFrame {
private MyComboBox box = null;

public TestMain() {
super("窗口");
JButton a = new JButton("触发按钮");
JPanel pane = new JPanel();
String [] arr = {"aaaaa", "bbbbb", "ccccc"};

box = new MyComboBox(arr);
box.setEditable(true);
pane.add(box);
pane.add(a);

box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getItem());
}});

a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
box.select(new ItemEvent(box, ItemEvent.ITEM_LAST, box.getSelectedItem(), ItemEvent.SELECTED));
}});

this.getContentPane().add(pane);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 200);
this.setVisible(true);
}

public static void main(String[] args) {
new TestMain();
}

}


class MyComboBox extends JComboBox{
public MyComboBox(Object [] o) {
super(o);
}
public void select(ItemEvent ie){
this.fireItemStateChanged(ie);
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧