Java painting program giving many errors - java

I want to make a simple painting program. So,when you drag your mouse a line will draw in a GUI. The problem is when the user drags the mouse, it will paint automatically, but my code doesn't work. Can someone please tell me how do this? Sorry for my English and if you don't understand my question, look at my code maybe you will than.
My main class:
import javax.swing.JFrame;
public class MainClass {
public static void main(String args[]){
tuna kip = new tuna();
kip.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
kip.setSize(800,600);
kip.setVisible(true);
}
}
This is my other class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tuna extends JFrame {
JPanel jpanel = new JPanel();
public tuna(){
super("Painting Program");
jpanel.setBackground(Color.WHITE);
add(jpanel);
hand handler = new hand();
jpanel.addMouseListener(handler);
jpanel.addMouseMotionListener(handler);
}
private class hand implements MouseListener ,MouseMotionListener { //THE ERRORS START TO APPEAR HERE
public void mouseDragged(MouseEvent event){
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(event.getX(), event.getY(), 5, 5);
}
}
}
}

When I try to run the code I get too much error messages:
You mean when you try to compile the code you get compile errors.
class hand implements MouseListener ,MouseMotionListener
Your class does not implement all the methods in those listeners. You only implement one method.
Read the section from the Swing tutorial on How to Write a MouseMotionListener for a working example.
If you only care about the mouseDragged() method then you only need to implement the MouseMotionListener.
Or as a simpler solution you can extend MouseMotionAdapter. This class implements all the methods of the MouseMotionListener so you only need to override the methods you want to change. The tutorial also discusses adapters.
Finally class names SHOULD start with an upper case character. Look at the Java API and you will notice this. Follow the Java conventions and don't make up your own.

Yes, there are so many issues in your codes. I just edited it and make it runnable at least. Just study and experiment on it. I hope you will learn something out of this even if I don't explain all of the changes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tuna extends JFrame {
int x, y, w, h;
MyPanel jpanel = new MyPanel();
public tuna(){
super("Painting Program");
setLayout(new BorderLayout());
jpanel.setBackground(Color.WHITE);
add(jpanel);
hand handler = new hand();
jpanel.addMouseListener(handler);
jpanel.addMouseMotionListener(handler);
}
private class hand implements MouseListener , MouseMotionListener { //THE ERRORS START TO APPEAR HERE
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
x=e.getX();
y=e.getY();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
w = e.getX() - x;
h = e.getY() - y;
jpanel.repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
class MyPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(x, y, w, h);
}
}
}

Related

How Do I Add A MouseMotionListener Without Implementing It Within The Class?

I have a test coming up where you have to remember 9 small programs and write them. Problem is, I have a learning disorder and things often get very "foggy" for me where I can't remember things correctly - particularly big things.
The test is specifically "write these programs in the smallest way you can".
So I don't have to risk failure by fog - how can I implement a MouseMotionListener without implementing it?
The code my teacher provides:
import javax.swing.JFrame;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
public class One extends JFrame implements MouseMotionListener {
public One() {
this.setVisible(true);
this.setSize(400, 400);
}
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse being moved...");
}
public void mouseDragged(MouseEvent e) {
int x = e.getX(), y = e.getY();
System.out.println("(" + x + ", " + y + ")");
}
public static void main(String[] args) {
One a = new One();
a.addMouseMotionListener(a);
}
}
Specifically, I want to not have to worry about writing methods that are automatically implemented - as I have several other problems like this - but with much more empty implemented methods.
Smth. like this one?
public class One extends JFrame {
public One() {
setVisible(true);
setSize(400, 400);
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse being moved...");
}
});
}
public static void main(String[] args) {
One a = new One();
}
}

My game is flickering due to my painting directly in JFrame. How do I use JPanel? [duplicate]

