Jump to content




Recent Status Updates

  • Photo
      30 Sep
    rhossis

    laptop hard disk seated beneath motherboard but with no access panel. 7 hours to replace :(

    Show comments (3)
  • Photo
      19 Sep
    Chall

    I love it when you go to write a help thread, then while writing, you reach an enlightenment, and figure it out yourself.

    Show comments (3)
View All Updates

Developed by Kemal Taskin
Photo
- - - - -

Java Mini-Paint Program

setpreferredsize

  • Please log in to reply
15 replies to this topic

#1 NomNom

NomNom

    CC Lurker

  • New Member
  • Pip
  • 9 posts

Posted 08 August 2010 - 07:39 PM

Okay, all you Java programmers out there! Here's my first tutorial! The last time I checked, there wasn't a Java paint program out here yet, so hopefully I'm the first. This tutorial will cover pretty much all of the code involved, so I guess this counts as a beginner tut. So, in this program that we'll be making(if you do it right), you'll be able to draw on a blank white canvas, change the colors of your brush, and clear it! Enough chat, let's do it!

Things needed before-code:
Okay, so some things that you'll need to do before the code is make an 16x16 GIF for each of the colors that we'll have, so you'll need a blue, green, magenta, black, and red GIF (create seperate GIFs. It's not that hard. Just go to Microsoft Paint[if you're using a Microsoft OS], make a 16x16 image and fill the canvas with that color). Or, you could use mine, which are attached. =D

Remember to save the GIFs as the names of the GIFs in the code, or just change the code to fit your file names.



Something else to do(I guess you don't have to, but I like to keep things organised), is to create a Paint folder and store all your code and images in it.

Now that you've done all that, we can get to the actual code =]


/* 
 * Code by NomNom /*
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class paint{
	public static void main(String[] args){
		Icon iconB = new ImageIcon("blue.gif");
		//the blue image icon
		Icon iconM = new ImageIcon("magenta.gif");
		//magenta image icon
		Icon iconR = new ImageIcon("red.gif");
		//red image icon
		Icon iconBl = new ImageIcon("black.gif");
		//black image icon
		Icon iconG = new ImageIcon("green.gif");
		//finally the green image icon
		//These will be the images for our colors.
		
		JFrame frame = new JFrame("Paint It");
		//Creates a frame with a title of "Paint it"
		
		Container content = frame.getContentPane();
		//Creates a new container
		content.setLayout(new BorderLayout());
		//sets the layout
		
		final PadDraw drawPad = new PadDraw();
		//creates a new padDraw, which is pretty much the paint program
		
		content.add(drawPad, BorderLayout.CENTER);
		//sets the padDraw in the center
		
		JPanel panel = new JPanel();
		//creates a JPanel
		panel.setPreferredSize(new Dimension(32, 68));
		panel.setMinimumSize(new Dimension(32, 68));
		panel.setMaximumSize(new Dimension(32, 68));
		//This sets the size of the panel
		
		JButton clearButton = new JButton("Clear");
		//creates the clear button and sets the text as "Clear"
		clearButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.clear();
			}
		});
		//this is the clear button, which clears the screen.  This pretty
		//much attaches an action listener to the button and when the
		//button is pressed it calls the clear() method
		
		JButton redButton = new JButton(iconR);
		//creates the red button and sets the icon we created for red
		redButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.red();
			}

		});
		//when pressed it will call the red() method.  So on and so on =]
		
		JButton blackButton = new JButton(iconBl);
		//same thing except this is the black button
		blackButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.black();
			}
		});
		
		JButton magentaButton = new JButton(iconM);
		//magenta button
		magentaButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.magenta();
			}
		});
		
		JButton blueButton = new JButton(iconB);
		//blue button
		blueButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.blue();
			}
		});
		
		JButton greenButton = new JButton(iconG);
		//green button
		greenButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.green();
			}
		});
		blackButton.setPreferredSize(new Dimension(16, 16));
		magentaButton.setPreferredSize(new Dimension(16, 16));
		redButton.setPreferredSize(new Dimension(16, 16));
		blueButton.setPreferredSize(new Dimension(16, 16));
		greenButton.setPreferredSize(new Dimension(16,16));
		//sets the sizes of the buttons
		
		panel.add(greenButton);
		panel.add(blueButton);
		panel.add(magentaButton);
		panel.add(blackButton);
		panel.add(redButton);
		panel.add(clearButton);
		//adds the buttons to the panel
		
		content.add(panel, BorderLayout.WEST);
		//sets the panel to the left
		
		frame.setSize(300, 300);
		//sets the size of the frame
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//makes it so you can close
		frame.setVisible(true);
		//makes it so you can see it
	}
}


class PadDraw extends JComponent{
	Image image;
	//this is gonna be your image that you draw on
	Graphics2D graphics2D;
	//this is what we'll be using to draw on
	int currentX, currentY, oldX, oldY;
	//these are gonna hold our mouse coordinates

	//Now for the constructors
	public PadDraw(){
		setDoubleBuffered(false);
		addMouseListener(new MouseAdapter(){
			public void mousePressed(MouseEvent e){
				oldX = e.getX();
				oldY = e.getY();
			}
		});
		//if the mouse is pressed it sets the oldX & oldY
		//coordinates as the mouses x & y coordinates
		addMouseMotionListener(new MouseMotionAdapter(){
			public void mouseDragged(MouseEvent e){
				currentX = e.getX();
				currentY = e.getY();
				if(graphics2D != null)
				graphics2D.drawLine(oldX, oldY, currentX, currentY);
				repaint();
				oldX = currentX;
				oldY = currentY;
			}

		});
		//while the mouse is dragged it sets currentX & currentY as the mouses x and y
		//then it draws a line at the coordinates
		//it repaints it and sets oldX and oldY as currentX and currentY
	}

	public void paintComponent(Graphics g){
		if(image == null){
			image = createImage(getSize().width, getSize().height);
			graphics2D = (Graphics2D)image.getGraphics();
			graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			clear();

		}
		g.drawImage(image, 0, 0, null);
	}
	//this is the painting bit
	//if it has nothing on it then
	//it creates an image the size of the window
	//sets the value of Graphics as the image
	//sets the rendering
	//runs the clear() method
	//then it draws the image


	public void clear(){
		graphics2D.setPaint(Color.white);
		graphics2D.fillRect(0, 0, getSize().width, getSize().height);
		graphics2D.setPaint(Color.black);
		repaint();
	}
	//this is the clear
	//it sets the colors as white
	//then it fills the window with white
	//thin it sets the color back to black
	public void red(){
		graphics2D.setPaint(Color.red);
		repaint();
	}
	//this is the red paint
	public void black(){
		graphics2D.setPaint(Color.black);
		repaint();
	}
	//black paint
	public void magenta(){
		graphics2D.setPaint(Color.magenta);
		repaint();
	}
	//magenta paint
	public void blue(){
		graphics2D.setPaint(Color.blue);
		repaint();
	}
	//blue paint
	public void green(){
		graphics2D.setPaint(Color.green);
		repaint();
	}
	//green paint

}


//good job, you've made your paint program =]


Yeah! You've made it through. Hopefully this helped someone with something. Thanks!

-NomNom

Attached Thumbnails

  • magenta..GIF
  • red..GIF
  • green..GIF
  • blue..GIF
  • black..GIF

Edited by NomNom, 23 August 2010 - 03:36 PM.

  • 2

#2 NomNom

NomNom

    CC Lurker

  • New Member
  • Pip
  • 9 posts

Posted 23 August 2010 - 03:32 PM

So, reply if you like it, or reply if you don't like it. Thanks!
  • 0

#3 farrell2k

farrell2k

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 157 posts

Posted 23 August 2010 - 05:08 PM

I have not tried it, yet, but I did peruse the code, and it looks interesting. I'll try it out when I have time. Thanks for making the java tut forum more exciting. This forum needs more excitement.
  • 0

#4 Crashnboboom

Crashnboboom

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 21 November 2010 - 04:23 PM

Hey. I'm a newbie when it comes to java programming so if I sound dumb, so be it.
If I wanted to add buttons that change the tool in use. Like, a square or circle tool instead of the default pencil, how would I go about doing that?
  • 0

#5 NomNom

NomNom

    CC Lurker

  • New Member
  • Pip
  • 9 posts

Posted 21 November 2010 - 05:46 PM

Hey. I'm a newbie when it comes to java programming so if I sound dumb, so be it.
If I wanted to add buttons that change the tool in use. Like, a square or circle tool instead of the default pencil, how would I go about doing that?


Okay. So, the button part:

//this is in the paint class, not the PadDraw class

Icon iconWhatever = new ImageIcon("whatever.gif");


JButton whateverButton = new JButton(iconWhatever);
		//green button
		whateverButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				drawPad.whatever();
                                //this here goes to the drawPad (it's a PadDraw class that we made, so technically it goes into the class)
                                //so this goes to the method in PadDraw, that we shall add next
			}
		});

Okay, PadDraw modification:

//at the bottom-ish add this:
public void whatever(){
		//you put whatever code you want in here...
                //I set this up the way it is so we could link the PadDraw methods to the paint class (via buttons)
	}

  • 0

#6 NomNom

NomNom

    CC Lurker

  • New Member
  • Pip
  • 9 posts

Posted 21 November 2010 - 05:48 PM

So yes, once I can get to my jumpdrive I'll update the tut (it has a brush, straight line, and eraser tool).
  • 0

#7 leetou

leetou

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 05 December 2010 - 02:56 PM

Thanks a lot for all the help. This tutorial really was easy to understand, and the code as well.
  • 0

#8 leetou

leetou

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 13 December 2010 - 08:36 PM

I was just wondering, how would you get the program to switch between the pencil and the brush. I see your code above. Also, how would you get a smooth line with the graphics2D.fillOval?
  • 0

#9 NomNom

NomNom

    CC Lurker

  • New Member
  • Pip
  • 9 posts

Posted 14 December 2010 - 10:06 AM

Well, I have an updated program that switches with different tools using the code above. And sure, it's not the smoothest line, but it works and looks great. You can use graphics2D.drawLine, and that works, but it doesn't look as good as the fillOval. Thanks for the reply! Again, I'll update the tut when I get the time...
  • 0

#10 bruceoutdoors

bruceoutdoors

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Learning:Java

Posted 02 August 2012 - 12:18 AM

hey there I just checked out and test your code. Hope you're still here after more than a year XD

inside the mouseDragged method you have a line:

if(graphics2D != null)

that basically does nothing. I deleted that line and the program runs as if nothing happened. What's it for?...
  • 0

#11 bruceoutdoors

bruceoutdoors

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Learning:Java

Posted 02 August 2012 - 08:09 AM

Sup ppl! I felt that the code could be a bit more simplified so I made some changes:
  • the process of making a color button has been reduced. You don't need the .gif files, just specify a color for makeColorButton and it will generate a button from it. You could simply add a button by an addition of one line of code, it's functionality is also automatically resolved by the changeColor method:
    makeColorButton(Color.BLUE);
    
  • A class PaintWindow takes out most of the code from the main method. This makes the code more reusable.
there are other changes too(just check the code), but if you execute the code you'll notice it does exactly the same thing... except that you can't resize the window. I will recommend you to understand NomNom's original code before going through this one:


/*
* Code by NomNom (24 Aug 2010)
* modified by Bruceoutdoors(2 Aug 2012)
*/


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

public class paintModified
{
public static void main(String[] args)
{
PaintWindow frame = new PaintWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}

}

class PaintWindow extends JFrame
{
public PaintWindow()
{
setTitle("Paint it");
setSize(300, 300);

panel = new JPanel();
drawPad = new PadDraw();

panel.setPreferredSize(new Dimension(32, 68));

//Creates a new container
Container content = this.getContentPane();
content.setLayout(new BorderLayout());

//sets the panel to the left, padDraw in the center
content.add(panel, BorderLayout.WEST);
content.add(drawPad, BorderLayout.CENTER);

//add the color buttons:
makeColorButton(Color.BLUE);
makeColorButton(Color.MAGENTA);
makeColorButton(Color.RED);
makeColorButton(Color.GREEN);
makeColorButton(Color.BLACK);

//creates the clear button
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
drawPad.clear();
}
});
panel.add(clearButton);
}

/*
* makes a button that changes the color
* @param color the color used for the button
*/

public void makeColorButton(final Color color)
{
JButton tempButton = new JButton();
tempButton.setBackground(color);
tempButton.setPreferredSize(new Dimension(16, 16));
panel.add(tempButton);
tempButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
drawPad.changeColor(color);
}
});
}

