Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411588 Posts in 69386 Topics- by 58443 Members - Latest Member: Mansreign

May 06, 2024, 12:25:06 PM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)Draw stuff in Java
Pages: [1]
Print
Author Topic: Draw stuff in Java  (Read 2519 times)
mesotes
Level 0
**


<3


View Profile
« on: May 20, 2010, 01:26:39 PM »

Hi all

I already know a bit of Java. In fact, I know enough that documentations can be a bitch and it happened more than one time that I just don't get the overall picture of things.
Yeah I did some googleing but still, after reading the sun tutorial on 2D Graphics I still don't get it what I need to do to get a white canvas with the ability to draw when the mouse is pressed down.

So can anyone give me a little push in the right direction :/?

thanks
Logged
Dacke
Level 10
*****



View Profile
« Reply #1 on: May 20, 2010, 01:37:57 PM »

To get started I recommend looking at a working example. To build something like this from scratch can be quite tricky. I have done quite a bit of graphics-programming in Java, but I still haven't found a super-clean way to do it.

Here is one example to get you started.
http://leepoint.net/notes-java/examples/mouse/paintdemo.html

I haven't looked at the code, so I can't give you any guarantees, but it seems okay.

I could also give you my own source-code for a simple paint-program I did last year (but it contains paint-chat functionality too)
Logged

programming • free software
animal liberation • veganism
anarcho-communism • intersectionality • feminism
mesotes
Level 0
**


<3


View Profile
« Reply #2 on: May 20, 2010, 02:05:39 PM »

Ahhhh,.. a nice simple example.. just the thing I wanted Smiley)
Thank you so much!

btw did you google that?
Logged
Dacke
Level 10
*****



View Profile
« Reply #3 on: May 20, 2010, 02:06:47 PM »

Good to hear Smiley

Google indeed.
Logged

programming • free software
animal liberation • veganism
anarcho-communism • intersectionality • feminism
Chromanoid
Level 10
*****



View Profile
« Reply #4 on: May 20, 2010, 02:37:12 PM »

http://www.jhlabs.com/index.html (some nice code snippets there...)

maybe not as useful as the mentioned tutorial...:
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class AppFrame extends javax.swing.JFrame {
    //panel as screen for the canvas.
    class PaintPanel extends JPanel {
        BufferedImage canvasBuffer;
        //last mouse position
        int lastX=-1, lastY=-1;
        //draw antialiased line from x0,y0 to x1,y1
        public void drawLine(int x0, int y0, int x1, int y1) {
            Graphics2D g2d = (Graphics2D) canvasBuffer.getGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setColor(Color.BLACK);
            g2d.drawLine(x0, y0, x1, y1);
            //repaint the panel
            repaint();
        }
        //create new panel with canvas of size width,height
        public PaintPanel(int width, int height) {
            canvasBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            this.addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    drawLine(lastX, lastY,e.getX(), e.getY());
                    lastX = e.getX();
                    lastY = e.getY();
                }
                @Override
                public void mouseMoved(MouseEvent e) {
                    lastX = e.getX();
                    lastY = e.getY();
                }
            });
        }
        //override the paint method, so we can paint the canvas onto the panel...
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(canvasBuffer, 0, 0, this);
        }
    }
    //Frame stuff
    public AppFrame() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        add(new PaintPanel(1000, 1000), BorderLayout.CENTER);
        setSize(400, 300);
    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AppFrame().setVisible(true);
            }
        });
    }
}
« Last Edit: May 20, 2010, 02:41:31 PM by Chromanoid » Logged
Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #5 on: May 20, 2010, 05:52:17 PM »

This Java project of mine does a lot of drawing, it may be worth a look.  Source code is included.

I don't remember much about how I did it, but it involves drag-and-drop between components, and I'm pretty sure I ended up doing dirty rectangle on this one.
Logged



What would John Carmack do?
st33d
Guest
« Reply #6 on: May 21, 2010, 04:20:46 AM »

Why not use Processing? It's already a comprehensive graphics library for Java, and a lot of its drawing routines are faster than standard Java because they use floats as a default datatype for numbers instead of doubles.

You also get cheap and easy access to JOGL. Which is a hook into OpenGL, allowing you to produce 3D graphics that begins to approach the speed of coding graphics in C++.

Their forum is pretty good as well, because the IDE for the library is used as a teaching enviroment.

You could always ask them about the way they handle drawing at the very least, especially as Processing is an open source project.
Logged
Dacke
Level 10
*****



View Profile
« Reply #7 on: May 21, 2010, 04:26:28 AM »

