How do I access variables from a mouseClicked event? - java

I'm trying to get the x and y coordinates of a mouse click to do some calculations I need to do. I can't seem to find anything online with how to get the vars outside the anonymous method.
MouseListener listener = new MouseListener()
{
public void mousePressed(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public void mouseEntered(MouseEvent me) { }
public void mouseExited(MouseEvent me) { }
public void mouseClicked(MouseEvent me)
{
int x,y;
x = me.getX();
y = me.getY();
System.out.println("X:" + x + " Y:" + y);
}
};
frame.addMouseListener(listener);
//calculations with the x and y coordinates

You can declare the x and y variables outside of the anonymous class and initialize them inside the mouseClicked method. Here's an example:
int x;
int y;
MouseListener listener = new MouseListener()
{
public void mousePressed(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public void mouseEntered(MouseEvent me) { }
public void mouseExited(MouseEvent me) { }
public void mouseClicked(MouseEvent me)
{
x = me.getX();
y = me.getY();
System.out.println("X:" + x + " Y:" + y);
}
};
frame.addMouseListener(listener);
// calculations with the x and y coordinates
// you can now use the values of x and y here
By declaring the variables outside of the anonymous class, you can access them outside of the mouseClicked method.

Related

Making the getX() and getY() methods to get the locations of the panel, not the frame

I'm using the getX() and getY() methods in the MouseListener class to get the location of the panel, but it's getting the location of the frame instead, and that includes the top of the title bar and the sides, so it's not getting the location that I want. I also have the:
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
method in my paint class to override the frame so when you paint in graphics, and set the paint location of x, and y, it sets it to the panel location, and not the frame location, but I don't know how to make it so that the MouseListener class does the same. Please help. Thanks.
Code for the MouseListener class:
package events;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Events implements ActionListener, MouseListener, MouseMotionListener {
static Events events = new Events();
int x;
int y;
public void actionPerformed(ActionEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("X:" + x + " " + "Y:" + y);
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
}
Nevermind. I can just call the panel name for the panel x, and y locations. But thanks anyways.
x = P.g.getX();
y = P.g.getY()

can't draw on a JPanel after repaint method

I'm experimenting on a GUI that I programmed and I don't understand how I can fix my problem:
My GUI contains a jPanel that on receiving a mouseclick, paints a point with filloval command.
private void myPnlMousePressed(java.awt.event.MouseEvent evt) {
changed = true;
p.x = evt.getX();
p.y = evt.getY();
drewPoints(p.x, p.y);
}
private void drewPoints (int x, int y) {
if (gf == null) {
gf = (Graphics)myPnl.getGraphics();
}
myPointsList.add(new Point(x, y));
gf.fillOval(x, y, 5, 5);
xVal.setText("X = " + x);
yVal.setText("Y = " + y);
}
everything works fine but when I want to open an XML file that I created to save all the points it doesn't work.
The problem is that when I use the repaint method on the jPanel after choosing a file, all the points loads fine but the panel can't draw the points.
If I put the repaint method in the open button listener (before the choosing file) it works, but then if the user cancels the open option so the panel stays blank and I don't want to draw the points again.
I think it happens because the repaint process is not finished.
All the points added to a private List.
private void OpenFile() {
try {
File thisFile;
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
if (option == JFileChooser.APPROVE_OPTION){
thisFileName = of.getSelectedFile().getPath();
thisFile = new File(thisFileName);
if (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, You didn't select XML file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
return;
}
myPnl.repaint();
myPointsList.clear();
....
....
....
for (int i = 0; i < pointsList.getLength(); i++) {
Element point = (Element) pointsList.item(i);
p.x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
p.y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(p.x, p.y);
}
....
how can I make it work??
Don't use gf = (Graphics)myPnl.getGraphics();, this is not how painting in Swing works. The getGraphics method can return null and is nothing more then a snap shot of the last paint cycle, any thing you paint to it will be erased on the next paint cycle (repaint).
Instead, override the JPanels paintComponent and put all you painting logic there. There is an expectation that when called, you are expected to fully re-paint the current state of the component.
See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing
You have to use the repaint() and override the paint() method:
class MyPanel extends JPanel implements MouseListener
{
private int x;
private int y;
public MyPanel() {
super();
addMouseListener(this);
}
#Override public void mouseEntered(MouseEvent e) { }
#Override public void mouseExited(MouseEvent e) { }
#Override public void mouseClicked(MouseEvent e) { }
#Override public void mousePressed(MouseEvent e) { }
#Override public void mouseReleased(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
#Override public void paint(Graphics g) {
super.paint(g);
g.fillOval(x, y, 10, 10);
}
}
If you want to draw all points, don't use x and y but a list of points:
class MyPanel extends JPanel implements MouseListener
{
private ArrayList<Point> points = new ArrayList<>();
public MyPanel() {
super();
addMouseListener(this);
}
#Override public void mouseEntered(MouseEvent e) { }
#Override public void mouseExited(MouseEvent e) { }
#Override public void mouseClicked(MouseEvent e) { }
#Override public void mousePressed(MouseEvent e) { }
#Override public void mouseReleased(MouseEvent e) {
points.add(new Point(e.getX(), e.getY()));
repaint();
}
#Override public void paint(Graphics g) {
super.paint(g);
for (Point p : points)
g.fillOval(p.getX(), p.getY(), 10, 10);
}
}
where:
class Point
{
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Then use it:
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
MyPanel myPanel = new MyPanel();
frame.add(myPanel);
frame.setVisible(true);
}

Moving a JFrame with custom title bar

How can I move a JFrame having a custom title bar?
I remove the default title bar and I did my own design. This is how it looks like:
I want to know how to drag a JFrame when the cursor is placed on the title bar only and not the whole frame. I've searched already and I have seen a lot of samples but I still don't get it. Do you guys have any simple code that I can understand?
I haven't started the code yet since I don't know how to start it. All I know is that, it is about mouseDragged or MouseMotionListener.
I implemented the following:
public class DragFrame extends JFrame {
int mpX, mpY;
public DragFrame() {
addMouseListener( new MouseAdapter() {
#Override
public void mousePressed( MouseEvent e ) {
mpX = e.getX();
mpY = e.getY();
}
} );
addMouseMotionListener( new MouseMotionAdapter() {
#Override
public void mouseDragged( MouseEvent e ) {
setLocation(
getLocation().x + e.getX() - mpX,
getLocation().y + e.getY() - mpY );
}
} );
}
}
Thanks to #peeskillet for giving the crucial link to Drag and Resize undecorated JFrame with the inspiration to save the mouse position on mousePressed(...).
Your guess that you'll need to overwrite the MoseMotionListener.mouseDragged method was correct. Then, you need to call JFrame.setLocation to move your JFrame, like this:
class FrameMoveListener extends MouseAdapter
{
private Point lastPos;
private Frame frame;
public FrameMoveListener (Frame f)
{
frame = f; // mustn't be null
}
public void mouseDragged (MouseEvent evt)
{
if (lastPos != null)
{
int x = lastPos.x - evt.getX();
int y = lastPos.y - evt.getY();
f.setLocation(f.getLocationOnScreen().x + x,
f.getLocationOnScreen().y + y);
}
lastPos = new Point(evt.getX(), evt.getY());
}
}
use this method is simple and perfec
final Component obj - your JFrame, JLabel, any Component
final boolean info - if you want display the position when release de left click
public static void Move(final Component obj,final boolean info) {
MouseInputAdapter d=new MouseInputAdapter() {int x,X,y,Y;
#Override public void mousePressed(MouseEvent e){if(SwingUtilities.isLeftMouseButton(e)){x=e.getXOnScreen();X=obj.getLocation().x;y=e.getYOnScreen();Y=obj.getLocation().y;}}
#Override public void mouseDragged(MouseEvent e){if(SwingUtilities.isLeftMouseButton(e)){obj.setLocation(X+(e.getXOnScreen()-x), Y+(e.getYOnScreen()-y));}}
#Override public void mouseReleased(MouseEvent e){if(info && SwingUtilities.isLeftMouseButton(e)){System.err.println(obj.toString().substring(0,obj.toString().indexOf("["))+" ("+obj.getLocation().x+","+obj.getLocation().y+")");}}};
obj.addMouseListener(d);obj.addMouseMotionListener(d);
}
this is the format code:
public static void Mover(final Component obj, final boolean info) {
MouseInputAdapter d = new MouseInputAdapter() {
int x, X, y, Y;
#Override public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
x = e.getXOnScreen();
X = obj.getLocation().x;
y = e.getYOnScreen();
Y = obj.getLocation().y;
}
}
#Override public void mouseDragged(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
obj.setLocation(X + (e.getXOnScreen() - x), Y + (e.getYOnScreen() - y));
}
}
#Override public void mouseReleased(MouseEvent e) {
if (info && SwingUtilities.isLeftMouseButton(e)) {
System.err.println(obj.toString().substring(0, obj.toString().indexOf("[")) + " (" + obj.getLocation().x + "," + obj.getLocation().y + ")");
}
}
};
obj.addMouseListener(d);
obj.addMouseMotionListener(d);
}

