Linking single listener to multiple buttons - java

Hello I am having an issue when linking a single listener to multiple buttons. I'm trying to use inner classes but it seems I'm getting it wrong somewhere. Can someone point me to the right direction?
If it helps the auto-correct thingy ( :D ) points to line 59 saying:
"createChampButton cannot be resolved to a variable"
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JApplet{
public void init(){
Container guiContainer = getContentPane();
LayoutManager layout = new FlowLayout();
guiContainer.setLayout(layout);
//Create Championship Button
final JButton createChampButton = new JButton("Create Championship");
guiContainer.add(createChampButton);
//Create Club Button
final JButton createClubButton = new JButton ("Create Club");
guiContainer.add(createClubButton);
//Create Athlete Button
final JButton createAthleteButton = new JButton ("Create Athlete");
guiContainer.add(createAthleteButton);
//Print Athletes Button
final JButton printAthletesButton = new JButton ("Print all Athletes");
guiContainer.add(printAthletesButton);
//The quiet Listener
ButtonListener aListener = new ButtonListener();
printAthletesButton.addActionListener(aListener);
createAthleteButton.addActionListener(aListener);
createClubButton.addActionListener(aListener);
createChampButton.addActionListener(aListener);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
//if (button.equals(printAthletesButton)){
//JOptionPane.showMessageDialog(null, "Athlete name is: " +anAthlete.GetAthleteName());
// JOptionPane.showMessageDialog(null, "Athlete age is: " + anAthlete.GetAge());
//}
if(button.equals(createChampButton)){
Championship aChampionship = new Championship("","");
aChampionship.champName = JOptionPane.showInputDialog("Enter Championship Name: ");
aChampionship.duration = JOptionPane.showInputDialog("Enter Championship Duration: ");
}
}
}
}
thanks in advance,
Chris

createChampButton is a local variable in init()
To access it elsewhere, you need to change it to a field in the class.

createChampButton is not defined in your other method, so the scope doesn't make possible that you access that. I see three options how you can work around that:
1) You use component.getActionCommand() instead - you can compare it with the text that your JButton holds (something like if( evt.getSource().getActionCommand().equals("Create Championship")
2) You can define your ActionListener within your init method:
public void init(){
Container guiContainer = getContentPane();
LayoutManager layout = new FlowLayout();
guiContainer.setLayout(layout);
//Create Championship Button
final JButton createChampButton = new JButton("Create Championship");
guiContainer.add(createChampButton);
//Create Club Button
final JButton createClubButton = new JButton ("Create Club");
guiContainer.add(createClubButton);
//Create Athlete Button
final JButton createAthleteButton = new JButton ("Create Athlete");
guiContainer.add(createAthleteButton);
//Print Athletes Button
final JButton printAthletesButton = new JButton ("Print all Athletes");
guiContainer.add(printAthletesButton);
//The quiet Listener
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
//if (button.equals(printAthletesButton)){
//JOptionPane.showMessageDialog(null, "Athlete name is: " +anAthlete.GetAthleteName());
// JOptionPane.showMessageDialog(null, "Athlete age is: " + anAthlete.GetAge());
//}
if(button.equals(createChampButton)){
Championship aChampionship = new Championship("","");
aChampionship.champName = JOptionPane.showInputDialog("Enter Championship Name: ");
aChampionship.duration = JOptionPane.showInputDialog("Enter Championship Duration: ");
}
}
};
printAthletesButton.addActionListener(aListener);
createAthleteButton.addActionListener(aListener);
createClubButton.addActionListener(aListener);
createChampButton.addActionListener(aListener);
}
}
3) You define your JComponents as instance variable - declaring them outside your init() method (but assigning them inside, still)
Regards,
Danyel

Related

Java Swing - manipulation of GUI

