I have been having some trouble with this action listener scenareo, and I am doing it exactly like what my java book says to do, and something is still not working. In the action listener the if statement is not working correctly. Here is an example of my code. The label in the center of the frame should be changing, but doesnt.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Test extends JFrame implements ActionListener{
private JButton team1;
private JLabel label;
public static void main(String[] args) {
new Test();
}//end main
public Test(){
super("Favorite Teams");
this.setVisible(true);
this.setSize(300, 300);
this.setLocationRelativeTo(null);//center the frame
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Initialize the JButtons
JButton team1 = new JButton("Zerg");//video game starcraft
//initialize the JLabel
label = new JLabel("Please select a team. ");
label.setHorizontalAlignment(JLabel.CENTER);
//add the JButtons to the frame
this.add(team1, BorderLayout.LINE_START);
//add JLabel to the frame
this.add(label, BorderLayout.CENTER);
//add ActionListeners to the buttons
team1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == team1)//Zerg
label.setText("Ok, if you like critters. ");
}//end method
}//end class