Using KeyEvents and Mouse events at the same time

I'm trying to create a simple Java applet that can detect both the location of the mouse within the applet and detect whether the shift key has been released or pressed. When I add a KeyListener, though, the program ignores the mouseMove event. How can I get the mouseMove event to work while also using KeyListener?
public class Test extends java.applet.Applet implements java.awt.event.KeyListener {
String message;
int moveX, moveY;
public Test() { this.addKeyListener(this); }
public void init() {
message = "";
moveX = moveY = 0;
}
public void paint(java.awt.Graphics g) {
new Test();
g.drawString(message,15,15);
g.drawString("(" + moveX + "," + moveY + ")",900,630);
}
#Override
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_SHIFT)
message = "Shift key pressed";
repaint();
}
#Override
public void keyReleased(java.awt.event.KeyEvent e) {
message = "Shift key released";
repaint();
}
#Override
public void keyTyped(java.awt.event.KeyEvent e) {}
public boolean mouseMove(java.awt.Event e, int x, int y) {
moveX = x;
moveY = y;
repaint();
return true;
}
}
If you want to check if someone was holding shift or another key while clicking, MouseEvent has a method called getModifiers()
I fixed the issue by replacing mouseMove(java.awt.Event e, int x, int y) with mouseMoved(java.awt.event.MouseEvent e), so now the coordinates change when the mouse's location changes and the message changes when the shift key is held down.

dragging object using MouseListener Java applet

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);

Categories

Resources