private JPanel panel;
private PadDraw drawPad;
}

class PadDraw extends JComponent
{
//this is gonna be your image that you draw on
Image image;
//this is what we'll be using to draw on
Graphics2D graphics2D;
//these are gonna hold our mouse coordinates
int currentX, currentY, oldX, oldY;

public PadDraw()
{
setDoubleBuffered(false);
addMouseListener(new MouseAdapter()
{
//if the mouse is pressed it sets the oldX & oldY
//coordinates as the mouses x & y coordinates
public void mousePressed(MouseEvent e)
{
oldX = e.getX();
oldY = e.getY();
}
});

addMouseMotionListener(new MouseMotionAdapter()
{
//while the mouse is dragged it sets currentX & currentY as the mouses x and y
//then it draws a line at the coordinates
//it repaints it and sets oldX and oldY as currentX and currentY
public void mouseDragged(MouseEvent e)
{
currentX = e.getX();
currentY = e.getY();

graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();

oldX = currentX;
oldY = currentY;
}
});
}

//this is the painting bit
//if it has nothing on it then
//it creates an image the size of the window
//sets the value of Graphics as the image
//sets the rendering
//runs the clear() method
//then it draws the image
public void paintComponent(Graphics g)
{
if(image == null)
{
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

clear();
}

g.drawImage(image, 0, 0, null);
}

//this is the clear
//it sets the colors as white
//then it fills the window with white
//thin it sets the color back to black
public void clear()
{
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
repaint();
}

public void changeColor(Color theColor)
{
graphics2D.setPaint(theColor);
repaint();
}
}

  • 2

#12 NomNom

NomNom

    CC Lurker

  • New Member
  • Pip
  • 9 posts

Posted 02 August 2012 - 10:01 AM

Nice! Haha, I kinda forgot I put this up... It was awhile ago, when I was a less experienced coder... Thanks for improving the code! Hope you found it interesting... Yeah, I have no idea why the if(graphics2D != null) is there... I guess I might've forgotten to take it out at some point? lol... Anyways, thanks again!
  • 0





Also tagged with one or more of these keywords: setpreferredsize