2017-08-11 77 views
-1

有人可以幫我解決這個問題,我一直在學習以Java編程的一本書,複製其中一個程序,並且它的工作原理是mouseDragged不起作用。無法點擊'Hello Java!'文本並將其拖動到屏幕上。我已經包含了這個程序,但是我不知道我出了什麼問題或者我錯過了什麼。 我看過這篇文章:「MouseDragged & MouseMoved不能在Java Applet中工作」,但這些方法都在我的程序中。MouseDragged不能正常工作

//file: HelloJava3.java 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 


public class HelloJava3 { 

public static void main(String[] args) { 
    JFrame frame = new JFrame("HelloJava3"); 
    frame.add(new HelloComponent3("Hello, Java!")); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(300, 300); 
    frame.setVisible(true); 

} 

} 

class HelloComponent3 extends JComponent 
implements ActionListener, MouseMotionListener 
{ 
    String theMessage; 
    int messageX = 125, messageY = 95; //Coordinates of the message 

    JButton theButton; 

    int colorIndex; //Current index into someColors 
    static Color[] someColors = { 
      Color.black, Color.red,    Color.green, Color.blue, Color.magenta 
    }; 

public HelloComponent3(String message) { 
    theMessage = message; 
    theButton = new JButton("Change Color"); 
    setLayout(new FlowLayout()); 
    add(theButton); 
    theButton.addActionListener(this); 
    addMouseMotionListener(this); 
} 

public void paintComponent(Graphics g) { 
    g.drawString(theMessage, messageX, messageY); 
} 

public void mouseDgragged(MouseEvent e) { 
    messageX = e.getX(); 
    messageY = e.getY(); 
    repaint(); 
} 

public void mouseMoved(MouseEvent e) {} 

public void actionPerformed(ActionEvent e) { 
    // Did somebody push out button? 
    if (e.getSource() == theButton) 
     changeColor(); 
} 

synchronized private void changeColor() { 
    //Change the index to the next colour, awkwardly. 
    if (++colorIndex == someColors.length) 
     colorIndex = 0; 
    setForeground(currentColor()); // Use the new colour. 
    repaint(); 
} 

synchronized private Color currentColor() { 
    return someColors[colorIndex]; 
} 

@Override 
public void mouseDragged(MouseEvent arg0) { 
    // TODO Auto-generated method stub 

} 
} 
+0

而不是複製代碼,學習概念,這將進一步得到你。在發佈問題之前,還需要搜索並學習相關教程,因爲通常會發現許多教程(包括如何在Swing中使用鼠標監聽器和鼠標移動監聽器)。 –

+0

通過複製代碼以及您在此過程中犯的所有錯誤,您可以從解決這些問題中學到很多東西。教程是偉大的,但能夠調試更大,是的,我沒有發佈之前尋找答案。 – Kalmiany

回答

1

mouseDragged方法正在被覆蓋並且什麼都不做。你應該刪除這個或定義它。我將刪除重寫的一個,並將@Override註釋添加到另一個mouseDragged方法中,假定它是您正在擴展的接口所需的。

刪除此:

@Override 
public void mouseDragged(MouseEvent arg0) { 
    // TODO Auto-generated method stub 

} 

或許應該出現這樣的代碼:

@Override 
public void mouseDragged(MouseEvent e) { 
    messageX = e.getX(); 
    messageY = e.getY(); 
    repaint(); 
} 
+0

謝謝你,我從你的解釋和你的和平代碼中學到了很多東西。現在起作用了。 – Kalmiany

+0

很高興能夠提供幫助,請點擊解決方案旁邊的複選標記,接受此問題爲正確答案。學習代碼是有益的,保持良好的工作。 – dspano