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; }
source share