I've got probably trivial problem but I've spent hours in looking for answer.
I would like to create a button (ENTER button) that once clicked, removes certain components on the GUI (like numpad). The problem is that the class that defines instructions to do once button clicked doesn't see the components. I've tried to add implements ATM to this class but then the console returned very weird errors (when executing). Is there any 'clean' way to do this?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ATM extends JFrame{
// Container
int state = 0; // PIN screen
// ELEMENTS
JPanel container = new JPanel();
JTextArea display = new JTextArea("Please enter your PIN", 10, 50);
JTextField inputArea = new JTextField("");
JPanel buttons = new JPanel();
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton zero = new JButton("0");
JButton clear = new JButton("Clear");
JButton enter = new JButton("Enter");
JButton quit = new JButton("Quit");
// EVENTS
ButtonPresser buttonPress = new ButtonPresser(inputArea, display);
EnterPresser enterPress = new EnterPresser(inputArea, display, state, buttons);
ATM(){
super("ATM Cash Machine");
buildGUI();
pack();
setVisible(true);
}
private void buildGUI(){
// EVENT BINDINGS
one.addActionListener(buttonPress);
two.addActionListener(buttonPress);
three.addActionListener(buttonPress);
four.addActionListener(buttonPress);
five.addActionListener(buttonPress);
six.addActionListener(buttonPress);
seven.addActionListener(buttonPress);
eight.addActionListener(buttonPress);
nine.addActionListener(buttonPress);
zero.addActionListener(buttonPress);
clear.addActionListener(buttonPress);
quit.addActionListener(buttonPress);
enter.addActionListener(enterPress);
// ELEMENT SETTINGS
inputArea.setEditable(false);
display.setEditable(false);
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(display);
container.add(inputArea);
// Numeric pad
buttons.setLayout(new GridLayout(5,3));
buttons.add(one);
buttons.add(two);
buttons.add(three);
buttons.add(four);
buttons.add(five);
buttons.add(six);
buttons.add(seven);
buttons.add(eight);
buttons.add(nine);
buttons.add(clear);
buttons.add(zero);
buttons.add(enter);
buttons.add(quit);
container.add(buttons);
add(container, BorderLayout.NORTH);
}
// Main method
public static void main(String[] args){
ATM atm = new ATM();
}
}
class ButtonPresser implements ActionListener{
private JTextField iField;
private JTextArea oArea;
ButtonPresser(JTextField in, JTextArea out){
iField = in;
oArea = out;
}
public void actionPerformed(ActionEvent e){
switch(e.getActionCommand()){
case "Quit":
System.exit(0);
break;
case "Clear":
iField.setText("");
break;
default:
String fieldText = iField.getText();
if(fieldText.length() < 4){
iField.setText(fieldText+e.getActionCommand());
}
break;
}
}
}
class EnterPresser implements ActionListener{
private JTextField iField;
private JTextArea oArea;
private int state;
private JPanel buttons;
private final String PIN = "1234";
EnterPresser(JTextField in, JTextArea out, int st, JPanel but){
iField = in;
oArea = out;
state = st;
buttons = but;
}
public void actionPerformed(ActionEvent e){
if(state == 0){
String fieldText = iField.getText();
if(fieldText.equals(PIN)){
iField.setText("");
state = 1;
uiState0To1();
}
}
}
public void uiState0To1(){
buttons.remove(one);
}
}
The solution to your problem is simple. You need some way for your ButtonPresser class to talk with your ATM class, this is a classic example of an Observer Pattern
The idea is, you would provide some kind of event notification that your ButtonPresser will trigger under certain conditions, then your ATM class would listen for those events, it would then decide what it should do based on those events.
It is not the responsibility of the ButtonPresser to modify the state of ATM, just so we're clear.
You're now moving into the realm of Model-View-Controller, which could provide you a means to utilise CardLayout, which will further reduce the overall complexity of your problem, but also isolate responsibility and decouple your code
I am not sure which components you are trying to remove, but your problem is pretty clear. All of the components defined in the ATM class are not public. One way to manipulate these components from other classes would be to set them public.
The simplest way is to declare them as "public static" and reference them statically through the ATM class. Depending on your case you may need multiple instances of ATM, in which case you would not declare them static.
Here is another question with good info: Difference between public static and private static variables

Using Enter key to use JButton instead of just mouse click?

