How to determine which button pressed on Java Swing?

I have this example code, How can I determine which button is pressed? Can someone put a println to this existing code?

System.out.println("Hello button pressed");
System.out.println("World button pressed");
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
 
class TestFrame extends JFrame
{
    public TestFrame(String title)
    {
       // call the superclass constructor
       super(title);
       JPanel panel = new JPanel();
       panel.setLayout(new BorderLayout());
       // this line adds the panel to the
       // Frame's content pane
       getContentPane().add(panel);
       // another way of doing the above is
       // setContentPane(panel);
       panel.add(new JButton("Hello"), BorderLayout.CENTER);
       panel.add(new JButton("World"), BorderLayout.SOUTH);
       // this line terminates the program when the X button
       // located at the top right hand corner of the
       // window is clicked
       addWindowListener(new WindowAdapter()
         {
           public void windowClosing(WindowEvent e)
           {
             System.exit(0);
           }
         });
    }
    public static void main(String[] args)
    {
       TestFrame testframe = new TestFrame("Test Frame");
       // this line causes the window to be sized to its
       // preferred size (this essentially compresses the
       // window)
       testframe.pack();
       // Initially, the JFrame is invisible. This line
       // makes the window visible.
       testframe.setVisible(true);
    }
}

Open in new window

glyncoAsked:
Who is Participating?
 
V4ForumsConnect With a Mentor Commented:
Follow the steps below:
1. Let your TestFrame class implement java.awt.event.ActionListener interface.
2. Provide an implementation to the actionPerformed() method of ActionListener to print the appropriate command on click of the buttons.
3. Register the buttons to the listener implemented.
4. Compile and Run the code, it should print the appropriate commands on the console based on your button click.

Please check the code snippet, I have added the implementation for the above mentioned points.

make sense?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
 
class TestFrame extends JFrame implements ActionListener
{
    public TestFrame(String title)
    {
       // call the superclass constructor
       super(title);
       JPanel panel = new JPanel();
       panel.setLayout(new BorderLayout());
       // this line adds the panel to the
       // Frame's content pane
       getContentPane().add(panel);
       // another way of doing the above is
       // setContentPane(panel);
	   JButton helloButton = new JButton("Hello");
	   JButton worldButton = new JButton("World");
	   //Register the buttons to 'this' ActionListener in order to handle the events triggered
	   //as a result of clicking one of these buttons.
	   helloButton.addActionListener(this);
	   worldButton.addActionListener(this);
       panel.add(helloButton, BorderLayout.CENTER);
       panel.add(worldButton, BorderLayout.SOUTH);
       // this line terminates the program when the X button
       // located at the top right hand corner of the
       // window is clicked
       addWindowListener(new WindowAdapter()
         {
           public void windowClosing(WindowEvent e)
           {
             System.exit(0);
           }
         });
    }
	/**
	* This method would handle the click events triggered by the buttons which are registered to 'this' listener.
	* This method has to be implemented as we are implementing the ActionListener.
	*/
	public void actionPerformed(ActionEvent event) {
		// Get the action command to identify which button was clicked.
		String command = event.getActionCommand();
		if("Hello".equals(command))
			System.out.println("You have clicked the 'Hello' button!");
		else if("World".equals(command)
			System.out.println("You have clicked the 'World' button!");
	}
	
    public static void main(String[] args)
    {
       TestFrame testframe = new TestFrame("Test Frame");
       // this line causes the window to be sized to its
       // preferred size (this essentially compresses the
       // window)
       testframe.pack();
       // Initially, the JFrame is invisible. This line
       // makes the window visible.
       testframe.setVisible(true);
    }
}

Open in new window

0
 
pratap_smsCommented:
Add Listener to the Button you are intrested, So when the user presses the button the method will be invoked.
0
 
glyncoAuthor Commented:
How?
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
sciuriwareCommented:
JButton b = new JButton();
b.addActionListener(this);

............................


   public void actionPerformed(ActionEvent a)
   {
      Object o = a.getSource();

      if(o == b)
      {
................................

And don't forget:

public class MyClass implements ActionListener

;JOOP!
0
 
sciuriwareCommented:
That will be:

class TestFrame extends JFrame implements ActionListener
{

for you.

Put the buttons in the instance, not in a method.

JButton helloButton;

       panel.add(helloButton = new JButton("Hello"), BorderLayout.CENTER);

;JOOP!
0
 
glyncoAuthor Commented:
Can you insert that into my code because I do not know where to insert it.
0
 
sciuriwareCommented:
See my last post.

;JOOP!
0
 
glyncoAuthor Commented:
I still have difficulty understanding it. I am not very familiar with Swing yet.

Can you write the FULL code? Please.
0
 
sciuriwareCommented:
I'm not going to rewrite your program. I'll give you the simplex :

public class MyClass extends JFrame implements ActionListener
{
     private JButton b;

     public gui()
     {
           b = new JButton("Exit");
           b.addActionListener(this);  // this object.
           JPanel p = new JPanel();
           p.add(b);
           getContentPane.add(p, BorderLayout.North);
           setVisible(true);
     }

     public void actionPerformed(ActionEvent a)
     {
        Object o = a.getSource();

        if(o == b)
        {
              System.exit(0); // Stop program.
         }
      }
}

somewhere:   MyClass m = new MyClass();

...........


;JOOP!
     
0
 
sciuriwareCommented:
I type quite slow.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.