I think I need to put some code where the comment is (or maybe use non static method but I am not sure). The main method creates the window and then starts the graphics method. I would like the blue square to flash.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paintTest extends JPanel{
private static JFrame theWindow = new JFrame("Window");
static boolean blueSqr = false;
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(10, 10, 10, 10);
if(blueSqr){
g.setColor(Color.BLUE);
g.fillRect(10, 10, 10, 10);
}
}
public static void main(String[] args){
createWindow();
theWindow.getContentPane().add(new paintTest());
while(true){
blueSqr = false;
System.out.println("off");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
blueSqr = true;
// Needs something here
System.out.println("on");
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
}
}
public static void createWindow(){
theWindow.setSize(500, 500);
theWindow.setLocationRelativeTo(null);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
Any help would be really good.
Use a Swing Timer to call repaint(). Also, override paintComponent() in a JPanel, rather than paint().
Something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintTest extends JPanel{
boolean blueSqr = false;
PaintTest() {
setPreferredSize(new Dimension(100,25));
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
blueSqr = !blueSqr;
repaint();
}
};
Timer timer = new Timer(1000,al);
timer.start();
}
public void paintComponent(Graphics g) {
Color c = (blueSqr ? Color.BLUE : Color.RED);
g.setColor(c);
g.fillRect(10, 10, 10, 10);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame theWindow = new JFrame("Window");
theWindow.getContentPane().add(new PaintTest());
createWindow(theWindow);
}
});
}
public static void createWindow(JFrame theWindow){
theWindow.pack();
theWindow.setLocationByPlatform(true);
theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theWindow.setVisible(true);
}
}
There were other improvements I could not be bothered documenting (code speaks louder than words). If you have any questions (check the docs first, then) ask.
your issues are
1) by calling Thread.sleep(int) in the Swing related code, never do that, for delaying in Swing (there are lots of topics about why not use sleep in programing languages ...) use Swing Timer
2) your JPanel doesn't returns any XxxSize
3) for Swing use paintComponent(), only if you have got really important reasons then use method paint() more about repaint and animating Graphics in the 2D Graphics tutorial
4) Swing GUI should be built in the Event Dispatch Thread

Drawing lines and deleting lines