How would one bind the "Enter" key on a keyboard to press a JButton? Currently trying to figure this out but have no idea on what to do.
Here is my code for reference. What it's supposed to do is create a guessing game (which it does) but I want to add the ability to press enter to click the "Enter" button (jButtonEnter in this case).
package day21;
import java.awt.*;
import java.awt.event.*;
//import java.applet.*;
import javax.swing.*;
//import javax.swing.border.*;
public class Day21 extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
//All important Variables
JTextArea outTextArea = new JTextArea(10,20);
JScrollPane scroller = new JScrollPane(outTextArea);
static int GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
JPanel jPanelTop = new JPanel();
JPanel jPanelMid = new JPanel();
JPanel jPanelLow = new JPanel();
JLabel jLabelTop = new JLabel("Guess a number between 1 and 1000");
static JTextField jTextFieldInput = new JTextField("Guess Here",25);
JButton jButtonEnter = new JButton("Enter");
JButton jButtonReset = new JButton("Reset");
JButton jButtonClose = new JButton("Close");
public void init(){
this.getContentPane().setBackground(Color.white);
this.setSize(new Dimension(400, 120));
//Top Panel
jPanelTop.setBackground(Color.cyan);
jPanelTop.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelTop.setPreferredSize(new Dimension(14, 40));
jPanelTop.setToolTipText("Top Panel");
this.getContentPane().add(jPanelTop, BorderLayout.NORTH);
jPanelTop.add(jLabelTop);
//Middle Panel
jPanelMid.setBackground(Color.orange);
jPanelMid.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelMid.setPreferredSize(new Dimension(14, 40));
jPanelMid.setToolTipText("Center Panel");
this.getContentPane().add(jPanelMid, BorderLayout.CENTER);
jPanelMid.add(jTextFieldInput);
jPanelMid.add(jButtonEnter);
jButtonEnter.addActionListener(this);
//Lower Panel
jPanelLow.setBackground(Color.black);
jPanelLow.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelLow.setPreferredSize(new Dimension(14, 40));
jPanelLow.setToolTipText("Lower Panel");
this.getContentPane().add(jPanelLow, BorderLayout.SOUTH);
jPanelLow.add(jButtonReset);
jPanelLow.add(jButtonClose);
jButtonClose.addActionListener(this);
jButtonReset.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
double input = 0;
boolean Error = false;
String ErrorMSG = "Error: Please Enter a Number";
try{
input = Double.parseDouble(jTextFieldInput.getText().trim());;
}
catch(NumberFormatException n){
Error = true;
}
if(Error){
JOptionPane.showMessageDialog(rootPane, ErrorMSG); //If variable entered is not a number
}
String correctAnswer = "Hooray! You guessed Correctly! \n Press Reset to play again";
String tooHigh = input + " is too high";
String tooLow = input + " is too low";
if(!Error){
if(e.getSource() == jButtonEnter){
if (input == GuessMe){
jPanelLow.setBackground(Color.green);
JOptionPane.showMessageDialog(rootPane, correctAnswer);
}
if (input > GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooHigh);
}
if (input < GuessMe){
jPanelLow.setBackground(Color.red);
JOptionPane.showMessageDialog(rootPane, tooLow);
}
}
}
if(e.getSource() == jButtonReset){
Day21.reset(); //runs the reset() method which resets the window back to it's normal state
}
if(e.getSource() == jButtonClose){
System.exit(1); //exits the program
}
}
public static void reset(){
GuessMe = (int) Math.ceil(Math.random()*1000);//randomizes the number
jTextFieldInput.setText("Guess Here");
}
}
Check out Enter Key and Button for a discussion on this topic and a couple of solutions depending on your exact requirement:
use the root pane to set a default button
use the UIManager to have focus follow the button
use Key Bindings to invoke the default Action
Define a method - processEnterButton() and put all the necessary logic there. Call the method from actionPerformed() if the button was clicked. Also define key binding for the ENTER key and call the processEnterButton() from the binding as well.

Java GUI Variables Problems

