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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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
Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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
V4ForumsCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.