2013-06-19 47 views
-2

我有一个JList问题。我有这个JList的监听器(鼠标和键盘)。 我想双击列表中的某个选项(或按Enter键)后,JFrame关闭。我无法找到任何地方。你能帮我解决吗?如何关闭我的JList的jFrame?

下面是我使用的类(从StackOverflow的拍摄):

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

public class ActionJList extends JList { 

    ActionListener al; 
    boolean close=false; 

    public ActionJList(String[] it){ 
    super(it); 

    addMouseListener(new MouseAdapter() { 
     public void mouseClicked(MouseEvent me) { 
     if (al == null) return; 
     Object ob[] = getSelectedValues(); 
     if (ob.length > 1) return; 
     if (me.getClickCount() == 2) { 
      System.out.println("Sending ACTION_PERFORMED to ActionListener"); 
      al.actionPerformed(new ActionEvent(this, 
      ActionEvent.ACTION_PERFORMED, 
      ob[0].toString())); 
      me.consume(); 
      close=true; 

     } 
     } 
    }); 

    addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent ke) { 
     if (al == null) return; 
     Object ob[] = getSelectedValues(); 
     if (ob.length > 1) return; 
     if (ke.getKeyCode() == KeyEvent.VK_ENTER) { 
      System.out.println("Sending ACTION_PERFORMED to ActionListener"); 
      al.actionPerformed(new ActionEvent(this, 
      ActionEvent.ACTION_PERFORMED, 
      ob[0].toString())); 
      ke.consume(); 
     } 
     } 
    }); 
    this.setSelectedIndex(0); 
    } 

    public ActionJList(Vector it){ 
    super(it); 

    addMouseListener(new MouseAdapter() { 
     public void mouseClicked(MouseEvent me) { 
     if (al == null) return; 
     Object ob[] = getSelectedValues(); 
     if (ob.length > 1) return; 
     if (me.getClickCount() == 2) { 
      System.out.println("Sending ACTION_PERFORMED to ActionListener"); 
      al.actionPerformed(new ActionEvent(this, 
      ActionEvent.ACTION_PERFORMED, 
      ob[0].toString())); 
      me.consume(); 
     } 
     } 
    }); 

    addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent ke) { 
     if (al == null) return; 
     Object ob[] = getSelectedValues(); 
     if (ob.length > 1) return; 
     if (ke.getKeyCode() == KeyEvent.VK_ENTER) { 
      System.out.println("Sending ACTION_PERFORMED to ActionListener"); 
      al.actionPerformed(new ActionEvent(this, 
      ActionEvent.ACTION_PERFORMED, 
      ob[0].toString())); 
      ke.consume(); 
     } 
     } 
    }); 
    this.setSelectedIndex(0); 
    } 



    public void addActionListener(ActionListener al){ 
    this.al = al; 
    } 
    public boolean getClose(){return close;} 
} 
+0

当你在SO上发现时,代码是否严重缩进? –

回答

3

你总是可以使用下面的代码片段:

Window window = SwingUtilities.getWindowAncestor(ActionJList.this); 
if (window!=null) 
    window.setVisible(false); 

注:而不是添加KeyListener/KeyAdapterJList,考虑使用Swing KeyBindings。

+0

使用SwingUtilities类有很多有用的方法。 – camickr

+0

非常好,没有意识到这个功能可用。 –

1

为什么值得检查List Action为可重用的类添加MouseListener和密钥绑定为您。此外,事件的来源是JList,因此使用Guillaume的建议可以轻松创建Action。

没有必要对可用的JFrame进行引用。 SwingUtilities方法是更好的方法。