Make a JLabel in the position where mouse last was? - java

I have a code that has a JLabel which follows the mouse. The JLabel says "exit" whenever the user exits the window, and stays at the last position the user was in. The problem is, the "exit" is only visible at when exiting the window from the top. This is because the JLabel is under the mouse. I want to make it so that the label moves down so I can see it if it exits up and move up if it exits down. I understand how to move it, but can we move it based on conditions? It shows up in the window fine, I just need to position it on different sides of my mouse based on exit position.
Here is my code:
class giraffemousehandler extends MouseAdapter implements MouseListener, MouseMotionListener { //MouseAdapter makes it so that you don't have to have all 7 implemented mouse listener methods
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
status.setBounds(e.getX(), e.getY(), 50, 60); //Makes JLabel follow mouse
}
#Override
public void mouseEntered(MouseEvent e) {
status.setText("Entered");
}
#Override
public void mouseExited(MouseEvent e) {
status.setText("exited");
// status.setBounds(e.getX(), e.getY(), 5, 6);
}
}
}
Thank you so much for the time you are taking for reading this, I really appreciate the effort you are putting into helping a fellow programmer!

public class GiraffeMouseHandler extends MouseAdapter implements MouseMotionListener
{
public void mouseEntered( MouseEvent event )
{
status.setText( "Entered" );
}
public void mouseExited( MouseEvent event )
{
status.setText( "Exited" );
}
public void mouseMoved( MouseEvent event )
{
//dimension is a reference of dimension of the main frame
if( ( dimension.getHeight() - event.getY() ) < 65 )
status.setBounds( event.getX(), (int)dimension.getHeight() - 65 , 50, 60 );
else if( ( dimension.getWidth() - event.getX() ) < 50 )
status.setBounds( (int)dimension.getWidth() - 50, event.getY(), 50, 60 );
else
status.setBounds( event.getX(), event.getY(), 50, 60 );
}
}

Related

Jittering when trying to move undercorated JFrame

I have made a custome JFrame called mainWindow that is undecorated. I have added a JLabel named dragBar at the top of it and gave it desired dimensions (as shown below). When I click on the label I make the window move according to my mouse by using two listeners; one MouseListener and one MouseMotionListener.
The problem is that whenever I click on the label the window does move according to my mouse's location but it spazzes all over my screen until I stop moving the mouse or let go of the click button.
Is my method wrong? What is causing this issue?
Here is my code:
//what i use to make the dragBar
private JLabel dragBar = new JLabel();
private Point initialClick; //the initial point where I click on the label
//my mainWindow JFrame
private JFrame mainWindow = new JFrame();
private Dimension mainWindowSize = new Dimension(680,410);
//the code I use to set up my mainWindow JFrame
mainWindow.setUndecorated(true);
mainWindow.setShape(new RoundRectangle2D.Double(0, 0, 670, 400, 5, 5));
mainWindow.setSize(mainWindowSize);
mainWindow.setMinimumSize(mainWindowSize);
mainWindow.setResizable(false);
mainWindow.setLocation((screen_size.width/2)- mainWindow.getWidth()/2, (screen_size.height/2)- mainWindow.getHeight()/2);
mainWindow.getContentPane().setBackground(new Color(46, 48, 50, 255));
//the code I use to set up my dragBar label
topContainer.add(dragBar,3); //a Jlayeredpane that contains the dragBar label and is added to the mainWindow
dragBar.setSize(topContainer.getSize());
dragBar.setLocation(0,0);
dragBar.addMouseListener(new MouseListener() {
#Override public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
}
#Override public void mouseReleased(MouseEvent e) {}
#Override public void mouseEntered(MouseEvent e) {}
#Override public void mouseExited(MouseEvent e) {}
});
dragBar.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
int changeX = e.getX()-initialClick.x;
int changeY = e.getY()-initialClick.y;
mainWindow.setLocation(mainWindow.getX()+changeX, mainWindow.getY()+changeY);
}
#Override public void mouseMoved(MouseEvent e) {}
});
a Jlayeredpane that contains the dragBar label
Don't think I would use a JLayeredPane for this. Just add a component to the BorderLayout.PAGE_START of the frame.
The basic logic for dragging a component is something like:
public class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
However in your case you don't want to drag the label, but instead drag the window, you your logic needs to forward the events to the window.
Check out Moving Windows for a more complex implementation of the above code that also adds additional features that easily allow you to move a window.

java - get a button to change color when the mouse hovers over it

