检测鼠标悬停在Graphics2D字符串上

时间:2014-01-12 14:04:48

标签: java string swing user-interface awt

当鼠标悬停在图形2D字符串上时,有没有办法设置颜色?

到目前为止,这是我的相关代码:

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;

    g2d.setColor(Color.white);

    g2d.setFont(new Font("Arial", Font.BOLD, 16));
    g2d.drawString("EXIT", 650, 50);
}

MouseListener ml=new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        //hover
        //should do something here...        
        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    };

1 个答案:

答案 0 :(得分:2)

除MouseListener外,请使用MouseMotionListener

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TextHoverComponent extends JPanel {
    private static final long serialVersionUID = 1;

    private static final Color DEFAULT_TEXT_COLOR = Color.WHITE;

    private static final Color HOVER_TEXT_COLOR = Color.RED;

    private Font font = new Font("Arial", Font.BOLD, 16);

    private String text = "EXIT";

    private Color textColor = DEFAULT_TEXT_COLOR;

    private Point textLocation = new Point(650, 50);

    public TextHoverComponent() {
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent event) {
                checkForHover(event);
            }

            @Override
            public void mouseExited(MouseEvent event) {
                checkForHover(event);
            }
        });

        addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseMoved(MouseEvent event) {
                checkForHover(event);
            }

            @Override
            public void mouseDragged(MouseEvent event) {
                checkForHover(event);
            }
        });
    }

    void checkForHover(MouseEvent event) {
        FontMetrics metrics = getFontMetrics(font);

        Graphics g = getGraphics();
        Rectangle textBounds = metrics.getStringBounds(text, g).getBounds();
        g.dispose();

        textBounds.translate(textLocation.x, textLocation.y);

        if (textBounds.contains(event.getPoint())) {
            textColor = HOVER_TEXT_COLOR;
        } else {
            textColor = DEFAULT_TEXT_COLOR;
        }
        repaint(textBounds);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setFont(font);
        g.setColor(textColor);
        g.drawString(text, textLocation.x, textLocation.y);
    }
}