Drawing Graphics is too slow - java

So, I have this project, and you can draw images in it. I wanted people to be able to draw on it, but at first it was too slow when I was using repaint() So i used the repaint(Rectangle r) tool. It's better, but still not the speed i was looking for.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawingPad extends JPanel implements MouseListener,MouseMotionListener,ListSelectionListener{
public Color[][] picture = new Color[601][601];
public Color selected;
public String action;
public Maker m;
private static final long serialVersionUID = 1L;
public DrawingPad(Maker m){
this.m = m;
this.setPreferredSize(new Dimension(600,600));
this.setVisible(true);
for (int x = 1;x<=600;x++){
for (int y = 1; y<=600;y++){
picture[x][y]=Color.WHITE;
}
}
}
public void addColor(int x, int y){
try{
picture[x][y]=selected;
repaint(new Rectangle(x,y,x,y));
}catch (Exception e){
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.clearRect(0, 0, 600, 600);
for (int x = 1;x<=600;x++){
for (int y = 1; y<=600;y++){
g.setColor(picture[x][y]);
g.drawLine(x, y, x, y);
}
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
for (int x = -1;x<=1;x++){
for (int y = -1;y<=1;y++){
this.addColor(e.getX()+x, e.getY()+y);
}
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource()==m.seeit){
selected = m.colors[m.seeit.getSelectedIndex()];
}else{
action=(String) m.actions.getSelectedValue();
}
}
}

You might want to look into drawing that which will not be changed into a BufferedImage, and then displaying that BufferedImage in the paintComponent method as a background image.
For example, please have a look at this link and also this one.

Related

How can I either reset the coordinates of this Buffered Image or put this Buffered Image in the rectangle?

I imported this "troll face" into my code as my enemy which rains from top of the screen to the bottom. But before doing so I created the pink rectangles so that I can overlay the troll face image on top of the rectangles. However, when I set the coordinates of the image equal to the rectangle, you can see that it did not center. I then set one troll face image's coordinate equal to (0,0) and you can see that it is clearly far away from the origin.
I tried to import a different PNG image but in vain and it did not work.
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class magazinerain extends GameDriverV4{
LinkedList<rainingenemies> r = new LinkedList<rainingenemies>();
rainingenemies variable;
BufferedImage trollface;
public magazinerain() {
trollface = this.addImage("minion.png");
}
public void faller(Graphics2D win) {
for (int i = 0; i<r.size(); i++) {
variable=r.get(i);
variable.fall(win);
if (variable.getY()>=800) {
delete(variable);
}
}
}
public void draw(Graphics2D win) {
int count = 0;
win.drawImage(trollface, 0, 0,null);
for (int i = 0; i < r.size(); i++) {
variable = r.get(i);
variable.fall(win);
//win.drawImage(trollface, (int) variable.getX(), (int) variable.getY(),null);
//the images are not correctly centered on the screen
//win.drawImage(trollface, 400, 400,null);
}
}
public void memorymanagement() {
for (int i = 0; i < r.size(); i++) {
variable = r.get(i);
//System.out.println(variable.getY());
if (variable.getY()>=800) {
r.remove(i);
//System.out.println("Removed");
}
}
}
public void checkintersects(int a, int b) {
int buffer = 10;
int buffery = 15;
for (int i = 0; i< r.size(); i++) {
variable = r.get(i);
//if (a>(variable.getX()-buffer) && (a<variable.getX()+buffer)) {
if ((variable.getX()>a-buffer-10)&& (variable.getX()<a+buffer+30)) {
//if ((b>variable.getY()-buffery) && (b<variable.getX()+buffery)) {
if ((variable.getY()>b-buffery) && (variable.getY()<b+buffery)){
r.remove(i);
System.out.println("spacex="+a+"getx="+variable.getX());
System.out.println("spacey="+b+"gety="+variable.getY());
}
}
}
}
public void delete(rainingenemies a) {
r.remove(a);
}
public void insert(rainingenemies a) {
r.add(a);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Specifically in this code, I expected the troll face to be at (0,0) but it is not there as shown in the screenshot

Multiple images one by one JPanel

I am trying to load images to JPanel from a directory (which contains only images) one by one. I want to crop the image one by one using mouse events. I wrote program for loading one image by giving it's path to JPanael and then cropping it using mouse. But i don't know how to extend program for multiple images one by one and saving the cropped ones in a different directory. I tried swing timer also but i could not figure how to use it. Can any please help me?
Here is my code for single image.
public class MainActivity extends JFrame implements MouseListener,MouseMotionListener{
int drag_status=0,c1,c2,c3,c4;
static String[] pathArray = new String[1000];
public static void main(String args[]) {
new MainActivity().start();
String s = "G:\\my pic";
File f = new File(s);
String str;
System.out.println(true);
//just to put all the pictures in list
File[] fa = f.listFiles();
for (int i=0; i< fa.length; i++) {
String path = fa[i].toString();
str = path.replace("\\", "\\\\");
pathArray [i] = str;
System.out.println(pathArray[2]); //gives all the paths in ImagePanel path format
}
}
public void start() {
ImageJPanel imageJPanel=new ImageJPanel(pathArray[1]);
add(imageJPanel);
setSize(200,200);
setVisible(true);
addMouseListener(this);
addMouseMotionListener( this );
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
c1=arg0.getX();
c2=arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
if(drag_status==1) {
c3=arg0.getX();
c4=arg0.getY();
try {
draggedScreen();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public void draggedScreen()throws Exception {
int width = c1 - c3;
int height = c2 - c4;
width = width * -1;
height = height * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,width,height));
File save_path=new File("C:\\Users\\apurvgandhwani\\Desktop\\cropped");
ImageIO.write(img, "JPG", save_path);
System.out.println("Saved to folder");
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
drag_status=1;
c3=arg0.getX();
c4=arg0.getY();
}
public void paint(Graphics g) {
super.paint(g);
int width = c1 - c3;
int height = c2 - c4;
width = width * -1;
height = height * -1;
if(width<0) width = width * -1;
g.drawRect(c1, c2, width, height); }
}
And ImageJPanel class
public class ImageJPanel extends JPanel{
private static final long serialVersionUID = 1L;
private Image image;
int x = 0;
public ImageJPanel(String image){
this(new ImageIcon(image).getImage());
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
x += 110;
if (x >= 1000) {
x = 1000;
((Timer)e.getSource()).stop();
}
repaint();
}
});
timer.start();
}
public ImageJPanel(Image image){
this.image = image;
Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g){
g.drawImage(image, 0, 0, null);
}
}

Changing a color of circle after mousePressed

I have to change a color of spot to 'red' when mousePressed, then it should be back to its original color when mouseRelease. This is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PanelTwo extends JPanel implements MouseListener{
public Spot spot = new Spot(100,100,20);
//public Color f = new Color(250,0,0);
public PanelTwo(){
super();
setLayout (new FlowLayout());
//setOpaque(true);
addMouseListener(this);
}
public void paintComponent(Graphics g){
spot.draw(g);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
spot.x=e.getX();
spot.y=e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
And there is another code with information about my shape
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Spot {
public int x,y,r;
public Color c= new Color(100,150,200);
public Color f = new Color(250,0,0);
public Spot(int X, int Y, int R){
x=X; y=Y; r=R;
}
public void draw(Graphics g){
g.setColor(c);
g.fillOval(x-r, y-r, 2*r, 2*r);
}
}
So, I want to change the color of this ball after I press my mouse, and after I release - it should come back to the original color.
When mousePressed is called, record the original color of spot and change its color
When mouseReleased is called, reset spot to its original color
i assume that the two colors in your class is the color when it is clicked and released. you can't change the color because you are setting the Graphics.setColor() method to a specific color which is c . try to make it more flexible.
public class Spot {
public int x,y,r;
public Color c= new Color(100,150,200);
public Color f = new Color(250,0,0);
//make the default color to c
public Color currentColor = c;
public Spot(int X, int Y, int R){
x=X; y=Y; r=R;
}
public void draw(Graphics g){
g.setColor(currentColor);
g.fillOval(x-r, y-r, 2*r, 2*r);
}
}
and in your mousePressed or mouseReleased just change the currentColor
#Override
public void mousePressed(MouseEvent e) {
spot.x=e.getX();
spot.y=e.getY();
spot.currentColor = spot.f;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
spot.x=e.getX();
spot.y=e.getY();
spot.currentColor = spot.c;
repaint();
}

Paint a rect on Jpanel with paintcomponent doesn't work

I want to draw a rect on a DrawPanel. This rect should be a object.
When I add it the place will be grey but the paintcomponent will not paint, so I see nothing.
The class Drawpanel.java will be add on the contentpane, the contentpane is on the JFrame.
import java.awt.event.*;
import java.awt.*;
import javax.swing.JPanel;
public class DrawPanel extends JPanel implements MouseListener{
private static final long serialVersionUID = 6725416157621860479L;
public DrawPanel() {
addMouseListener(this);
this.setLayout(null);
setPreferredSize(new Dimension(500, 500));
}
Graphics2D g2d = null;
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g2d = (Graphics2D)g;
System.out.println("paint!!!!!!!");
for (int i = 0; i < 1500; i++) {
if (i %10 == 0) {
g2d.setColor(new Color(242, 242, 242));
g2d.drawLine(0, i, 1500, i);// _
g2d.drawLine(i, 0, i, 1500);// |
}
}
g2d.setColor(Color.BLUE);
}
#Override
public void mouseClicked(MouseEvent arg0) {
if (START.modus != 4) {
return;
}
System.out.println("X_" + arg0.getX() + " | Y_"+arg0.getY());
int x = (arg0.getX()) - (arg0.getX()%10);
int y = (arg0.getY()) - (arg0.getY()%10);
System.out.println("x_" + x + " " + "y_" + y);
Dia d = new Dia(x, y);
d.setBounds(x, y, 50, 50);
add(d);
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
The object which will not be painted is:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Dia extends JPanel implements MouseListener {
private Point startcoord;
private int sizex = 50;
private int sizey = 20;
public Dia(int x, int y) {
super();
addMouseListener(this);
this.startcoord = new Point(x, y);
setPreferredSize(new Dimension(sizex, sizey));
}
#Override
public void paintComponents(Graphics g) {
super.paintComponents(g);
System.out.println("Diaaaaa1");
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(0, 0, 50, 50);
// g.setColor(Color.RED);
g.drawRect(0, 0, sizex, sizey);
g.setColor(Color.GREEN);
g.drawString("TEST", 3, 3);
System.out.println("Diaaaaa");
}
public Point getStartcoord() {
return startcoord;
}
public void setStartcoord(Point startcoord) {
this.startcoord = startcoord;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("diac");
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
Dia c = new Dia(10, 10);
//c.textsize();
JFrame a = new JFrame();
a.setVisible(true);
a.setSize(new Dimension(100, 100));
JPanel b = new JPanel();
a.add(b);
b.add(c);
}
}
When I start the main in the dia class I see nothing. Why dia will not start the paintcomponent method?
Really its simple you override another method paintComponents() but you need paintComponent(). Change that and all will be work.

freehand drawline using mouse events

may i know if there is any formula for drawing lines? currently i am implementing a freehand draw line in java, however the code below when drawn it is not what im expecting.
i have tried g.drawLine(arg0.getX(), arg0.getY(), arg0.getX(), arg0.getY()); , however the line drawn is not continous rather it is drawing points, i read that it is because the mouse drag happens at intervals, if so how should i record the points?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class STDrawingArea extends JPanel implements MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
public STDrawingArea()
{
setPreferredSize(new Dimension(1280, 700));
setBounds(0, 0, 1280, 700);
setBackground(Color.WHITE);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
xDragged = xPressed;
yDragged = yPressed;
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
xPressed = arg0.getX();
yPressed = arg0.getY();
System.out.println("xPressed: "+xPressed+" ,yPressed: "+yPressed);
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
xReleased = arg0.getX();
yReleased = arg0.getY();
System.out.println("xReleased: "+xPressed+" ,yReleased: "+yPressed);
}
}
A simple way to do this might be:
Maintain a List of Points in your component
In the mouseDragged() method, get the point (MouseEvent#getPoint()) and add it to your list
Override the paintComponent() method of the JPanel
Iterate over all points in your list of points
Draw lines between each pair of points (except the first and last, of course)
For example, you might make the following changes:
private ArrayList<Point> points = new ArrayList<Point>();
//...
public void mouseDragged(MouseEvent arg0) {
points.add(arg0.getPoint());
repaint(); //request Swing to refresh display as soon as it can
}
//...
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < points.size() - 2; i++)
{
Point p1 = points.get(i);
Point p2 = points.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
Some slight Changes are required
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xDragged, yDragged, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
}
and
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
xPressed = arg0.getX();
yPressed = arg0.getY();
System.out.println("xPressed: "+xPressed+" ,yPressed: "+yPressed);
xDragged=xPressed;
yDragged=yPressed;
}
I have compiled and executed this code and found its perfectly working..:-)
Try This. It's working. There is no need to use the Point class and iterate the 'for' loop, If you wanna simply make a Freehand Drawing.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class STDrawingArea extends JPanel implements MouseListener,MouseMotionListener,ActionListener
{
int xPressed,yPressed;
int xReleased,yReleased;
int xDragged,yDragged;
private JButton clear;
public STDrawingArea()
{
setPreferredSize(new Dimension(1200, 500));
setBounds(0, 0, 480, 500);
//setBackground(Color.YELLOW);
clear=new JButton("CLEAR");
add(clear);
clear.setBounds(540, 5, 100, 25);
clear.addActionListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==clear)
{
setOpaque(false);
repaint();
}
}
#Override
protected void paintComponent(Graphics g)
{
g.drawLine(xPressed,yPressed,xDragged,yDragged);
xPressed=xDragged;
yPressed=yDragged;
}
#Override
public void mouseDragged(MouseEvent arg0) {
Graphics g = getGraphics();
g.drawLine(xPressed, yPressed, arg0.getX(), arg0.getY());
xDragged = arg0.getX();
yDragged = arg0.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
setOpaque(true);
xPressed = arg0.getX();
yPressed = arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class Frame4 extends JFrame
{
private STDrawingArea da;
public Frame4()
{
da=new STDrawingArea();
da.setBackground(Color.YELLOW);
da.setLayout(new BorderLayout());
add(da);
}
}
public class FreeHandDrwing
{
public static void main(String s[])
{
Frame4 ob=new Frame4();
ob.setVisible(true);
ob.setBounds(100, 100, 1200, 500);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Categories

Resources