So i want to make a menu for a simple java game where the buttons changes colors when the mouse hovers over them. I am not using JButton but a picture of a button that uses mouselistener to detect the click. How do i make it so MouseEntered is called when you hover over a specific area where the button is?
public void mouseEntered(MouseEvent e) {
if(e.getX() < 950 && e.getX() > 350 && e.getY() < 300 && e.getY() > 200){
menuImage2 = true;
menuImage1 = false;
}
}
This is what i have so far
This is how I did it. It also plays a sound too. You just use flags. Notice, I used mouseMoved rather than mouseEntered.
Class MouseInput
#Override
public void mouseMoved(MouseEvent e) {
int x=e.getX();
int y=e.getY();
if (x>100&&x<200&&y>150&&y<200) {
if (mouseInStart==false) { <---- if this line is true, means mouse entered for first time.
Sound.playSound(soundEnum.BUTTONHOVER);
}
mouseInStart=true;
} else {
mouseInStart=false;
}
}
public boolean mouseInStart() { <--use this in your update method
return mouseInStart;
}
And in my other class (Class Menu)
public void render(Graphics2D g) {
....
....
gradient = new GradientPaint(100, 150, setStartColor(), 200, 200, Color.gray);
g.setPaint(gradient);
g.fill(startButton);
}
public Color setStartColor() {
if (mouseInStart) {
return Color.red;
} else {
return Color.white;
}
}
public void update() { <--- and this is to keep checking if your mouse is in start. This is part of the giant game loop.
mouseInStart=mouseInput.mouseInStart();
mouseInLoad=mouseInput.mouseInLoad();
mouseInQuit=mouseInput.mouseInQuit();
}

mouse listener on frame

