0

Extension クラスが KeyEvent をキャッチできないという問題があります。コードは次のとおりです。

public class DatabaseJTable extends JTable implements KeyListener {
    public DatabaseJTable(Object [][] data, Object [] columnNames) {
        super(data, columnNames);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
       return false;
    }

    @Override
    public void keyPressed(KeyEvent kv) {
        // TODO Auto-generated method stub
        if (kv.getKeyChar() == KeyEvent.VK_F2) {
            int selectedRow = this.getSelectedRow();
            System.out.println(this.getModel().getValueAt(selectedRow, 1));
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
}

クラスの使用方法は次のとおりです。

public class DatabaseRecordScreen extends JPanel {
    public DatabaseRecordScreen() {
        String [] columnNames = {"Date", "Order Number", "Item Number", "Contact", "Client", "Quantity"};
        Object [][] data = getAllWorkOrders();
        DatabaseJTable dataTable = new DatabaseJTable(data, columnNames);
        dataTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
        dataTable.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(dataTable);       
        scrollPane.setPreferredSize(Furniture.MAX_PANEL_SIZE);
        this.setPreferredSize(Furniture.MAX_PANEL_SIZE);
        this.add(scrollPane);
    }
}

DatabaseJTable は KeyEvent をキャッチできません。KeyPressed メソッドの先頭にブレークポイントを設定してデバッグしました。でも一向に捕まらない。

何か見逃した場合は、この問題を解決する方法を教えてください。ありがとう。

4

1 に答える 1

1

KeyListenersは気まぐれであることで有名です。機能するためには、それらが登録されているコンポーネントがフォーカス可能であるだけでなく、機能するためにフォーカスを持っている必要があります。

たとえば、より良い解決策は、キーバインディング APIを使用することです。

ここに画像の説明を入力

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TableKeyBindings {

    public static void main(String[] args) {
        new TableKeyBindings();
    }

    public TableKeyBindings() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                DefaultTableModel model = new DefaultTableModel(new String[]{"Row", "Name"}, 0);
                String[] names = new String[]{
                    "Lyveb", "Eldw", "Sutaw", "Radine", "Namhin", "Draos", "Et'rad",
                    "Deloef'c", "Ashlyeu", "Urner", "Nalund", "Rothem", "En'saya", "Torelm",
                    "Sulyc-it", "Ranray", "Denehin", "Zhayss", "Untechustos", "Aldh", "Tastintin",
                    "Burl", "Lyeril", "Trohliss", "Lehub", "Feyef", "Tutsul", "Ingjsam",
                    "When", "Worunde", "Ashtai", "Undoc", "Nyril", "Ightigar", "Umach",
                    "Ceracki", "Ler'elda", "Ray'vesa", "Echril", "Chrorodang", "Oskim", "Mos'tas",
                    "Siusk", "Yertas", "Queler", "Parehy", "Essr", "Shyhon", "Inep",
                    "Yeraer", "Inand", "Osutur", "Aryny", "Vycel", "Roolt", "Ceriss-kin",
                    "Age'augha", "Lelysa", "Ahaty", "Engpolskel", "Kulal", "Ardlper", "Lonuru",
                    "Belyf", "Chroozis", "Rodir", "Dralech", "Undvorrod", "Aqueo", "Yshya",
                    "Eldrad", "Umbur", "Ina'pola", "Hon'er", "Rientai", "Wareph", "Urnil'l",
                    "Et'inee", "Kyest", "Rodinga", "Yenet", "Fothund", "Ackgcer", "Estbanos",
                    "Seroughrad", "Nyer", "Tortiatia", "Dosac", "Moimash", "Whiril", "Oundi",
                    "Sayangrak", "Taqh", "Fidad", "Elmom", "Sayvera", "Imsayo", "Elmsam",
                    "Hubame", "Phorileng", "Bel'ves", "Awit", "Kelvesonhin", "Ingpol", "Ough'ther",
                    "Inaine", "Rilck", "Shys", "Ightl", "Vesangar", "Queineo", "Jyunt",
                    "Aleack", "Ageat", "Cysod", "Deluju", "Oldl", "Alent", "Tia'dele"};

                int row = 0;
                for (String name : names) {
                    model.addRow(new String[]{Integer.toString(++row), name});
                }

                JTable table = new JTable(model);
                InputMap inputMap = table.getInputMap(JComponent.WHEN_FOCUSED);
                ActionMap actionMap = table.getActionMap();

                inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "Show");
                actionMap.put("Show", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JTable table = (JTable)e.getSource();
                        int row = table.getSelectedRow();
                        if (row != -1) {

                            row = table.convertRowIndexToModel(row);
                            String name = (String) table.getModel().getValueAt(row, 1);

                            JOptionPane.showMessageDialog(null, name, "Show", JOptionPane.INFORMATION_MESSAGE);

                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

さて、あなたが問題を抱えている他の理由の 1 つは、比較できないという事実ですkv.getKeyChar() == KeyEvent.VK_F2。つまり、キーcharが値と一致せずVK、それらが持つ唯一の関係は名前です。

の方が好きかもしれませんがkv.getKeyCode()、キーバインディングの方が成功するでしょう...

于 2013-11-07T04:47:30.857 に答える