-2

我有一个 JList 问题。我有这个 JList 的听众(鼠标和键盘)。我希望,在您双击列表中的一个选项(或按 Enter)后,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;}
}
4

2 回答 2

3

您始终可以使用以下代码段:

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

注意:考虑使用 Swing KeyBindings,而不是添加KeyListener/KeyAdapter到您的.JList

于 2013-06-19T14:08:21.633 回答
1

对于为您添加 MouseListener 和 Key Bindings 的可重用类,值得查看List Action。此外,事件的来源是 JList,因此您可以使用 Guillaume 的建议轻松创建 Action。

无需引用可用的 JFrame。SwingUtilities 方法是更好的方法。

于 2013-06-19T14:55:44.280 回答