简体   繁体   中英

java key pressed to perform an action

i am very new to java.I am developing a inventory management system where i want to add the data to the jtable when "ENTER" key is pressed.but i don't know how to do so.i have searched about key bindings but got nothing helpful for me at that initial stage.here is my action that i want to perform at key pressed..

 private void addItemActionPerformed(java.awt.event.ActionEvent evt) {                                        
   int quantity,price;
   Product p=new Product();
   String[] result=new String[8];
   String data[]=new String[6];
   int i=0;
   result=p.getInfo(this.addItemField.getText());
    for(String s:result){
        data[i]=s;
        i+=1;
    }
    data[0]="1";
    quantity=Integer.parseInt(data[0]);
    price=Integer.parseInt(data[5]);
    int tPrice=price*quantity;
    data[5]=Integer.toString(tPrice);
    System.out.println(quantity+" "+price);
    table.addRow(data);
    this.addItemField.grabFocus();
  } 

and here is my default constructor

    public SellWindow() {

    initComponents();
    String title[]={"Qty","Code","Name","Unit Value","ml/kg","Line Total","Action"};
    entry.getColumnModel().getColumn(0).setPreferredWidth(20);
    table.setColumnIdentifiers(title);
    this.entry.setModel(table);

}

If the data to be added is being entered in a JTextField, an actionEvent should be fired when you press enter.

inputField.addActionListener(listener);  

Where listener is the container for your actionPerformed method.

But otherwise go with Nizil's suggestion and use KetListener.

i mean the action is executed when i clicked the button(Add item).i want it to be executed also when i pressed the ENTER in keyboard

You can make a button on the dialog the default button. It will be invoked when the Enter key is pressed. See Enter Key and Button for a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM