简体   繁体   中英

Java - override paint(Graphics g) Method from >variable<

I have a Canvas variable in my class. How can I override the paint() method from Canvas ?. I know that you can create a separate class and extend Canvas , but in this case I want to keep my variable.

//This is the method i am looking for
  public void paint(Graphics g) {
     super.paint(g)
  }

Here's my class:

private JFrame frame;
private Canvas canvas;

public SimpleSkinCreator() {
    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    canvas.setBackground(Color.black);
    canvas.setFocusable(true);
    canvas.requestFocus();

    frame = new JFrame("AvarionDE's - SimpleSkinEditor");
    frame.add(canvas);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

First, avoid using Canvas and AWT components with your Swing GUI and instead use a JPanel and override its paintComponent. You can do this easily if desired via:

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;

public class OverridePaintComponent extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;

   public OverridePaintComponent() {
      // TODO add junk to GUI
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);

      // draw here
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("OverridePaintComponent");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new OverridePaintComponent());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

You could use an anonymous class:

canvas = new Canvas() {
    @Override
    public void paint() {
        super.paint();
        // your code here
    }
};

Are you sure this is what you want to do, though? I recommend using Swing and the Swing API and not modifying paint() directly, unless you know what you're doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM