I have written a very basic paint program in java using AWT and Swing. I have separated the program into two different class files; one of them holds the JFrame
and adds a custom panel (this custom panel being the second class file, extending JPanel
).
In my first try, I tried using Timer
and an ActionListener
with repaint()
but that seemed very very laggy (I could not draw straight lines/curves, they would always be laggy when I dragged my mouse fast.)
Then I switched to using a different approach (stored previous x and y locations and drew a line between the current position and the previous location). Here are the two class files:
The custom JPanel
class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Panel extends JPanel
{
// PROPERTIES
private final int DEFAULT_WIDTH = 800;
private final int DEFAULT_HEIGHT = 800;
private final Color BACK_COLOR = Color.WHITE;
private int x1, y1, x2, y2;
private MyMouseHandler handler;
private Graphics g;
// CONSTRUCTOR
public Panel()
{
setBackground( BACK_COLOR );
setPreferredSize( new Dimension( DEFAULT_WIDTH, DEFAULT_HEIGHT ) );
handler = new MyMouseHandler();
this.addMouseListener( handler );
this.addMouseMotionListener( handler );
}
// METHOD
public void paintComponent(Graphics g)
{
super.paintComponent(g);
}
private void setUpDrawingGraphics()
{
g = getGraphics();
}
// INNER CLASS
private class MyMouseHandler extends MouseAdapter
{
public void mousePressed( MouseEvent e )
{
x1 = e.getX();
y1 = e.getY();
System.out.println("Mouse is being pressed at X: " + x1 + " Y: " + y1);
setUpDrawingGraphics();
x2=x1;
y2=y1;
}
public void mouseDragged( MouseEvent e )
{
x1 = e.getX();
y1 = e.getY();
System.out.println("Mouse is being dragged at X: " + x1 + " Y: " + y1);
g.drawLine(x1,y1,x2,y2);
x2=x1;
y2=y1;
}
}
}
and the JFrame
class with the main
method:
import java.awt.*;
import javax.swing.*;
public class RunPanel
{
public static void main(String[] args)
{
JFrame frame = new JFrame( "Run Panel" );
frame.setDefaultCloseOperation(3);
Panel panel = new Panel();
frame.add( panel );
frame.pack();
frame.setVisible( true );
}
}
The program works fine, I can draw normal curves at low mouse speed. But again, as I increase the mouse speed the lines/curves start the get jaggy and ugly.
Maybe this is because I am drawing lines in between the positions, but drawing individual pixels look MUCH worse.
NOTE: I have gathered the two classes into one class file and the program stopped the lag. What is causing this? You can see the code here.