I am trying to implement a click and drag method, for which I need mousePressed and mouseReleased events. I will also be using mouseClicked events, so I implemented MouseMotionListener and MouseListener.
However, when I go to write mousePressed, mouseReleased, mouseEntered, mouseExited methods I get the following error:
method mousePressed(MouseEvent) is already defined in class BoingPanel
Here is the entire class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JPanel;
public class BoingPanel extends JPanel implements MouseMotionListener, MouseListener {
private int width;
private int height;
private int updateRate=40;
ArrayList<Ball> balls;
ArrayList<Line> lines;
private Container box;
private boolean drag = false;
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public BoingPanel()
{
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
lines.add(new Line(0, height, width, height));
gameStart();
}
public BoingPanel(int x, int y)
{
width=x;
height=y;
balls = new ArrayList<Ball>();
balls.add(new Ball(100,0)); // adds test ball
balls.get(0).setXVelocity(5);
balls.add(new Ball(100,0));
balls.add(new Ball(400,50));
lines = new ArrayList<Line>();
box = new Container(width, height);
gameStart();
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public void gameStart() {
// Run the game logic in its own thread.
Thread gameThread = new Thread() {
public void run() {
while (true) {
// Execute one time-step for the game
update();
// Refresh the display
repaint();
// Delay and give other thread a chance
try {
Thread.sleep(1000 /updateRate);
} catch (InterruptedException ex) {}
}
}
};
gameThread.start(); // Invoke GaemThread.run()
}
private void update()
{
for(Ball a:balls) //calls balls updated position
{
a.update(box);
}
}
public void paintComponent(Graphics g)
{
box.paint(g);
for(Ball a:balls) //calls balls updated position
{
a.paint(g);
}
for(Line b:lines) //draws lines
{
b.paint(g);
}
}
public void actionPerformed(ActionEvent e)
{
update(); //changes ball position
repaint(); //refreshes image
}
}
What is causing this error? Thanks!
I would suggest this, just below your variable declarations and before you constructor, isn't helping...
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
You've basically implemented these methods twice. Just before and after the constructor.
Simply remove on of these groups of declarations...
please remove public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { } and then try
Related
I'm not sure why the fr.repaint(); method isn't working here. If I use the set visible false, then set it true after making changes it makes the screen go black which isn't what I'm trying to do.
Any help?
This code is for a school project, so if it's possible please provide somewhat detailed explanation to understand.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
class Main {
static int startingposx;
static int startingposy;
static int endingposx;
static int endingposy;
public static void main(String[] args) {
JFrame fr = new JFrame();
fr.setBounds(10,10,512,512);
fr.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
fr.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
startingposx = e.getX();
startingposy = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
endingposx = e.getX();
endingposy = e.getY();
//fr.setVisible(false);// i tried to use this to refresh it but it makes the frame black for a second
JPanel x = new JPanel(){
#Override
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(startingposx-(32-15),startingposy-32,30,30);
g.setColor(Color.BLUE);
g.fillRect(endingposx-(32-15),endingposy-32,30,30);
}
};
fr.add(x);
fr.repaint();// why does this not work??
//fr.setVisible(true);
System.out.print("\033[H\033[2J");
System.out.println("starting pos: " + startingposx+ ","+ startingposy+"\n" + "ending pos: " + endingposx+ "," + endingposy);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame made shorter in height purely to save space in answer
See further comments in the code. Note that the blue rectangle completely covers the red rectangle.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestCustomPaint {
// Don't use static! Make them instances of the x class and give it a constructor
static int startingposx;
static int startingposy;
static int endingposx;
static int endingposy;
public static void main(String[] args) {
JFrame fr = new JFrame();
// this is the wrong size if the content should be square
fr.setBounds(10,10,512,512);
// unused MouseMotionListener removed
fr.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) { }
#Override
public void mousePressed(MouseEvent e) {
startingposx = e.getX();
startingposy = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
endingposx = e.getX();
endingposy = e.getY();
fr.repaint();
System.out.print("\033[H\033[2J");
System.out.println("starting pos: " + startingposx+ ","+ startingposy+"\n" +
"ending pos: " + endingposx+ "," + endingposy);
}
#Override
public void mouseEntered(MouseEvent e) { }
#Override
public void mouseExited(MouseEvent e) { }
});
// This is when the panel should be created and added.
JPanel x = new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(startingposx-(32-15),startingposy-32,30,30);
g.setColor(Color.BLUE);
g.fillRect(endingposx-(32-15),endingposy-32,30,30);
}
};
fr.add(x);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I'm trying to print a color of the current pixel on mouse move event. I have this code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class PixelWizard extends JFrame {
public PixelWizard() {
addMouseMotionListener(new MouseListenerImpl());
setVisible(true);
}
public static void main(String[] args) {
PixelWizard pixelWizard = new PixelWizard();
}
}
class MouseListenerImpl implements MouseMotionListener {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("moved event");
mouseDragged(e);
}
#Override
public void mouseDragged(MouseEvent e) {
try {
Robot robot = new Robot();
robot.delay(2000);
Point coord = MouseInfo.getPointerInfo().getLocation();
Color color = robot.getPixelColor((int) coord.getX(), (int) coord.getX());
String hex = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
System.out.println(hex);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
But it does nothing.
There is no need to invoke mouseDragged whenever mouseMoved is invoked:
class MouseListenerImpl implements MouseMotionListener {
private Robot robot;
MouseListenerImpl() {
try {
robot = new Robot(); //construct a robot once
} catch (AWTException ex) {
ex.printStackTrace();
}
}
#Override
public void mouseMoved(MouseEvent e) {
printColor(e);
}
#Override
public void mouseDragged(MouseEvent e) {
printColor(e);
}
private void printColor(MouseEvent e) {
Color color = robot.getPixelColor(e.getX(), e.getY());
String hex = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
System.out.println(hex);
}
}
I am trying to make code that adds a label when I click and then removes the label when I press e. Can someone help me do this
I added the labels and I got it to compile but the label won't show up and its for my graphics project I worked on it really hard
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.awt.Label;
public class Volcano_Client extends Applet implements MouseListener, KeyListener, Runnable
{
Label label1;
boolean pickE=false;
boolean play = true;
boolean makeLava=false;
Thread t;
Thread thr;
Thread th;
boolean mouseEntered;
int count;
Volcano v1;
public void init()
{
label1 = new Label("You see lava flowing down as you press e");
v1 = new Volcano();
thr=new Thread(this);
thr.start();
t=new Thread(this);
t.start();
th= new Thread(this);
count=0;
addMouseListener(this);
addKeyListener(this);
}
public void keyTyped(KeyEvent k)
{
}
public void keyReleased(KeyEvent k)
{
}
public void keyPressed(KeyEvent k)
{
if(k.getKeyCode() ==KeyEvent.VK_E)
{
pickE=true;
repaint();
k.consume();
}
}
public void mouseExited(MouseEvent me)
{
mouseEntered=false;
repaint();
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
mouseEntered=true;
repaint();
}
public void mouseClicked(MouseEvent me)
{
if(mouseEntered==true)
{
makeLava=true;
}
else
{
makeLava=false;
}
repaint();
}
public void run()
{
while(play==true)
{
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
repaint();
}
while(true)
{
try{
Thread.sleep(20);
}
catch(Exception e){};
repaint();
}
}
public void stop()
{
}
public void start()
{
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
label1 = new Label("You see lava flowing down as you press e");
v1.makeVolcano(g2);
if(makeLava)
{
v1.makeLavaUp(g2);
g.setColor(Color.black);
g.drawString("KABOOM!!!",200,70);
add(label1);
}
else
{
g.setColor(Color.white);
g.drawString("Please Click For Eruption part 1",160,250);
}
if(pickE)
{
v1.makeLavaFlow(g2);
remove(label1);
}
else
{
//g.setColor(Color.white);
//g.drawString("Please press 'E' for Eruption part 2",160,276);
}
}
}
To display the label, below is modified init() function:
public void init()
`{`
`label1 = new Label("You see lava flowing down as you press e");`
//v1 = new Volcano();
thr=new Thread(this);
thr.start();
t=new Thread(this);
t.start();
th= new Thread(this);
count=0;
addMouseListener(this);
addKeyListener(this);
add(label1); //to display label
}
I made a Frame which repaints itself when I click on it(also the new geometric figure is painted) but when I click rapidly It does not responds so fast, it needs like half a sec beetween clicks. What have I done wrong?
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Okienko extends Frame implements MouseListener{
public static final int SIZE = 500;
public static int mX = 0,mY = 0;
public ArrayList<Wyrysowywalny> l; //COLLECTION OF OBJECT TO DRAW
Okienko(){
l = new ArrayList<Wyrysowywalny>();
createGUI();
}
public void createGUI(){
setSize(SIZE, SIZE);
setVisible(true);
setAlwaysOnTop(true);
setTitle("Zadanie 1");
addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
#Override
public void windowClosing(WindowEvent arg0) {
JOptionPane.showConfirmDialog(null, "dziekujemy za skorzystanie z programu","",JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
#Override
public void windowActivated(WindowEvent arg0) {
repaint();
}
});
addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {/// IMPORTANT!
System.out.println(e.getX() + " " + e.getY());
mX = e.getX();
mY = e.getY();
int r;
r = (int) (Math.random() * 6);
switch(r){
case 0: l.add(new Trojkat(mX,mY,lXY(),lXY(),lXY(),lXY()));break; // OBJECTS TO DRAW
case 1: l.add(new Prostokat(mX,mY,lR(),lR()));break;
case 2: l.add(new Kwadrat(mX,mY,lR()));break;
case 3: l.add(new Kolo(mX,mY,lR()));break;
case 4: l.add(new Elipsa(mX,mY,lR(),lR())); break;
case 5: l.add(new TrojkatRownoboczny(mX,mY,lR())); break;
}
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {}
#Override
public void mouseExited(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent arg0) {}
#Override
public void mouseReleased(MouseEvent arg0) {}
public static int lXY(){
return (int) (Math.random()*SIZE * 4d/5 + 1d/40*SIZE);
}
public static int lR(){
return (int) (Math.random()*200 - 1d/40*SIZE);
}
public void paint(Graphics g){
super.paint(g);
for(Wyrysowywalny w : l)
w.draw(g);//DRAW OBJECT
}
public static void main(String[] args) {
new Okienko();
}
}
Absent a complete example, I can only make several observations:
Instead of mouseClicked(), which fires when the mouse is released in the same component, you may want to respond to mousePressed().
Also consider MouseAdapter over implements MouseListener.
As mentioned here, "Swing programs should override paintComponent() instead of overriding paint()."
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
A more elaborate example with no perceptible latency is cited here.
I'm trying to create an applet that draws a circle (defined as an object) to the screen then this circle can be dragged across the screen using the mouse. So far when the mouse is pressed the object is drawn and can be dragged, but what I want it to do is draw the object when the applet is started then allow the user to click on the object and drag it. Any help or clues would be much appreciated. here is the code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class sheepDog extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
manAndDog dog;
int xposR;
int yposR;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void paint(Graphics g)
{
dog.display(g);
}
public void actionPerformed(ActionEvent ev)
{}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
dog = new manAndDog(xposR, yposR);
xposR = e.getX();
yposR = e.getY();
repaint();
}
}
class manAndDog implements MouseListener, MouseMotionListener
{
int xpos;
int ypos;
int circleWidth = 30;
int circleHeight = 30;
Boolean mouseClick;
public manAndDog(int x, int y)
{
xpos = x;
ypos = y;
mouseClick = true;
if (!mouseClick){
xpos = 50;
ypos = 50;
}
}
public void display(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(xpos, ypos, circleWidth, circleHeight);
}
public void mousePressed(MouseEvent e)
{
mouseClick = true;
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
if (mouseClick){
xpos = e.getX();
ypos = e.getY();
}
}
}
Thanks
In the start method of your applet, assign a location for the manAndDog object and call repaint
Reimeus is more correct, the init method is a better place to initalise the manAndDog.
Hope you don't mind some feedback ;)
You should be calling super.paint(g) in your paint method. In fact, I'd encourage you to use JApplet and override paintComponent, but that's just me
I don't see the need to continuously recreate the manAndDog object.
For example. If you added a method setLocation, you could simply call 'setLocation` when the mouse is dragged.
public void mouseDragged(MouseEvent e) {
dog.setLocation(xposR, yposR);
xposR = e.getX();
yposR = e.getY();
repaint();
}
This is more efficient as it's not continuously creating short lived objects. It also means you can do more with the manAndDog object, such as apply animation. IMHO
The simplest way is to create the ManAndDog object in your init() method, something like:
dog = new ManAndDog(0, 0);