Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "Paint" event handler in Java?

Tags:

java

swing

What is the event handler in Java (using net beans, Swing) that resembles the Paint in C#? The event which shall be fired when the form is restored, resized ... etc

public void paint(Graphics g2){
    g2 = pnlDrawing.getGraphics();
    g2.clearRect(0, 0, size, size);
    g2.setColor(Color.BLACK);
    g2.fillRect(size/2-1, 0, 2, size); // draw y axis
    g2.fillRect(0, size/2-1, size, 2); // draw x axis

    //set the font
    g2.setFont(new Font("Arial", 2, 12));

    // write the values on the X axis
    for(int i=0; i<=10; i++){
        if(i == 0)
            continue;
        int pos1 = (size/2-1)-i*30;
        int pos2 = (size/2-1)+i*30;
        g2.draw3DRect(pos1, size/2-3, 1, 5, true);
        g2.drawString(String.valueOf(-i),pos1-10,size/2-3+20);
        g2.draw3DRect(pos2, size/2-3, 1, 5, true);
        g2.drawString(String.valueOf(i),pos2-5,size/2-3+20);
    }

    for(int i=0; i<=10; i++){
        if(i == 0)
            continue;
        int pos1 = (size/2-1)-i*30;
        int pos2 = (size/2-1)+i*30;
        g2.draw3DRect(size/2-3, pos1, 5, 1, true);
        g2.drawString(String.valueOf(i),size/2-3+10,pos1+5);
        g2.draw3DRect(size/2-3, pos2, 5, 1, true);
        g2.drawString(String.valueOf(-i),size/2-3+10,pos2+5);
    }

       pnlDrawing.invalidate();
}
like image 379
Ahmad Farid Avatar asked Mar 23 '26 04:03

Ahmad Farid


2 Answers

The method:

public void paint(Graphics g)

in the java.awt.Component class (which is the superclass for all Swing components) is the callback method for painting. So any repainting of the components that needs to be done will eventually call this method, so you can override it if you wish to perform your own painting.

== UPDATE ==

You need to subclass a component to get the paint callback, e.g.

public class MyPanel extends JPanel {
    public void paint(Graphics g) {
        // do your painting here
    }
}

Or you could use an anonymous inner class if you don't want to create a whole new class, e.g.

pnlDrawing = new JPanel() {
    public void paint(Graphics g) {
        // Your painting code
    }
}
like image 57
DaveJohnston Avatar answered Mar 24 '26 18:03

DaveJohnston


You should override paintComponent method because paint is also responsible for drawing child components, border and doing some other stuff.

like image 25
Ha. Avatar answered Mar 24 '26 18:03

Ha.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!