在屏幕上获得鼠标滚轮的大小

问题描述:

您好,我正在用Java中的mousewheel事件进行练习,因此当鼠标滚轮移动时,我制作了一个长大的虾仁。现在我还想在鼠标指针旁边的屏幕上显示“MousWheel”的大小。任何人都可以告诉我一个如何做到这一点的例子吗?在屏幕上获得鼠标滚轮的大小

这就是我现在得到的。

public class MouseWheelPanel extends JPanel implements MouseWheelListener { 

private int grootte = 50; 

public MouseWheelPanel() { 
    this.addMouseWheelListener(this); 
} 

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.setColor(Color.YELLOW); 
    g.fillOval(10, 10, grootte, grootte); 
} 


public void mouseWheelMoved(MouseWheelEvent e) { 
    // TODO Auto-generated method stub 
    String 
    grootte += e.getWheelRotation(); 
    repaint(); 
} 

} 
+1

'g.drawString(arguments)'只需在Graphics api中查找该方法即可。 – thatidiotguy

假设你也对定位文本感兴趣。查找FontMetrics。这会将大小字符串居中在圆圈中。

public void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 
    g.setColor(Color.YELLOW); 
    g.fillOval(10, 10, grootte, grootte); 

    String str = ""+grootte; 
    FontMetrics fm = g.getFontMetrics(); 
    Rectangle2D strBounds = fm.getStringBounds(str, g); 

    g.setColor(Color.BLACK); 
    g.drawString(str, 10 + grootte/2 - (int)strBounds.getWidth()/2, 10 + grootte/2 + (int)strBounds.getHeight()/2); 
}