Java override method from another class without inheritance

I found a similar question here:
overriding methods without subclass in Java

But mine is a little different, I have two classes, one based on the GUI and the other just methods for changing elements in the first class. If he just edits the main function, I don't see a problem, but now I want to override jbutton in the first class method from the second class without inheriting it. Where do I need to start?

I have a workaround that the second class extends JButton, overrides the method I want, and adds this class to my GUI class (anonymous object or not, it does not matter). But I want to find a way to find a way to answer the question, is this possible? Thanks:)

Edit
Here is an example code:

The first class, since this is only a button in jframe, I add them only to the constructor:
ButtonOverrider bo=new ButtonOverrider(); β†’ this is an overrider class
button=bo.overridePaintComponent(bo); // first try button=bo.overridePaintComponent(); // second attempt
bo.overridePaintComponent(bo); // third attempt

And here is the ButtonOverrider method:

 public JButton ButtonOverrider(JButton button) { button = new JButton() { @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); GradientPaint gp = new GradientPaint(0, 0, Color.blue.brighter().brighter(), 0, getHeight(), getBackground().darker().darker()); g2.setPaint(gp); g2.fillRect(0, 0, getWidth(), getHeight()); g2.dispose(); super.paintComponent(g); super.setContentAreaFilled(false); super.setFocusPainted(false); super.setBorder(new LineBorder(Color.yellow, 2)); super.setText("Shuro"); } }; return button; } 
+4
source share
1 answer

Where do I need to start?

With inheritance. The only way that redefinition does makes any sense. It is not clear why you do not want to use inheritance, but this is the only way to override the method. If you use an anonymous class or a named one, it does not matter, but it must extend the class to override the method. This is just a way of redefinition working in Java.

EDIT: The code you provided in the updated question uses inheritance by creating an anonymous inner class ... but it does not do what I expect from it, because it creates a new object, and does not override the method of the existing object. The parameter value is never used.

+7
source

Source: https://habr.com/ru/post/1485164/


All Articles