简体   繁体   中英

How to use two paint methods in java? Or outside the basic paint method

How can i create two paint methods? When i'm trying to use two paint methods on of them is never working. If that cant be i want to paint outside the basic paint method and i dont know how. For example:

public class test extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                test frame = new test();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public void paint(Graphics g) {
    g.fillRect(100, 100, 100, 100);
}

public void pp(Graphics g) {
    g.fillRect(250, 100, 100, 100);
}

/**
 * Create the frame.
 */
public test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
}

}

When i'm trying to use two paint methods on of them is never working.

paintComponent(...) is not a method of JFrame. Whenever you attempt to override a method you should use the @Override annotation and the compiler will tell you when you attempt to override a method that doesn't exist.

In general, for other Swing components, the paint(...) method is responsible for invoking the paintComponent(...) method, so you should not override the paint() method. See: A Closer Look at the Paint Mechanism for more information.

Anyway you should NOT override paint() on a JFrame. Read the whole section on Performing Custom Painting from the tutorial link for a working example of how custom painting should be done.

I found a way.

public void paint(Graphics g) { super.paint(g); draw(g); draw2(g); }

public void draw(Graphics g){
    g.fillRect(100, 100, 100, 100);
}

public void draw2(Graphics g){
    g.setColor(Color.blue);
    g.fillRect(200, 100, 100, 100);
}

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