Abhishek V
Abhishek V

Reputation: 11

how to make a button run a loop in java

I understand how to create a button and it's application in Java. Would anyone be able to show me the code to be able to make the button in the code below be able to print something as simple as hello world in the terminal. I am using bluej if that is of any matter. I am very sorry I am a beginner coder.

code sample

Upvotes: 0

Views: 865

Answers (3)

Robert Bartlensky
Robert Bartlensky

Reputation: 41

ActionListener is what you are looking for. There is a very nice guide on Oracle's website. You should look into this tutorial and understand different ways of creating ActionListeners. I will give you a simple example which doesn't involve Anonymous Classes because I am not sure of how much you know about them.

public class Frame extends JFrame implements ActionListener {

    public Frame() {

        super("Test"); // calling the superclass
        setLayout(new FlowLayout()); // creating a layout for the frame
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // create the button
        JButton jbTest = new JButton("Click me!");

        /* 'this' refers to the instance of the class
           because your class implements ActionListener
           and you defined what to do in case a button gets pressed (see actionPerformed)
           you can add it to the button
        */
        jbTest.addActionListener(this); 
        add(jbTest);
        pack();
    }

    // When a component gets clicked, do the following
    @Override
    public void actionPerformed(ActionEvent ae) {

        System.out.println("Hello!");
    }
}

Upvotes: 0

Andrei-Marius Longhin
Andrei-Marius Longhin

Reputation: 563

JButton button = new JButton();
button.setActionListener(e -> System.out.println("Clicked"));

This uses a lambda expression. Inside it, you can add as much code as you like, but add it between {} if it's more than a line.

More on buttons here

Upvotes: 2

TheFooBarWay
TheFooBarWay

Reputation: 594

You need a listener for your button.

JButton button= new JButton("Button");
button.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    System.out.println("Hello World");
  }
});

the button will 'listen' for the action and preform whatever task you define for it.

Upvotes: 0

Related Questions