Pat*_*ick 3 java events swing listener
我似乎没有掌握事件的概念等.在阅读了一段关于如何实现监听器之后,我遇到了Java教程,说我应该扩展AbstractListModel
以获取数据事件.由于某种原因,它仍然无法正常工作.
有什么我做错了吗?
什么样的代码可以addListDataListener(ListDataListener l)
使它工作?既然我也不明白.
public class CarComboBox extends AbstractListModel<Object> implements ComboBoxModel<Object> {
private JdbcRowSet jdbc;
private int size = 0;
private String selection;
public CarComboBox() {
try {
jdbc = new Query().getCarInfo();
jdbc.beforeFirst();
while (jdbc.next()) {
size++;
}
jdbc.beforeFirst();
}
catch (SQLException ex) {
System.err.println(ex.toString());
}
}
@Override
public void setSelectedItem(Object anItem) {
selection = (String) anItem;
}
@Override
public Object getSelectedItem() {
return selection;
}
@Override
public void addListDataListener(ListDataListener l) {
}
@Override
public void removeListDataListener(ListDataListener l) {
}
@Override
public int getSize() {
return size;
}
@Override
public String getElementAt(int index) {
try {
jdbc.absolute(index + 1);
return jdbc.getString(2);
}
catch (SQLException ex) {
System.out.println(ex.toString());
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
为了向CarComboBox添加一个监听器,我做了:
CarComboBox ccb = new CarComboBox();
ccb.addListDataListener(new ListDataListener()
Run Code Online (Sandbox Code Playgroud)
我猜你正在使用官方教程.
但是,您不应该触摸ListModel和ComboBoxModel.这些是您可能不需要的更高级的功能.本教程中的4个示例不使用ListModel和ComboBoxModel.
如果你使用标准的JComboBox(没有ListModel或ComboBoxModel),那么当有人做出选择时,ActionEvent
就会被触发.这个事件被Swing神奇地解雇了; 你不必担心它是如何产生的.但是,您有责任让一些(零个,一个或多个)对象能够接收并执行有关ActionEvent的操作:
public class MyClass implements ActionListener {
JComboBox comboBox = ...;
...
// You must register explicitly every ActionListener that you
// want to receive ActionEvent's from comboBox.
// Here we register this instance of MyClass.
comboBox.addActionListener(this);
...
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JComboBox) {
System.out.println("MyClass registered an ActionEvent from a JComboBox.");
System.out.println("Selected: " +
((JComboBox) e.getSource()).getSelectedItem());
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您没有任何其他ActionEvent被不同的Swing组件触发,您可以跳过,if (e.getSource() instanceof JComboBox)
因为您知道您的ActionEvent总是来自JComboBox.
在我的例子中,JComboBox在MyClass中,但它不一定是:
JComboBox comboBox = ...;
MyClass myClass = ...;
comboBox.addActionListener(myClass);
...
comboBox.addActionListener(someOtherActionListener);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2335 次 |
最近记录: |