0

So I have just got into java swing and cannot find how I would change the colour within a lambda function, I imagine it will have something to do with getting the source or maybe even just making the button variable at the top of the class so I can access it from anywhere in the code.

Here is my window class:

import javax.swing.*;

public class window {
    JFrame frame;
    window(String title){
        this.frame = new JFrame(title);
        JButton button = new JButton("Text");
        button.addActionListener(x-> System.out.println(x.getSource()));
        this.frame.setSize(550,550);
        button.setBounds(550/2-75,550/2-75,150,50);

        this.frame.add(button);
        this.frame.setLayout(null);
        this.frame.setVisible(true);
    }
}

and my main class:

public class Main {
    public static void main(String[] args) {
        window win = new window("Hi");
    }
}

I would like for the button to change colour on click.

  • Implement java.awt.event.ActionEvent on your window class and (write) override the method "public void actionPerformed(ActionEvent e)" then notify the button has an event using the method buttonid.addActionListener(this) – Samuel Marchant Jul 08 '23 at 06:35

1 Answers1

0

You would override the actionPerformed in addActionListener method for this. Example from this solution:

@Override
public void actionPerformed(ActionEvent e) {
    // the source here refers to the object that provoked this method to occur
    JButton sourceBtn = (JButton) e.getSource();
    sourceBtn.setBackground(Color.RED);
}

You might want to read Oracle's documentation on this, which will strengthen your understanding here.

Thanks to user16320675 for correcting me on my phrasing.

  • 1
    `addActionListener` is a method, it does not contain other methods, you cannot override a method of it - maybe you meant override/implement the `actionPerformed` method of `ActionListener` – user16320675 Jul 08 '23 at 16:10