我創建了這個java程序,我想要一個輸出,如果int x和int y大於100,它會繪製一個矩形。但事實並非如此。我怎樣才能使它工作?我需要添加另一行代碼嗎? 這裏是我的代碼:在java中需要幫助定位
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class GameSetup extends JPanel implements MouseMotionListener{
public static JFrame njf = new JFrame("Test");
public static int x, y;
public static void main(String[] args){
GameSetup gs = new GameSetup();
njf.add(gs);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.GREEN);
g.fillRect(150, 75, 200, 100);
g.setColor(Color.ORANGE);
g.drawString("Play", 239, 123);
njf.addMouseListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
});
if(x > 100 && y > 100){
g.drawRect(10, 10, 100, 100);
}
}
public GameSetup(){
njf.setSize(500,500);
njf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
njf.setResizable(false);
njf.setLocationRelativeTo(null);
njf.setVisible(true);
}
@Override
public void mouseDragged(MouseEvent arg0) {
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
是paint組件被調用後,位置超過100?如果不只是將if語句移動到mouseMoved方法的內部 –
'public void paintComponent(Graphics g){ .. njf.addMouseListener(new MouseAdapter(){'不,不,不!不要使用paint方法(可能會多次調用)來添加監聽器到組件中,在構造函數中這樣做 –