Java - Call Method via JButton - java

How can I call a method by pressing a JButton?
For example:
when JButton is pressed
hillClimb() is called;
I know how to display messages etc when pressing a JButton, but want to know if it is possible to do this?
Many thanks.

If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.
With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.
You can use an anonymous class too:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hillClimb();
}
});

Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonSample extends JFrame implements ActionListener {
public ButtonSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(100, 100);
setLocation(100, 100);
JButton button1 = new JButton("button1");
button1.addActionListener(this);
add(button1);
setVisible(true);
}
public static void main(String[] args) {
new ButtonSample();
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
}
}

Fist you initialize the button, then add ActionListener to it
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});

You need to add an event handler (ActionListener in Java) to the JButton.
This article explains how to do this.

btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
with lambda

Related

how to define action listener for buttons in java

I have a jframe that includes JButton.I have six buttons in this frame, but I don't know how to define action listener for this buttons.please help to solve this problem.
First you have to import the package java.awt.event.* to enable events. After the class name you have to add implements ActionListener so that the class can handle events. When you have created the buttons you have to add an actionlistener to each button. Since you haven't showed which code you use I make an example with a simple program that counts votes, if the user clicks the yesButton the votes are increased with 1 and if the user clicks the noButton the votes are decreased with 1.
Here is the code to add an ActionListener to each button:
yesButton.addActionListener(this);
noButton.addActionListener(this);
Then write the following code to handle the events:
public void actionPerformed(ActionEvent e) {
JButton src = (JButton) e.getSource();
if(src.getActionCommand().equals("Yes")) {
yesCount++;
} else {
noCount++;
}
label.setText("Difference: " + (yesCount - noCount));
}
If you have 6 buttons you need to have an if statement and then 5 "else if" statements instead of only an if and an else statement.
Have a look at the Java tutorials on how to use ActionListeners:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Here's a simple example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hello extends JPanel implements ActionListener {
JButton button;
public Hello() {
super(new BorderLayout());
button = new JButton("Say Hello");
button.setPreferredSize(new Dimension(180, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this); // This is how you add the listener
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e) {
System.out.println("Hello world!");
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Hello");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Hello();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
buttons have a method called addActionListener, use that for adding the action listener that you can implement for the click...
Example:
dummyButton = new JButton("Click Me!"); // construct a JButton
add(dummyButton); // add the button to the JFrame
dummyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(" TODO Auto-generated method stub");
}
});
It's really simple.
I suppose you have an instance of your button, right? Let's say that instance is called myButton.
You can just add an action listener by calling addActionListener:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do whatever you like here
}
});
Protip: next time you don't know what method to call, just type the instance name and .. Then, your IDE will show you all the methods you can call, unless you are not using an IDE. If that is the case, download one.

The button declared in the frame is not working properly when it is pressed

import java.awt.*;
import java.sql.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class nava extends JFrame implements ActionListener
{
Button b1=new Button("clear");
TextField t1=new TextField();
public nava()
{
this.setLayout(new GridLayout(2,2));
b1.addActionListener(this);
this.setSize(200,200);
add(t1);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText(""); //without space
}
}
public static void main(String r[])
{
new nava().show();
}
}
On clicking the button b1 the TextField should get empty but it is not
getting empty.The textfield just remain the same .But when I put space in the actionPerformed function it add a space in textfield. Please tell me what is the problem with the code.
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
t1.setText(" "); //with space
}
}
Use Swing components, not AWT components and the code should work. For example use JButton and JTextField not Button and TextField. Also don't call deprecated methods such as show(). Please consider checking the Swing tutorials as they'll teach you much you'll find useful. For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Nava extends JFrame implements ActionListener {
JButton b1 = new JButton("Clear");
JTextField t1 = new JTextField("Fubar", 10);
public Nava() {
this.setLayout(new GridLayout(2, 2));
b1.addActionListener(this);
// this.setSize(200, 200);
add(t1);
add(b1);
b1.setMnemonic(KeyEvent.VK_C); // alt-c to activate button
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
t1.setText("");
}
}
public static void main(String r[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Nava nava = new Nava();
nava.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nava.pack(); // let components and layout managers size themselves
nava.setLocationByPlatform(true);
nava.setVisible(true);
}
});
}
}
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
As for why your code doesn't work -- I honestly don't know as I don't work directly with AWT library components; very few people do. Edit: note this similar question. The authors of that question don't know why setText("") but offer a work-around:
// first this:
tf.setText(" ");
// followed by this:
tf.setText("");

ActionEvent won't appear

I have a problem in my program. Here's my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;`
public class click_rep extends JFrame{`
public click_rep(){
super("CLICK");
final JButton btn1 = new JButton("CLICK HERE");
final JLabel label = new JLabel();
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(btn1);
setSize(315,120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
String command = e.getActionCommand();
if (command.equals(btn1)){
label.setText("CLICK");
setVisible(true);
}
}catch(Exception e1){
e1.printStackTrace();
}
}
});
}
public static void main(String[] a){
click_rep cp = new click_rep();
}
}
My problem is that the ActionEvent won't appear. What will I do to make the ActionEvent appear?
Hopefully someone can help me. Thanks for the help.
Take a closer look at this...
String command = e.getActionCommand();
if (command.equals(btn1)){
command is a String and btn1 is a JButton, when are they likely to ever be equal?
There are a few ways you might fix it, you could, for example, do something like this...
if ("CLICK HERE".equals(command)) {
Or something like this...
if (e.getSource() == btn1) {
But I prefer the first one...
But, because the ActionListener is an annoymouse listener registered to btn1, the source of the event can never be anything other then btn1, so you could simply do something like this instead...
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
label.setText("CLICK");
// Not sure what this is meant for, as the component
// must already be visible in order for the user to
// activate the button...
setVisible(true);
}
});

How can I add the ActionEvent to the JButton so that when i click it it will fire the event?

I want to be able to add the ActionListener to the JButton but cannot seem to get it to work properly.
I have tried to add the ActionListeneer and also the ActionEvent and neither seems to fire the ActionPerformed method.
I did not one curious aspect was the the compiler made me take off the #Override keyword since the interface is used to create a variable and not implemented.
Does this make a difference? I am certain that you can do it this way but I think I am just a bit off the mark.
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class testInterfaces2 {
static ActionListener m;
static ActionEvent me;
testInterfaces2() {
}
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse Clicked");
}
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JButton pButton = new JButton("Print");
pButton.addActionListener(m);
//pButton.addActionListener(m.actionPerformed(me));
f.add("Center", pButton);
f.pack();
f.setVisible(true);
}
}
It should be like this and remove ActionListener and ActionEvent variables that is not needed.
public class testInterfaces2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse Clicked");
}
...
JButton pButton = new JButton("Print");
pButton.addActionListener(this);
}
#Override doesn't do any thing extra other than compile time checking of the overridden method.
In simple term, You need a class that implements ActionListener and obviously implements actionPerformed() method. Simply create a object of that class and pass in addActionListener() method.
I did not one curious aspect was the the compiler made me take off the
#Override keyword since the interface is used to create a variable and
not implemented.
This should have highlighted your first problem, your testInterfaces2 class can't override actionPerformed as it's not defined in any part of the parent class or it's parents. This is because testInterfaces2 doesn't implement ActionListener directly or indirectly (via inheritance).
Your second problem is m is null, you've never initialised it
Take a closer look at How to write ActionListeners for more details
I think it's best to define a new ActionListener for each button. Like this
JButton pButton = new JButton();
pButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
System.exit(0);
}
});

How to make a JButton do something

I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});

Categories

Resources