I seem to have set up something wrong in the action listener for the Create Button handler. When I tried to get the value of the text field nameTF I get a null pointer error. I tried to imitate your code for the calculator, and the Exit Button Handler works well. I know that pressing the Create button invokes the handler but the statement
inName = nameTF.getText();
gives the error message.
The complete text of the listener is
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
and the whole program is below. Any help/explanation/suggestion would be very welcome.
import javax.swing.*; // import statement for the GUI components
import java.awt.*; //import statement for container class
import java.awt.event.*;
public class DogGUI //creation of DogGUI clas
{
private JLabel nameL, typeL, ageL, outtputL;
private JTextField nameTF, typeTF, ageTF;
private JButton createB, exitB;
CreateButtonHandler cbHandler;
ExitButtonHandler ebHandler;
public void driver () //creates everything
{
//create the window
JFrame DogInfo = new JFrame ("Dog GUI");
DogInfo.setSize(400,300); //set the pixels for GUI
DogInfo.setVisible(true); // set visibility to true
DogInfo.setDefaultCloseOperation(DogInfo.EXIT_ON_CLOSE); // when closed JFrame will disappear
//layout
Container DogFields = DogInfo.getContentPane();
DogFields.setLayout(new GridLayout(5,2));
// setting labels for GUI
nameL = new JLabel ("Enter name of Dog: ",
SwingConstants.RIGHT);
typeL = new JLabel ("Enter the type of the Dog: ",
SwingConstants.RIGHT);
ageL = new JLabel ("Enter the age of the Dog: ",
SwingConstants.RIGHT);
outtputL = new JLabel ("Dog Information: ",
SwingConstants.RIGHT);
//Buttons
JButton createB, exitB; //creating button for creation of Dog and button to exit
createB = new JButton("Create Dog");
exitB = new JButton("Exit");
//text fields
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
typeTF = new JTextField(15);
ageTF = new JTextField(5);
outtputTF = new JTextField(25);
outtputTF.setEditable(false); //this TF is to display this output
//Lables and Textfields
DogInfo.add(nameL);
DogInfo.add(nameTF);
DogInfo.add(typeL);
DogInfo.add(typeTF);
DogInfo.add(ageL);
DogInfo.add(ageTF);
DogInfo.add(outtputL);
DogInfo.add(outtputTF);
//Buttons
DogInfo.add(createB);
DogInfo.add(exitB);
//Instantiate Listeners
cbHandler = new CreateButtonHandler();
ebHandler = new ExitButtonHandler();
//Register Listeners
createB.addActionListener(cbHandler);
exitB.addActionListener(ebHandler);
DogInfo.setVisible(true);
}
//run the program from main, instantiate class, invoke driver() method
public static void main(String[] args)
{
DogGUI d = new DogGUI();
d.driver();
}
// class to actually handle Dog creation
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
private class ExitButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("inside exit button");
System.exit(0);
} // end method actionPerformed
}
}
You have a local variable in the driver() method called nameTF that is hiding that field (same for some other variables).
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
Remove the declaration of those fields since they are already declared as instance fields.
private JTextField nameTF, typeTF, ageTF;
(probably not outtputTF, depending on what you want to do)

How do I store information from the textFields?

Right now, I'm just testing the to make sure the button works...but this is my code for an applet that expands a binomial using Pascal's triangle! I have the equations for the actually figuring out part, I just need to know how to store the information from the JTextFields! Thanks!
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.Action;
public class BinomialExpander extends JApplet implements ActionListener
{
JLabel welcome;
JLabel directions;
JLabel example;
JLabel instructions;
JLabel startOfBinomial;
JLabel plusSign;
JLabel forExponent;
JLabel endOfBinomial;
JTextField txtFirst;
JTextField firstVar;
JTextField txtSecond;
JTextField secondVar;
JTextField exp;
JLabel lblExpanded;
JLabel outputExpanded;
double degreesFahrenheit;
FlowLayout layout;
Timer timer;
Button compute;
private int[] pascal1 = {1,1};
private int[] pascal2 = {1,2,1};
private int[] pascal3 = {1,3,3,1};
private int[] pascal4 = {1,4,6,4,1};
private int[] pascal5 = {1,5,10,10,5,1};
private int[] pascal6 = {1,6,15,20,15,6,1};
private int[] pascal7 = {1,7,21,35,35,21,7,1};
private int[] pascal8 = {1,8,28,56,70,56,28,8,1};
private int[] pascal9 = {1,9,36,84,126,84,36,9,1};
private int[] pascal10 = {1,10,45,120,210,120,45,10,1};
public void init()
{
Container c = getContentPane();
c.setBackground(Color.cyan);
layout = new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);
c.setLayout(layout);
setSize(500,175);
welcome = new JLabel("Welcome to the Binomial Expander Applet!");
directions = new JLabel("Enter binomial in the form: '(number)(variable) + (number)(variable)^exponent'.");
example = new JLabel("Example: (4a + 2)^2.");
// instantiate JLabel object for Degrees Fahrenheit
instructions = new JLabel("Enter the first number of your binomial(if there is a variable, add it into the second box):");
// instantiate JTextField object for the degrees fahrenheit
startOfBinomial = new JLabel(" (");
txtFirst = new JTextField(4);
// instantiate JLabel object for Degrees Celesius
firstVar = new JTextField(4);
plusSign = new JLabel(" + ");
txtSecond = new JTextField(4);
secondVar = new JTextField(4);
endOfBinomial = new JLabel(")");
forExponent = new JLabel("^");
forExponent.setFont(new Font("Times New Roman", Font.BOLD, 9));
exp = new JTextField(2);
compute = new Button("Compute!");
compute.addActionListener(this);
lblExpanded = new JLabel("Your expanded binomial is: ");
// JLabel to display the equivalent degrees Celsius
outputExpanded = new JLabel("");
c.add(welcome);
c.add(directions);
c.add(example);
c.add(instructions);
c.add(startOfBinomial);
//CALL the addActionListener() method on the JTextField object
// for the degrees Fahrenheit
txtFirst.addActionListener(this);
// Add the textbox the celsius label and output label
c.add(txtFirst);
c.add(firstVar);
c.add(plusSign);
c.add(txtSecond);
c.add(secondVar);
c.add(endOfBinomial);
c.add(forExponent);
c.add(exp);
c.add(compute);
c.add(lblExpanded);
c.add(outputExpanded);
// timer = new Timer(1, this);
// timer.start();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
}
public String expand()
{
String x = "callingComputing";
return x;
}
}
yourTextField.getText() returns a String you can use as you would any other String, store it in an array, teach it to sing, fly and enjoy life.
Conversely, you can use yourTextField.setText() to display stuff in your JLabel, textfield etc.
JTextField extends JTextComponent, which has API to deal text manipualtion.
As suggested by other answers use setText to replace the current text with new text.
Also read the official tutorial to understand How to Use Text Fields
JTextField txtName = new JTextField();
JButton btn = new JButton();
in the action performed method add this
String name = txtname.getText();
this statement returns the text that is entered in the text field the second before you click the button
You create a class where you'll store the data, and create an object of that in the Frame class, i.e. the class that'll provide the GUI to the data class, then in the action listener of the submit button of the frame assign the getText() returned string to the object's field
for eg: you want to take input name and age from the text field,
create a Person class
public class Person{
public String name;
public int age;
}
now create a GUI class
public PersonFrame extends JFrame{
public person;
public PersonFrame(){
person = new Person();
JTextField txtName = new JTextField();
JButton btn = new JButton();
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
person.name = txtName.getText();
person.age = Integer.parseInt(txtAge.getText()); //as the textfield returns a String always
}
});
}
}
and avoid using
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
If you have 100 button it'll be foolish to write nested if-else statements to check which button generated the event!!
remember that swing is designed for providing the user interface and you need an object of a class for storing the data!
for java tutorial visit here

