Home Java Example Java Swing Java JButton Key Binding Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java JButton Key Binding Example

Advertisement
In this section we will discuss about how to bind a specific key to the button.

Java JButton Key Binding Example

In this section we will discuss about how to bind a specific key to the button.

Key binding feature is supported by the JComponent class. It is supported like an individual key is typed and the corresponding keystroke is responded.

Example

Here I am going to give a simple example which will demonstrate you about how to bind Enter key on JButton. In this example I want to save the data of a JTextField added at the JFrame to the database by pressing Enter Key. For this I have created a class named JavaJButtonEnterKeyBinding.java where I have created a method for creating GUI. In this method I have used JFrame to create a JFrame as well as used some other components like JTextField for creating a textfield, JLabel for creating a label,  then created a JPanel for adding the above components and created another JPanel for adding the JButton and then added these panel to a Container. To make a key binding on JButton I have used the methods as follows :

getInputMap(int) : This method returns the input map and the argument int can be specified by the constant integer value JComponent.WHEN_*FOCUSED* i.e. one of the constant value WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_IN_FOCUSED_WINDOW. However, this method can be used without an argument also.

put(keystroke, actionMapKey) : This method binds keyStroke to actionMapKey.

After binding the key I have created an Action object to perform the save action which saves the textfield data to the database table. This action will be performed when a binding key is mapped to the action map, so I have used the methods described below for mapping the action with the specified key-button binding.

getActionMap() : This method returns the ActionMap which specifies that a action with the specified keystroke binding.

put(key, action) : This method binds the key to action. Key is an object

Then I have created a method for saving the textfield data to the database table.

Source Code

JavaJButtonEnterKeyBinding.java

import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.Action;
import javax.swing.AbstractAction;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.sql.*;
 
public class JavaJButtonEnterKeyBinding
	{
		String name;
		JFrame frame;
        JPanel panel;
		JButton button;
		JTextField text1;
		JLabel lab1;
		public void createUI()
		{
			frame = new JFrame("Binding key example");
			frame.setLayout(null);			

			Container pane = frame.getContentPane();
			pane.setLayout(null);
			Insets insets = pane.getInsets();
			Dimension size;

			panel = new JPanel();

			text1=new JTextField(10);
			text1.setText("");
			text1.setEditable(true);
			lab1 = new JLabel("Enter Name ");
			panel.add(lab1);
			panel.add(text1);		
			pane.add(panel);
			size = panel.getPreferredSize();
			panel.setBounds(40 + insets.left, 50 + insets.top,
			size.width, size.height);

			panel = new JPanel();
			button = new JButton("Press Enter");
			button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
			
			Action action = new AbstractAction()
			   {
					@Override
				  public void actionPerformed(ActionEvent e)
				   {
					  button = (JButton)e.getSource();
					  name = text1.getText();
					  saveName();                        
				   }
			   };			
			button.getActionMap().put("Enter", action);
			button.addActionListener(action);
			
			panel.add(button);
			pane.add(panel);
			size = panel.getPreferredSize();
			panel.setBounds(100 + insets.left, 100 + insets.top,
			size.width, size.height);

			frame.setVisible(true);
			frame.setSize(300, 200);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);			
		}
		public String saveName()
		{
			try
			{
				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
				Connection con = DriverManager.getConnection("jdbc:odbc:swing");
				String sql = "INSERT INTO person(name) VALUES('"+name+"')";
				Statement st = con.createStatement();
				st.execute(sql);
				JOptionPane.showMessageDialog(null, "Record Added Succesfully.","Record Added",
							JOptionPane.INFORMATION_MESSAGE);
			}
			catch(Exception e)
			{
				JOptionPane.showMessageDialog(null, e.getMessage(),"Error",
							JOptionPane.ERROR_MESSAGE);
			}
			return name;
		}
		public static void main(String[] args)
		{
			JavaJButtonEnterKeyBinding jbe = new JavaJButtonEnterKeyBinding();
			jbe.createUI();
		}
}

Output

When you will execute the above code you will get the output as follows :

1. When you will compile and execute the above Java class then the output will be as follows :

When you will enter the value into the textfield and press the Enter key then the value will be saved to the database table and a dialog box will be displayed which specifies the value submitted successfully otherwise the dialog box will show an error message.

And lastly to specify whether your data is saved into the table or not see the database table as follows :

Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 10, 2013

Ask Questions?    Discuss: Java JButton Key Binding Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com