java - swing:一段代码的优化。
怪我咯
怪我咯 2017-04-17 13:10:11
0
1
257

如下代码给一个表格(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) {

        }
    });
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
小葫芦

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:

java  //注册表格事件
  table.addMouseListener(new MouseAdapter() {
        //鼠标双击事件
        @Override    // 不确定是否需要@Override, U try
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                .....//处理事件
            }
        }
    });

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!