How to use setActionCommand and getActionCommand
843806Jul 15 2009 — edited Jul 16 2009I am having a problem with setActionCommand and get ActionCommand.
Below is my current code:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TheFrame extends JFrame implements ActionListener{
JTextField textbox1;
JTextField textbox2;
JLabel lbl;
JLabel lbl2;
JButton enter;
public TheFrame(){
//create Textboxes and set locations
textbox1 = new JTextField(30);
textbox2 = new JTextField(30);
textbox1.setBounds(160, 10, 100, 20);
textbox2.setBounds(160, 30, 100, 20);
//Create label and set location
lbl = new JLabel("Enter your name here:");
lbl.setBounds(10,10,150,20);
lbl2 = new JLabel("Here is your name:");
lbl2.setBounds(10,30,150,20);
//create enter button and set location
enter = new JButton("Enter");
//creates ActionListener
textbox1.addActionListener(this);
enter.setActionCommand("enter");
//Adds components to the frame
getContentPane().setLayout(new FlowLayout());
getContentPane().add(lbl);
getContentPane().add(textbox1);
getContentPane().add(lbl2);
getContentPane().add(textbox2);
getContentPane().add(enter);
}
// actionPerformed method
public void actionPerformed(ActionEvent event){
if(event.getActionCommand().equals("enter")){
getContentPane().setBackground(Color.green);
} else {
textbox2.setText(textbox1.getText());
}
}
}
public class RepeatName{
public static void main(String args[]){
TheFrame frame = new TheFrame();
frame.setVisible(true);
frame.setSize(485, 130);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
I am using jGrasp to run, and after clicking the Enter button in my GUI application, nothing happens. What is the reason this is happenning?
Thanks in advance,
Eric