• 0

[Java] Mouse Over


Question

I've been posting quite a few of these. Don't worry, it's all over tomorrow. You guys have been of great help.

Is there anyway I can trigger something when a mouse moves over one of the components in a JFrame.

For example, I have a checkbox (JCheckBox). I want it so that when the user hover's the mouse over the checkbox, a JLabel's text is changed. I know there is a similar thing for a mouse click, but I'm sure how to go about doing one for mouse over.

Thank you.

-0

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

Going along with your last post:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener,MouseListener {
  JButton[] cb = new JButton[3];
  public Test() {
    init();
  }
  public void init() {
    this.setSize(640,480);
    this.setLayout(null);
    String[] array = { "Yes", "No", "Maybe" };
    for(int i=0;i<3;i++)
    {
      cb[i] = new JButton(array[i]);
      cb[i].setBounds(i*100,0,80,30);
      cb[i].addActionListener(this);
      cb[i].addMouseListener(this);
      this.add(cb[i]);
    }
    this.setVisible(true);
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == cb[0]) {
      System.out.println("Yes");
    }
    else if (e.getSource() == cb[1]) {
      System.out.println("No");
    }
    else {
      System.out.println("Maybe");
    }
  }
  //Called when mouse goes over a component
  public void mouseEntered(MouseEvent e) {
    if (e.getSource() == cb[0]) {
      System.out.println("Over Yes");
    }
    else if (e.getSource() == cb[1]) {
      System.out.println("Over No");
    }
    else {
      System.out.println("Over Maybe");
    }
  }
  //Called when mouse released after clicking
  public void mouseReleased(MouseEvent e) { }
  //Someone clicked (pressed and released) their mouse
  public void mouseClicked(MouseEvent e) { }
  //Mouse no longer over component
  public void mouseExited(MouseEvent e) { }
  //Mouse is pressed down
  public void mousePressed(MouseEvent e) { }
}

For more info: http://java.sun.com/j2se/1.5.0/docs/api/ja...seListener.html

Link to comment
Share on other sites

  • 0
Any way I can get the text of the button and use it in the of statement? I.e. if (...button's text = "blah"...) do this.

-0

Sure, as long as you know it's a JButton using that actionListener:

if (((JButton)e.getSource()).getText().equals("blah")) {

//etc

}

Or you can even make a new class that handles the actionListener for each button. e.g. class YesActionListener, NoActionListener, etc.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.