我想實現一個繪製兩隻眼睛的面板,它根據鼠標光標是否在上面而向上看,向中心或向下看,內部或眼睛下方。我第一次使用這個代碼,以使眼睛:一個Swing初學者,想做一個小動眼睛的Java GUI練習但是卡住了
public class EyesPanel extends JPanel implements ActionListener {
// images
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawOval(130, 100, 120, 120);
g.drawOval(250, 100, 120, 120);
g.fillOval(175, y, 30, 30); // x: 175 y: 145
g.fillOval(295, y, 30, 30); // x: 295 y: 145
}
,然後及時添加事件偵聽器,使這個類的作品,但這裏是我堅持的部分。我知道如何使圖形移動(ActionListener),我知道如何實現MouseInputListener(擴展MouseInputListener)。但是,將這兩者結合起來讓我感到沮喪。任何人都可以告訴我怎麼做,給我一個示例代碼可以非常有幫助。
下面是我的代碼,到目前爲止,沒有一個運作和完整代碼:
public class EyesPanel extends JPanel implements ActionListener {
private JPanel panel;
private int y;
private int dy;
private Timer t;
private Mouse move;
public EyesPanel() {
dy = 5;
y = 145;
// mouse detector
this.addMouseListener(new Mouse());
this.addMouseMotionListener(new Mouse());
// Timer
t = new Timer(100, this);
}
// images
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawOval(130, 100, 120, 120);
g.drawOval(250, 100, 120, 120);
g.fillOval(175, y, 30, 30); // x: 175 y: 145
g.fillOval(295, y, 30, 30); // x: 295 y: 145
}
public void actionPerformed(ActionEvent event) {
moveDown(); //➜ not complete, don't know how to implement
}
// move up
private void moveUp() {
if (move.move() == 1) {
t.start();
y = y + dy;
repaint();
} else {
t.stop();
}
}
// move down
private void moveDown() {
if (move.move() == -1) {
t.start();
y = y - dy;
repaint();
} else {
t.stop();
}
}
// ➜ not complete, trying, but no clue
}
我的鼠標事件類:
public class Mouse extends MouseInputAdapter {
private int y;
public void mouseEntered(MouseEvent event) {
JPanel pane = (JPanel) event.getSource();
y = pane.getHeight(); // ➜ not complete
}
}
看看這裏:https://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html – slambeth
你不需要任何的ActionListener或定時器。你需要的是一個MouseMotionListener。在其mouseMoved()方法中,存儲鼠標的新座標,然後調用repaint()。在paintComponent()中,使用鼠標的座標來計算眼睛應該看的位置。 –