2

I have a JTable that has a delete button to delete its rows.

I want to create a shortcut, for example when user selects a row and presses the 'Delete' button on keyboard , that line should be deleted.

My line is deleted with my JButton1 perfectly.

        if (e.getSource() == KeyEvent.VK_DELETE) {

           // Delete row Method
    }

But it doesn't work.

4

3 回答 3

4
  • 不要使用 KeyListener 来完成这项工作,并且在 Swing 中永远不要使用 KeyBindings

  • 将 ListSelectionListener 添加到 JTable 中,注意测试if(table.getSelectedRow > 0)

  • 对 JTable 使用 KeyBindings,覆盖 Delete 键

于 2013-05-10T08:26:38.990 回答
2

我不知道确切的问题是什么,因为您提供的代码太少。但是,您不能使用getSource()来测试键入(按下或释放)哪个键。使用getKeyChar()getKeyCode()


以下是我的代码的解释:

  1. 您需要将 a 添加KeyListener到组件中(当然)
  2. 组件必须有焦点
    1. 组件必须是可聚焦的(将 focusable 设置为 true)
    2. 组件需要请求焦点
  3. 覆盖keyTyped keyPressedkeyReleased检索KeyEvent
    1. 要检查输入了哪个键keyTyped,请使用getKeyChar()
    2. keyPressed要检查在and中按下或释放哪个键,请keyReleased使用getKeyCode()

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

public class Test {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setSize(new Dimension(410, 330));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(null);
        JPanel panel = new JPanel();
        panel.setBackground(Color.GREEN);
        panel.setBounds(50, 50, 300, 200);

        panel.addKeyListener(new MyKeyListener()); // add KeyListener
        panel.setFocusable(true); // set focusable to true
        panel.requestFocusInWindow(); // request focus

        f.getContentPane().add(panel);
        f.setVisible(true);
    }

    static class MyKeyListener extends KeyAdapter {
        @Override
        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar() == '\177') {
                // delete row method (when "delete" is typed)
                System.out.println("Key \"Delete\" Typed");
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                // delete row method (when "delete" is pressed)
                System.out.println("Key \"Delete\" Pressed");
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                // delete row method (when "delete" is released)
                System.out.println("Key \"Delete\" Released");
            }
        }
    }
}
于 2013-05-13T13:13:20.953 回答
2

看看这个页面:

http://www.coderanch.com/t/341332/GUI/java/setting-keyboard-navigation-shortcut-keys

取自那里:

为该按钮创建一个键侦听器(看来您已经做到了):

Button btn = new Button("Press Me");
btn.addKeyListener(myKeyListener);

并实现keylistener:

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_DELETE ){
        //Do whatever you want
    }
}

试试看,告诉我它是否有效。

于 2013-05-14T11:20:56.323 回答