I am trying to create a program that allows the user to drag and draw lines and also delete the lines after it have been drawn. Is there any ways i can do it? I have the code that draws the line but i am not sure how i could delete the lines after i have drawn it. Im looking to click any of the lines drawn and delete it with the delete button.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Drawing {
public Drawing() {
JFrame jf=new JFrame("Free Hand Drawing Example");
Board draw=new Board();
jf.add(draw);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(600,500);
jf.setVisible(true);
}
public static void main(String a[]){
new Drawing();
}
}
class Board extends JPanel implements MouseListener,MouseMotionListener {
ArrayList<pts> list = new ArrayList<pts>();
Point start,end;
public Board() {
start=null; /*Initializing*/
end=null;
//this.setBackground(Color.BLACK);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
#Override
public void paint(Graphics g)
{ Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
super.paint(g2);
//g.setColor(Color.BLACK);
for (pts p : list)
g.drawLine((int)p.getStart().getX(), (int)p.getStart().getY(), (int)p.getEnd().getX(), (int)p.getEnd().getY());
if(start!=null)
{
g.drawLine(start.x,start.y,end.x,end.y);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {}
#Override
public void mouseEntered(MouseEvent arg0) {}
#Override
public void mouseExited(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent me) {
start = me.getPoint();
}
#Override
public void mouseReleased(MouseEvent me) {
end = me.getPoint();
pts pt = new pts(start,end);
list.add(pt);
repaint();
for(pts p : list)
{
System.out.println(p.getStart()+""+p.getEnd());
}
start = null;
end = null;
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {}
}
class pts{
Point start = null;
Point end = null;
public pts(Point start, Point end){
this.start = start;
this.end = end;
}
public Point getStart(){
return this.start;
}
public Point getEnd(){
return this.end;
}
}
There is more than one way to go about this, but one simple approach would be to add a 'delete' button with an ActionListener that clears out the list of points you have when the button is pressed. You could also associate the clearing action with something like a MouseDragged event, but that doesn't seem very user friendly.
UPDATE:
So, to delete the line when the user clicks on it, you could use a simple function like this one:
public boolean intersects(Point linePoint1,
Point linePoint2,
Point usersClickPoint) {
return new Line2D.Float(linePoint1, linePoint2).
ptLineDist(usersClickPoint) <= 0.01;//some margin of error
}
in your MousePressed method.
Side Note: The way you've chosen to interpret the mouse events is a bit strange. You record the first point on MousePressed, and the second one on MouseReleased. Why not use MouseClicked and simply keep track of the first and second clicks when drawing the line?
One approach would be to create a Line object for each line your user draws and have the object store the locations on the screen where the line is drawn. Then when in delete mode, have an onClickListener that will select a line based upon the coordinates of the click matching up to a point contained in a line. Then just delete the line (probably could redraw using the same endpoints but with the pen set to the background color). There would need to be some logic for the possible case where lines intersect and you don't want to delete a portion of the other line, but that could be solved fairly easily. Keep in mind, I'm not a big graphics programmer. This is just my idea.

Displaying characters typed at mouse location in Java GUI

I have a Java exercise using KeyListeners that I have been stuck on for a while. Any help would be greatly appreciated. The exercise is:
"Write a program to get a character input from the keyboard and display the character where the mouse points."
I did some debugging and it seems like the KeyListener is never registering when a key is pressed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class EventProgrammingExercise10 extends JFrame {
CharPanel chars;
private int x;
private int y;
String s;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventProgrammingExercise10 frame = new EventProgrammingExercise10();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public EventProgrammingExercise10() {
setTitle("EventProgrammingExercise10");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
chars = new CharPanel();
chars.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
chars.repaint();
}
});
add(chars);
}
public void setX(int n) {
x = n;
}
public void setY(int n) {
y = n;
}
class MouseLocListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
setX(e.getX());
setY(e.getY());
}
}
class CharPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(String.valueOf('a'), x, y);
}
}
}
Thanks.
A KeyListener will only work if the component that owns it has the focus. You must first make your JPanel focusable, i.e., setFocusable(true), and then request that it have focus, i.e., requestFocusInWindow().
I wouldn't use a MouseListener at all. What I'd do if I had to use a KeyListener, and what I know works, would be:
Make my JPanel Focusable and have focus
Give it a BufferedImage that is exactly its size and draw this in its paintComponent method.
Add a KeyListener/KeyAdapter to it
In the KeyAdapter, keyPressed method, Use the MouseInfo class to get a PointerInfo object: PointerInfo pInfo = MouseInfo.getPointInfo()
Use PointerInfo to get the current mouse's location on screen via pInfo.getLocation();
Get the drawing JPanel's locationOnScreen.
Translate the mouse pointer location to one that is relative to that of the component's using simple vector graphics.
If the point is in bounds of the location, get a Graphics object from the BufferedImage
Draw the char in the BufferedImage
Repaint the JPanel
Look #Hovercraft and you forget to add the MouseLocListener. Than it works :)
chars.addMouseMotionListener(new MouseLocListener());
chars.setFocusable(true);
chars.requestFocusInWindow();
It looks like you should attach lKeyListener not to chars panel but to the frame itself.
This way KeyListener will allways work even if panel losses focus for any reason.

error in java code of performing mouselistener

hi i am performing a mouselistener action in my programm i am making a color jpanel when user click on panel it change its color but a line of code give some error like create a class e in your code but e is already declared as a instance of event class plz help me here is my code below.error is in this line "panel.addMouseListener(e);".
'import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class randomcolor extends JFrame{
JPanel panel;
public randomcolor (){
panel=new JPanel();
panel.setBackground(rancolor());
add(panel);
}
event e =new event();
panel.addMouseListener(e);
public Color rancolor(){
int r= (int) (Math.random()*256);
int g= (int) (Math.random()*256);
int b= (int) (Math.random()*256);
return (new Color(r,g,b));
}
public class event implements MouseListener{
public void mouseClicked(MouseEvent e) {
panel.setBackground(rancolor());
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
public static void main (String args[]){
randomcolor gui=new randomcolor();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(300, 300);
gui.setTitle("color panel");
}
}
Capitalize Event in event e = new event(). It should probably be Event e = new Event(). The formatting in your code looks odd; that might be hiding other formatting errors too.
Now that the code is properly formatted, I can see another problem; you probably meant to have
Event e = new Event();
panel.addMouseListener(e);
inside your constructor, instead of after that right curly brace.
Move statement panel.addMouseListener(e); to the constructor randomcolor(). This will solve the issue.

Categories

Resources