package jtablekeylistener;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
public class MyTable extends JTable implements KeyListener{
/**
* constructor
*/
private MyTable() {
this.setTableHeader(null); // no header
}
/**
* constructor
*
* @param defaultTableModel
*/
public MyTable(DefaultTableModel defaultTableModel) {
this();
this.setModel(defaultTableModel);
}
/**
*
* @param defaultTableModel
*/
public void setDefaultTableModel(DefaultTableModel defaultTableModel) {
this.setModel(defaultTableModel);
}
// // not editable
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
@Override
public void keyPressed(KeyEvent e) {
System.out.println ("keyPressed");
// Returns the integer code for the key on the keyboard and if keyCode is equal to VK_C (ASCII C)...
if(e.getKeyCode() == KeyEvent.VK_C) {
System.out.println ("ctrl-c");
}
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println ("keyReleased");
}
@Override
public void keyTyped(KeyEvent e) {
System.out.println ("keyTyped");
}
/**
*
* @param args
*/
public static void main(String[] args) {
try{
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e){
e.printStackTrace();
}
List<String> list1=new ArrayList<String>();
list1.add("1a");
list1.add("1b");
list1.add("1c");
list1.add("1d");
String[][] stringArray = new String[list1.size()][1];
int index = 0;
for (String string: list1) {
stringArray[index][0] = string;
index++;
}
final MyTable myTable = new MyTable(new DefaultTableModel(stringArray, new Object[] { "" }));
final JPanel myPanel = new JPanel();
myPanel.add(myTable);
final JFrame frame = new JFrame();
frame.add(myPanel, BorderLayout.CENTER);
frame.setTitle("Test JTable KeyListener" );
frame.setPreferredSize(new Dimension(200, 100));
frame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
}
});
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocation(200, 100);
frame.pack();
frame.setVisible(true);
}
}
|