[java] How to draw in JPanel? (Swing/graphics Java)

I'm working on a project in which I am trying to make a paint program. So far I've used Netbeans to create a GUI and set up the program.

As of right now I am able to call all the coordinated necessary to draw inside it but I am very confused with how to actually paint inside it.

Towards the end of my code I have a failed attempt at drawing inside the panel.

Can anyone explain/show how to use graphics in a example like this?

All examples I have found make a class and extend it with JPanel but I don't know if I can do this since it was generated in netbeans.

I need to draw inside a JPanel, inside my JFrame. I don't know where to put the graphics class.

JavaPaintUI Class

package javapaint;

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

public class JavaPaintUI extends javax.swing.JFrame {

public JavaPaintUI() {
    initComponents();
}


private void initComponents() {


    jPanel2 = new javax.swing.JPanel();

    jPanel2.setBackground(new java.awt.Color(255, 255, 255));
    jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
    jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jPanel2MousePressed(evt);
        }
        public void mouseReleased(java.awt.event.MouseEvent evt) {
            jPanel2MouseReleased(evt);
        }
    });
    jPanel2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            jPanel2MouseDragged(evt);
        }
    });
    pack();
}// </editor-fold>                        

int currentX, currentY, oldX, oldY;

private void jPanel2MouseDragged(java.awt.event.MouseEvent evt) {                                     
    if (tool == 1) {
        currentX = evt.getX();
        currentY = evt.getY();
        oldX = currentX;
        oldY = currentY;
        System.out.println(currentX + " " + currentY);
        System.out.println("PEN!!!!");
    }

}                                    

private void jPanel2MousePressed(java.awt.event.MouseEvent evt) {                                     
    oldX = evt.getX();
    oldY = evt.getY();
    System.out.println(oldX + " " + oldY);
}                                    


//mouse released//
private void jPanel2MouseReleased(java.awt.event.MouseEvent evt) {                                      
    if (tool == 2) {
        currentX = evt.getX();
        currentY = evt.getY();
        System.out.println("line!!!! from" + oldX + "to" + currentX);
    }
}                                     

//set ui visible//
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new JavaPaintUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel2;
// End of variables declaration                   

class jPanel2 extends JPanel {

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

        g.drawString("BLAH", 20, 20);
        g.drawRect(200, 200, 200, 200);
    }
}
}

Screen shot

The whole thing is a JFrame and the white section in the center is jPanel2 which is what I want to draw on. screen shot of some code that is not this

This question is related to java swing jpanel draw paintcomponent

The answer is


Here is a simple example. I suppose it will be easy to understand:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

And the output looks like this:

Output


Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);
        super.setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp = new GPanel();
        super.add(jp);
    }

    public static void main(String[] args) {
        Graph g1 = new Graph();
        g1.setVisible(true);
    }

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);
        }
    }
}

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to jpanel

What does .pack() do? How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background How to layout multiple panels on a jFrame? (java) add controls vertically instead of horizontally using flow layout JPanel vs JFrame in Java Align text in JLabel to the right Adding JPanel to JFrame Java :Add scroll into text area JPanel setBackground(Color.BLACK) does nothing

Examples related to draw

How to draw a rectangle around a region of interest in python Class is not abstract and does not override abstract method Draw an X in CSS How to draw a standard normal distribution in R Can I draw rectangle in XML? Android: how to draw a border to a LinearLayout How to draw in JPanel? (Swing/graphics Java) Android Drawing Separator/Divider Line in Layout? Drawing a line/path on Google Maps How to show x and y axes in a MATLAB graph?

Examples related to paintcomponent

How to draw a circle with given X and Y coordinates as the middle spot of the circle? How does paintComponent work? How to draw in JPanel? (Swing/graphics Java)