If you only want to do simple stuff, it's often handy to use the standard libraries.
If you are looking to do more advanced stuff, there are many nice libraries to choose from.  Smiley
Logged

programming • free software
animal liberation • veganism
anarcho-communism • intersectionality • feminism
mesotes
Level 0
**


<3


View Profile
« Reply #8 on: May 21, 2010, 05:48:04 AM »

Heh, thanks but I "just" want to do a pixel editor.
Though its hard enough for me to figure out how to zoom in and to have a pen tool
which doesnt use drawLine to fill in the gaps when the mouse is moved too fast.
ah well, ill figure that out somehow.

now that i know that i have to google for "paint" and not "image/pixel editor"
^^
Logged
Dacke
Level 10
*****



View Profile
« Reply #9 on: May 21, 2010, 06:15:15 AM »

This part, from the example I linked to, handles all mouse actions.

Code:
    //============================================================= mousePressed
    public void mousePressed(MouseEvent e) {
        _state = State.DRAGGING;   // Assume we're starting a drag.
       
        _start = e.getPoint();     // Save start point, and also initially
        _end   = _start;           // as end point, which drag will change.
    }
   
    //============================================================= mouseDragged
    public void mouseDragged(MouseEvent e) {
        _state = State.DRAGGING;   // We're dragging to create a shape.
       
        _end = e.getPoint();       // Set end point of drag.  May change.
        this.repaint();            // After change, show new shape
    }
   
    //============================================================ mouseReleased
    public void mouseReleased(MouseEvent e) {
        //... If released at end of drag, write shape into the BufferedImage,
        //    which saves it in the drawing.
        _end = e.getPoint();      // Set end point of drag.
        if (_state == State.DRAGGING) {
            _state = State.IDLE;
           
            //... Draw current shape in saved buffered image.
            drawCurrentShape(_bufImage.createGraphics());
           
            this.repaint();
        }
    }

Press the mouse button: it creates a start point .
Drag the mouse (mouse button down, move mouse): it redraws the shape based on where you move.
Release the button: the shape is drawn to the actual image.

Let's say we only want it to act like the pencil in MsPaint. How does it act?
Press the mouse button: draw a rectangle to the actual image.
Drag the mouse: draw a rectangle to the actual image.
Release the button: do nothing.

Code for this could look something like:

Code:
    //============================================================= mousePressed
    public void mousePressed(MouseEvent e) {
        drawSomethingHere(e.getPoint(), _bufImage.createGraphics());
    }
   
    //============================================================= mouseDragged
    public void mouseDragged(MouseEvent e) {
        drawSomethingHere(e.getPoint(), _bufImage.createGraphics());
    }
   
    //============================================================ mouseReleased
    public void mouseReleased(MouseEvent e) {
        //Do nothing
    }

Where drawSomethingHere(e.getPoint(), _bufImage.createGraphics()) is your own function. It should draw a rectangle (or circle or teapot) at the point (first argument) to the graphics context (second argument).
Logged

programming • free software
animal liberation • veganism
anarcho-communism • intersectionality • feminism
mesotes
Level 0
**


<3


View Profile
« Reply #10 on: May 21, 2010, 07:01:18 AM »

yeah I already do that. but mouseDragged() is a little slow and cant process all the mouse positions when you move your mouse, resulting in missing pixels.
to fill in the "gaps" you can use drawLine but thats not pretty either.
Logged
Dacke
Level 10
*****



View Profile
« Reply #11 on: May 21, 2010, 07:17:54 AM »

Those are your options Shrug
Drawing a line of some sort works surprisingly well. It's what most "real" programs use most of the time.
Logged

programming • free software
animal liberation • veganism
anarcho-communism • intersectionality • feminism
Chromanoid
Level 10
*****



View Profile
« Reply #12 on: May 21, 2010, 07:19:19 AM »

you never get all mouse positions, there are always gaps. All tools (from ms paint to photoshop) have to handle that. draw in ms paint so you can check the mouse sample rate reached by a non-java-program ...
Logged
Dacke
Level 10
*****



View Profile
« Reply #13 on: May 21, 2010, 07:26:58 AM »

I think they have very similar sample rates.
But apparently¹ some professional programs use smoothing algorithms (interpolating/anti-aliasing). But at least in my own Java-paint-program, lines looked good enough  Smiley

1) http://forums.sun.com/thread.jspa?threadID=5387382
Logged

programming • free software
animal liberation • veganism
anarcho-communism • intersectionality • feminism
Chromanoid
Level 10
*****



View Profile
« Reply #14 on: May 21, 2010, 07:50:05 AM »

I think using the MouseInfo Class could lead to improvements of the sample rate (as mentioned in the thread).
Logged
Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic