Reputation: 27
I have a jframe with some JComponents, with some mouseListener. My aim is to show a little jframe with a specified text, when the mouse enter on a jlabel, and to show off it when the mouse is exited. Jframe is supposed to be shown near the mouse. Anyway that does not happen, and the programm behaves in a very strange way. Why? the bug That's my code
package finestrina;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class finestra implements MouseListener{
private JFrame finestra = new JFrame();
private JFrame pagina = new JFrame();
private JButton submit1 = new JButton("press");
private JTextField text = new JTextField();
finestra(){
pagina.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pagina.setSize(500, 500);
JPanel cont = new JPanel();
cont.setLayout(new GridLayout(3,4));
JLabel label = new JLabel();
label.setText("ON MOUSEROVER THIS");
cont.add(label);
label.addMouseListener(this);
submit1.addMouseListener(this);
text.addMouseListener(this);
cont.add(submit1);
cont.add(text);
pagina.add(cont);
pagina.setVisible(true);
finestra.setUndecorated(true);
}
@Override
public void mouseClicked(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent event) {
if(event.getSource() instanceof JLabel){
JLabel event_casted = (JLabel)event.getSource();
if(event_casted.getText().equals("ON MOUSEROVER THIS")){
Point punto = event.getLocationOnScreen();
punto.setLocation(punto.getX()+20, punto.getY()+20);
JLabel littlelabel = new JLabel();
littlelabel.setText("your mouse is on the jlabel");
finestra.add(littlelabel);
finestra.setLocation(punto);
finestra.setSize(100,100);
finestra.setVisible(true);
}
}
}
@Override
public void mouseExited(MouseEvent event) {
if(event.getSource() instanceof JLabel){
JLabel event_casted = (JLabel)event.getSource();
if(event_casted.getText().equals("ON MOUSEROVER THIS")){
finestra.setVisible(false);
}
}
}
@Override
public void mousePressed(MouseEvent event) {
}
@Override
public void mouseReleased(MouseEvent arg0) {}
public static void main(String[] args0){
new finestra();
};
}
Upvotes: 0
Views: 268
Reputation: 347194
There are a number of (possible) issues
GridLayout
will cause the component to occupy most of the space of the container, which might cause the window to "appear" to popup earlier then you expectfinestra.add(event_casted);
is causing the label to be removed from it's current parent container (the main window), as a component can only belong to a single containerIt would, generally be better to use the tooltip support provided by the API. Maybe have a look at How to Use Tool Tips, remember, they can also support HTML.
If that's not functionality what you want, then maybe a JPopupMenu
might be better
Upvotes: 1