Java: override method on demand

344 Views Asked by At

Am I able to override a method on demand? I have a class that extends JFrame and has a JPanel inside. I want to draw a circle in the JPanel but I don't want to have an own class for the JPanel (then I could override paintComponent). My idea was something like this:

public class KugelClient extends JFrame {
 public KugelClient() {
    super("KugelClient");

    JPanel panel = new JPanel();
    panel.paintComponent(Graphics g) { 
      //overriding method here
      g.fillOval(...);
    }
  }

Is there anything in Java which makes it possible to do something like this (e.g. with lambda?) or do I have do create an own class for the panel?

1

There are 1 best solutions below

3
On BEST ANSWER

You can create an anonymous subclass of JPanel with an overriden paintComponent() method. Something like this:

JPanel panel = new JPanel() {
    //overriding method here
    public void paintComponent(Graphics g) {
        g.fillOval(...);
    }
};