如下代码给一个表格(JTable)注册行双击事件,请问如何写得更加简单、可读?
//注册表格事件
table.addMouseListener(new MouseListener() {
//鼠标双击事件
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
.....//处理事件
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
Many GUI Listener interfaces in J2SE have Adapter implementation classes. By using the anonymous class of Adapter, you can avoid the trouble of implementing unnecessary methods.
For example, your code can be written as:
Explanation: xxListener is an interface, which defines many event calling methods. If your class implements xxListener, you must implement all the event methods it defines. Regardless of whether you need events or not, all events must be implemented, at least. Empty methods (interfaces are so arbitrary). xxAdapter belongs to a class. It implements the xxListener interface, but all its methods are made into empty methods. The class you inherit from the xxAdapter class only needs to rewrite the event methods you need. Other events occur. If so, the empty method of xxAdapter will be automatically called.
Reference http://www.766.com/doc/java/awt/event/MouseAdapter.html