create hot keys for JButton in java using swing

I use the following code to create hot keys for the java form using swing. If I press ALT+N,ALT+R,ALT+1,ALT+2 the cursor moves to correct text fields and I enter the value in corresponding Text Fields. It works properly. My problem is, I have Save and exit JButtons in this form if. I press CTRL+S means the Save button will be selected at the same time If i press CTRL+X means the exit button will be selected. How to create mnemonics for JButton? How to do CTRL+S,CTRL+X this using the following code?
Thanks in advance.
package hotkeys;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class hotkey extends JFrame {
public static void main(String arg[]) {
JLabel Name = new JLabel("Name");
JTextField tf1 = new JTextField(20);
Name.setLabelFor(tf1);
Name.setDisplayedMnemonic('N');
JLabel Regno = new JLabel("RegNO");
JTextField tf2 = new JTextField(20);
Regno.setLabelFor(tf2);
Regno.setDisplayedMnemonic('R');
JLabel Mark1 = new JLabel("Mark1");
JTextField tf3 = new JTextField(20);
Mark1.setLabelFor(tf3);
Mark1.setDisplayedMnemonic('1');
JLabel Mark2 = new JLabel("Mark2");
JTextField tf4 = new JTextField(20);
Mark2.setLabelFor(tf4);
Mark2.setDisplayedMnemonic('2');
JButton b1 = new JButton("Save");
JButton b2 = new JButton("eXit");
JFrame f = new JFrame();
JPanel p = new JPanel();
p.add(Name);
p.add(tf1);
p.add(Regno);
p.add(tf2);
p.add(Mark1);
p.add(tf3);
p.add(Mark2);
p.add(tf4);
p.add(b1);
p.add(b2);
f.add(p);
f.setVisible(true);
f.pack();
}
}
You need to register a keyBinding in the button's component inputmap. In code (repeating a subtle variant of what you have been told to do in your previous questions :-)
// create an Action doing what you want
Action action = new AbstractAction("doSomething") {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("triggered the action");
}
};
// configure the Action with the accelerator (aka: short cut)
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));
// create a button, configured with the Action
JButton toolBarButton = new JButton(action);
// manually register the accelerator in the button's component input map
toolBarButton.getActionMap().put("myAction", action);
toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
(KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");
Sun has a really good Description of the whole Key Binding issue. You can find it here:
JavaSE Tutorial on Keybinding
//EDIT
Edited my example code so you can just copy + paste it and it will work. Included the points that were missing, thanks for the feedback.
KeyStroke keySave = KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK);
Action performSave = new AbstractAction("Save") {
public void actionPerformed(ActionEvent e) {
//do your save
System.out.println("save");
}
};
JButton b1 = new JButton(performSave);
b1.getActionMap().put("performSave", performSave);
b1.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySave, "performSave");
KeyStroke keyExit = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK);
Action performExit = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent e) {
//exit
System.out.println("exit");
}
};
JButton b2 = new JButton(performExit);
b2.getActionMap().put("performExit", performExit);
b2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyExit, "performExit");
Just modified your code. (inserted code in //**)
Just 1 comment... Ctrl-X is shortcut for edit command "Cut" (along with Ctrl-C & Ctrl-V). You have editable fields in frame. I used Ctrl-Q (quit) instead.
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.plaf.ActionMapUIResource;
import java.net.*;
public class HotKeys extends JFrame {
public static void main(String arg[]) {
JLabel Name = new JLabel("Name");
JTextField tf1 = new JTextField(20);
Name.setLabelFor(tf1);
Name.setDisplayedMnemonic('N');
JLabel Regno = new JLabel("RegNO");
JTextField tf2 = new JTextField(20);
Regno.setLabelFor(tf2);
Regno.setDisplayedMnemonic('R');
JLabel Mark1 = new JLabel("Mark1");
JTextField tf3 = new JTextField(20);
Mark1.setLabelFor(tf3);
Mark1.setDisplayedMnemonic('1');
JLabel Mark2 = new JLabel("Mark2");
JTextField tf4 = new JTextField(20);
Mark2.setLabelFor(tf4);
Mark2.setDisplayedMnemonic('2');
JButton b1 = new JButton("Save");
JButton b2 = new JButton("eXit");
JFrame f = new JFrame();
JPanel p = new JPanel();
p.add(Name);
p.add(tf1);
p.add(Regno);
p.add(tf2);
p.add(Mark1);
p.add(tf3);
p.add(Mark2);
p.add(tf4);
p.add(b1);
p.add(b2);
// *****************************************************
ActionMap actionMap = new ActionMapUIResource();
actionMap.put("action_save", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save action performed.");
}
});
actionMap.put("action_exit", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Exit action performed.");
}
});
InputMap keyMap = new ComponentInputMap(p);
keyMap.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
java.awt.Event.CTRL_MASK), "action_save");
keyMap.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q,
java.awt.Event.CTRL_MASK), "action_exit");
SwingUtilities.replaceUIActionMap(p, actionMap);
SwingUtilities.replaceUIInputMap(p, JComponent.WHEN_IN_FOCUSED_WINDOW,
keyMap);
// *****************************************************
f.add(p);
f.setVisible(true);
f.pack();
}
}
I provide this as much for me as a learning experience as for anyone else. I've always had difficulty applying code snippets for key binding that I've found in the past and I hope my explanation and code will be clear. Thanks to #kleopatra for her code snippet, on which I base my code below.
(I'm using CAPITAL LETTERS where I should NOT in order to more clearly show what MUST MATCH.)
The code links the Ctrl-Shift-U keystroke to the code in actionPerformed for MYACTION via the matching strings in getInputMap and getActionMap.
The three instances of MYACTION below must match, as must the four instances of MYACTIONBUTTON, as must the two instances of the string MAKE_THESE_MATCH. Call them what you will; just make them match.
The button MYACTIONBUTTON must have MYACTION as the argument to the JButton defining it AND must have getInputMap and getActionMap applied to it.
private static JButton MYACTIONBUTTON;
private static JFrame frame;
private static JPanel panel;
...
Action MYACTION = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
// put action code here
}
};
MYACTIONBUTTON = new JButton(MYACTION);
MYACTIONBUTTON.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(getKeyStroke(VK_U, CTRL_DOWN_MASK | SHIFT_DOWN_MASK),
"MAKE_THESE_MATCH");
MYACTIONBUTTON.getActionMap().put("MAKE_THESE_MATCH", MYACTION);
panel.add(MYACTIONBUTTON);
frame.add(panel);

Categories

Resources