[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to determine which button pressed on Java Swing?

Posted on 2008-11-19
10
Medium Priority
?
1,353 Views
Last Modified: 2012-05-05
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

0
Comment
Question by:glynco
10 Comments
 
LVL 1

Expert Comment

by:pratap_sms
ID: 23001361
Add Listener to the Button you are intrested, So when the user presses the button the method will be invoked.
0
 

Author Comment

by:glynco
ID: 23001600
How?
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 23001683
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 24

Expert Comment

by:sciuriware
ID: 23001690
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
 

Author Comment

by:glynco
ID: 23001696
Can you insert that into my code because I do not know where to insert it.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 23001705
See my last post.

;JOOP!
0
 

Author Comment

by:glynco
ID: 23001722
I still have difficulty understanding it. I am not very familiar with Swing yet.

Can you write the FULL code? Please.
0
 
LVL 2

Accepted Solution

by:
V4Forums earned 2000 total points
ID: 23001734
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 23001745
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
 
LVL 24

Expert Comment

by:sciuriware
ID: 23001747
I type quite slow.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month19 days, 9 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question