好吧,我放棄了。我幾年來一直是C++程序員,但我嘗試學習Java,因爲它是一種流行的語言。在我學習的過程中,我學到了很多東西,但最終我開始玩耍並嘗試使用輸入系統,這樣當我點擊這個紅色菱形多邊形時,它變成了綠色,但經過幾天令人沮喪的日子...... nada。我仍然只有一顆紅色的鑽石。這可能是一些非常小,但我無法找到它Java輸入錯誤
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Vici extends Applet
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Space castle;
public Vici()
{
castle = new Space();
castle.addMouseListener(new SpaceInput());
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
int width = getSize().width;
int height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height);
castle.paint(g2d);
}
class SpaceInput implements MouseListener
{
public void mouseEntered(MouseEvent m) { }
public void mouseExited(MouseEvent m) { }
public void mouseReleased(MouseEvent m)
{
switch(m.getButton())
{
case MouseEvent.BUTTON1:
castle.setColor(Color.GREEN);
castle.repaint();
repaint();
}
}
public void mouseClicked(MouseEvent m)
{
switch(m.getButton())
{
case MouseEvent.BUTTON1:
castle.setColor(Color.GREEN);
castle.repaint();
repaint();
}
}
public void mousePressed(MouseEvent m)
{
switch(m.getButton())
{
case MouseEvent.BUTTON1:
castle.setColor(Color.GREEN);
castle.repaint();
repaint();
}
}
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class Space extends Canvas
{
private Polygon poly;
private Color c;
private int[] polyX = { 0, 24, 0, -24 };
private int[] polyY = { 24, 0, -24, 0 };
public void init()
{
poly = new Polygon(polyX, polyY, polyX.length);
c = Color.red;
}
Space()
{
init();
}
void setColor(Color c)
{
this.c = c;
}
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
AffineTransform identity = new AffineTransform();
g2d.setTransform(identity);
g2d.translate(100, 100);
g2d.setColor(c);
g2d.fill(poly);
}
public void update(Graphics g)
{
paint(g);
}
}
什麼是錯誤?我們沒有通過你的代碼並發現錯誤! –
@Hemant Metalia - 問題在於鼠標偵聽器永遠不會被調用,所以顏色永遠不會被改變。這是一個合法的問題... – paulsm4
Applets不是學習Java GUI編程的好方法。製作應用。第一。不要使用AWT,請使用Swing。大多數曾經知道如何使用AWT的人都忘記了細節。 –