1

I am doing awt work, but awt is not easy compared with JavaFX I learned before, I am struggling in setting an event for the button in the frame, and I have a PlayAgain() method, my aim is to call the method when the button is clicked. Additional: please do not create an inner class such to implement some Handlers, and justing using awt rather than swing/Fx.

This is my code:

public class CircleDraw extends Frame{
int[] diceResults;

public void paint(Graphics g) {
    super.paint(g);
    //in this part, I just using Graphics drawing some circles.
}

public void PlayAgain() {
    //......do something
}


public static void main(String args[]) {
    Frame frame = new CircleDraw();
    Button button = new Button("again!");//this is the button, I want to set a Event, when clicking the button,my program will call PlayAgain() method
    frame.add(button);
    button.setBounds(5, 5, 5, 5);
    frame.add(button);
    frame.setLayout(new FlowLayout());
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            System.exit(0);
        }
    });
    frame.setSize(500, 250);
    frame.setVisible(true);
}

}

I remember in JavaFX it indeed could be written like this:

button.setMouseClicked(e -> {
      //call the method}  )

So is there something similar in the awt could do this?

Gilbert
  • 121
  • 2
  • 13
  • 1
    " please do not create an inner class " - is that _your_ requirement? Note that even `e -> { /*call the method*/ }` will create an anonymous inner class. For action listeners you could use lambdas, i.e. `button.addActionListener( e -> { ... } ) `, for other listeners like mouse listeners that would not be so easy as the interfaces don't meet the requirements (you could provide some form of builder that accepts lambdas though). – Thomas Oct 18 '17 at 11:35
  • Use `Action`, for [example](https://stackoverflow.com/a/37063037/230513); see also [*Initial Threads*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html). – trashgod Oct 18 '17 at 11:48

1 Answers1

0

There is no way around creating a class. This is required by Java's strong typing. However, you do have some choices that you might find better than others.

  • You can create a lambda function directly.
  • You can have a compatible method signature and use it as a lambda function.
  • You can implement the listener in your top-level class, ie. CircleDraw implements WindowListener.
  • You can declare a field in CircleDraw and make it an instance of anonymous class.
  • You can use an anonymous class as a parameter (as per your example)
  • You can use a named inner class (you said you don't like that).

All of them are merely syntactic sugar. Behind the scenes, there is always a class that implements WindowAdapter.

jurez
  • 4,436
  • 2
  • 12
  • 20