private class Board extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w=getWidth();
int h=getHeight();
Graphics2D g2d = (Graphics2D) g;
以下代码绘制网格:
g2d.setPaint(Color.WHITE);
g2d.fill(new Rectangle2D.Double(0, 0, w, h));
g2d.setPaint(Color.BLACK);
g2d.setStroke(new BasicStroke(4));
g2d.draw(new Line2D.Double(0, h/3, w, h/3));
g2d.draw(new Line2D.Double(0, h*2/3, w, h*2/3));
g2d.draw(new Line2D.Double(w/3, 0, w/3, h));
g2d.draw(new Line2D.Double(w*2/3, 0, w*2/3, h));
以下代码通过访问数组List中的元素来绘制圆和x:
for(Shape shape : shapes){
g2d.setPaint(Color.BLUE);
g2d.draw(shape);
}
}
}
public void addMouseListener(MouseListener ml){
// HOW CAN I ADD A MOUSE LISTENER HERE?
}
答案 0 :(得分:1)
您可以创建一个implements
MouseListener
interface
的课程,如下所示:
public class CustomMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
statusLabel.setText("Mouse Clicked: ("+e.getX()+", "+e.getY() +")");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
您希望根据方法所代表的操作定义每个方法(这些是自解释的)。 MouseEvent
对象将包含您需要的与鼠标相关的所有信息(例如鼠标的x和y位置)。
现在,您要将此新MouseListener
添加到JPanel
(在本例中为Board
类):
//JPanel panel = new JPanel();
Board panel = new Board();
panel.addMouseListener(new CustomMouseListener());
答案 1 :(得分:1)
创建实现MouseListener的类,并通过addMouseListener方法传递它??
http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
答案 2 :(得分:0)
您需要使该类实现MouseListener。 你需要添加unmplements方法。 在这里你去:) 你没有什么新方法:
public void mouseClicked(MouseEvent e) // method calls when mouse clicked
public void mousePressed(MouseEvent e) // method calls when mouse pressed
public void mouseReleased(MouseEvent e) // method calls when mouse relesed
public void mouseEntered(MouseEvent e) // method calls when the mouse curser getting into the component's geometry
public void mouseExited(MouseEvent e) // method calls when mouse curser getting out of the component's geometry
希望它能帮到你:)。