Hi
i am trying to add a mouse listener to my frame to get the position of the mouse clicked and check if it is inside the circle, the problem is that it is not triggering
public class CircleDraw extends Frame implements MouseListener {
static int circles = 0;
private double color;
double mousex = 0;
double mousey = 0;
int score;
public void mouseClicked(MouseEvent evt)
{
mousex = evt.getX();
mousey = evt.getY();
}
public void mouseEntered (MouseEvent me) {}
public void mousePressed (MouseEvent me) {}
public void mouseReleased (MouseEvent me) {}
public void mouseExited (MouseEvent me) {}
public void paint(Graphics g) {
try {
this.addMouseListener(this);
while (circles < 20) {
color = 10*Math.random();
Shape circle = new Ellipse2D.Double(900*Math.random(),900*Math.random(), 50.0f, 50.0f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);
if(color >2)
ga.setPaint(Color.green);
else
ga.setPaint(Color.BLACK);
ga.fill(circle);
if(circle.contains(mousex, mousey) && color > 2)
score ++;
else
if(circle.contains(mousex, mousey) && color < 2)
score--;
Thread.sleep(1000);
System.out.println(circles);
System.out.println(mousex);
System.out.println(mousey);
circles ++;
ga.setPaint(Color.white);
ga.fill(circle);
}
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Frame frame = new CircleDraw();
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setSize(1000, 1000);
frame.setVisible(true);
}}
It is deadly to add your mouselistener in the paint() method, since this method is called very very often (with each repaint), and so many listeners are added (with each repaint).
You should add the listener to your content-panel and not to the JFrame itself. This will do it. You can do this in the constructor of your class:
public CircleDraw() {
this.getContentPane().addMouseListener(this);
}
This won't solve your problem completely I think, since you won't get your mouseclick while your paint-method is active. Your code-design (especially your while-loop) does not give any time to other events to fire. So the mouseclick-event will be handled after your 20 loops. You can check this by adding
public void mouseClicked(MouseEvent evt) {
mousex = evt.getX();
mousey = evt.getY();
System.out.println("X: "+mousex+"/ Y: "+mousey);
}
to your code. You have to run your GUI in a different thread (e.g. use SwingUtilities and a Runnable() therefor). I recommend you to get a good book on JAVA development. Or you can start with online-tutorials like this one.
IMHO you should not try to deal with awt, instead use SWING or SWT for GUI-design, since this is much more compfortable.
add the listener in the constructor, the paint is called repeatedly
Here are some of the problems I see with that source:
Adds the listener in paint()
Calls wait() within the paint() method.
Calls System.exit() within the paint() method (not strictly a problem, but very unusual).
Is poorly formatted and hard to understand
Calls deprecated methods.
Codes in AWT in the wrong millennium.

JButton breaks my Keylistener

JAVA USING NETBEANS
Hello stackoverflow, i have a problem i would like help with. In a nutshell, I have a mouselistener and a keylistener on a jpanel, everything works fine except when i press one of my jbuttons, then the keylistener goes AWOL. Can any1 explain the problem, is the panels focus now on the buttons instead of the keyboard, im at a lost.
Here is the code, if somethings are not reference, assume its are there the entire panel code was 500+ long so i cut quite a bit.
Thanks in advance for any help.
package tankgame;
public class TankPanel extends JPanel implements KeyListener,
MouseListener,MouseMotionListener
{
JButton back,shop, menu, health, speed, rapidfire, shootradius;
TankPanel()
{
setLayout( null );
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setFocusable(true);
shop= new JButton("SHOP");
shop.addMouseListener(this);
shop.setBounds(400,0, 80,15);
add(shop);
}
public void keyPressed(KeyEvent k)
{
char c = k.getKeyChar();
if(c=='u')
{
u++;
System.out.println(u+" = u");
}
if(c=='i')
{
i++;
System.out.println(i+" = i");
}
if( c == 'd' )
{
if(Ptank.pic==PlayerTankE)
{
if(Ptank.move==true)
{
Pbarrel.x+=Ptank.speed;
Ptank.x+=Ptank.speed;
}
}
else
{
if(Ptank.pic==PlayerTankN || Ptank.pic==PlayerTankS)
{
Ptank.x = Ptank.x - 5;
Ptank.y=Ptank.y+5;
}
Ptank.setPic(PlayerTankE);
Ptank.width=35;
Ptank.height = 23;
}
}
setFocusable(true);
repaint();
}
public void keyReleased(KeyEvent k)
{
}
public void keyTyped(KeyEvent k)
{
}
public void mouseClicked(MouseEvent e)
{
//Invoked when the mouse button has been clicked (pressed and released)
}
public void mouseEntered(MouseEvent e)
{//Invoked when the mouse enters a component.
}
public void mouseExited(MouseEvent e)
{ //Invoked when the mouse exits a component.
}
public void mousePressed(MouseEvent e)
{//Invoked when a mouse button has been pressed on a component.
if(e.getSource()==back)
{
System.out.println(456);
System.out.println(back.getLocation().x + " "+back.getLocation().y);
}
else if(e.getSource() == menu)
{
changebuttons("menu");
System.out.println(456);
System.out.println(menu.getLocation().x + " "+menu.getLocation().y);
}
else if(e.getSource() == shop)
{
changebuttons("shop");
System.out.println(456);
System.out.println(shop.getLocation().x + " "+shop.getLocation().y);
}
else if(e.getButton() == MouseEvent.BUTTON1)
{
destpoint= new Point();
destpoint.setLocation(mousex, mousey);
origin = new Point();
}
for(int i = 0; i< Ptank.rapidfire; i++)
{
if (origin.distance(destpoint) <= 100 && origin.distance(destpoint) >= 50)
{
Bullet add = new Bullet(this,destpoint);
add.getOrigin(origin);
add.setPic(PlayerBullet);
add.width=4;
add.height=4;
bulletList.add(add);
}
}
}
}
public void mouseReleased(MouseEvent e)
{//Invoked when a mouse button has been released on a component.
}
public void mouseDragged(MouseEvent e)
{//Invoked when a mouse button is pressed on a component and then dragged.
}
public void mouseMoved(MouseEvent e)
{
//Invoked when the mouse cursor has been moved onto a component but no buttons
Cursor cursor = Cursor.getDefaultCursor();
//you have a List<Polygon>, so you can use this enhanced for loop
cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
setCursor(cursor);
mousex=e.getX();
mousey=e.getY();
}
public void changebuttons(String x)
{
if(x.equals("shop"))
{
menu.setBounds(720, 0, 80, 15);
health.setBounds(0, 0, 125, 15);
speed.setBounds(150, 0, 125, 15);
shootradius.setBounds(300, 0, 200, 15);
rapidfire.setBounds(500, 0, 150, 15);
shop.setBounds(1000, 0, 150, 15);
}
}
KeyEvents are only generated on a component that has focus. When you click on the button is now has focus to key events won't be generated on the panel. You need to add:
panel.requestFocusInWindow()
in your ActionListener to give focus back to the panel.
However the better solution is to use Key Bindings as you can add bindings to a KeyStroke even when the component doesn't have focus.
Don't use a KeyListener which requires the component be focused to work. Instead consider using Key Bindings. You can find out how to use these guys at the Swing tutorial: How To Use Key Bindings. If you need more specific help, you will want to post a much smaller bit of code than you show above, code that is self-contained and will actually compile and run for us, an SSCCE.

getting JSlider bar to move on mouse click event

I have a JSlider which shows bet sizes (for a poker game) I am trying to achieve the effect that when a mouse click occurs the slider jumps forward by a bet amount (i.e. a big blind amount) rather than just incrementing by one. If the mouse click happens to the left of the bar i want it to decrement by a fixed amount else increment. I looked into attaching a mouse listener, but do not know how I can use the event to find out on what side of the bar the mouse was clicked.
Any ideas?
You just need to change your perspective on the problem.
Don't view the clicks as being to the 'left' or 'right' (below or above) the current bet.
Rather, you simply store the old tick, and look at what the new tick is. The difference will tell you if the user has tried to increase (positive delta) or decrease (negative delta).
Then you can increment by your desired 'fixed bet' amount.
I think you need to write a custom UI for this. This should get you started:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
public class SliderScroll extends JFrame
{
public SliderScroll()
{
final JSlider slider = new JSlider(0, 50, 20);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setExtent(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
getContentPane().add( slider );
slider.setUI( new MySliderUI() );
}
class MySliderUI extends MetalSliderUI
{
public void scrollByUnit(int direction)
{
synchronized(slider)
{
int oldValue = slider.getValue();
int delta = (direction > 0) ? 10 : -5;
slider.setValue(oldValue + delta);
}
}
}
public static void main(String[] args)
{
JFrame frame = new SliderScroll();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
}
This is how i accomplish the MouseClickEvent
MoveSlider = new JSlider(JSlider.HORIZONTAL, 0, 0, 0);
MoveSlider.addMouseListener(new MouseListener()
{
public void mousePressed(MouseEvent event) {
//Mouse Pressed Functionality add here
}
#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 mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
});

Categories

Resources