Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java drawString()方法上的MouseListener_Java_Graphics2d_Mouselistener - Fatal编程技术网

Java drawString()方法上的MouseListener

Java drawString()方法上的MouseListener,java,graphics2d,mouselistener,Java,Graphics2d,Mouselistener,如何检测我使用drawString()方法绘制的文本(“Resume”、“Restart”、“Quit”)是否正在被单击 到目前为止,我的代码是: public class Pause { public Pause() { } public void draw(Graphics2D g) { g.setFont(new Font("Arial", Font.BOLD, 14)); int intValue = Integer.pa

如何检测我使用
drawString()
方法绘制的文本(“Resume”“Restart”“Quit”)是否正在被单击

到目前为止,我的代码是:

public class Pause {

    public Pause() {

    }


    public void draw(Graphics2D g) {

        g.setFont(new Font("Arial", Font.BOLD, 14));
        int intValue = Integer.parseInt( "ff5030",16);      
        g.setColor(new Color(intValue));

        g.drawString("Resume", 200, 156);
        g.drawString("Restart", 200, 172);
        g.drawString("Quit", 200, 188);    
    }
}
我希望你能帮助我。谢谢

@也许我试着把它写得尽可能简单。以下是SSCCE:

GameFrame.java

public class GameFrame extends JFrame implements Runnable { 
    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    // dimensions
    public static final int WIDTH = 448;
    public static final int HEIGHT = 288;
    public static final double SCALE = 2.5; 

    // game thread
    private Thread thread;
    private boolean running;

    private int FPS = 60;
    private long targetTime = 1000 / FPS;

    // image
    private BufferedImage image;
    private Graphics2D g;

    //displays
    private Pause pauseDisplay;


    public GameFrame() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setPreferredSize(new Dimension((int)(WIDTH * SCALE), (int)(HEIGHT * SCALE)));
        this.setBounds(100, 100, (int)(WIDTH * SCALE), (int)(HEIGHT * SCALE));
        this.setLocationRelativeTo(null);
        this.setFocusable(true);
        this.requestFocus();
        this.setVisible(true);
    }

    public void addNotify() {
        super.addNotify();
        if(thread == null) {
            thread = new Thread(this);
            thread.start();
        }
    }

    private void init() {       
        image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        g = (Graphics2D) image.getGraphics();

        running = true;     
    }

    public void run() {     
        init();

        long start;
        long elapsed;
        long wait;

        // game loop
        while(running) {
            start = System.nanoTime();          
            elapsed = System.nanoTime() - start;            
            wait = targetTime - elapsed / 1000000;
            if(wait < 0) wait = 5;

            try {
                Thread.sleep(wait);
            }
            catch(Exception e) {
                e.printStackTrace();
            }

            pauseDisplay = new Pause(this);
            drawToScreen();
            draw();         
        }       
    }


    private void draw() {               
        pauseDisplay.draw(g);
    }


    private void drawToScreen() {
        Graphics g2 = getGraphics();
        g2.drawImage(image, 0, 0, (int)(WIDTH * SCALE), (int)(HEIGHT * SCALE), null);
        g2.dispose();
    }       


    public static void main(String[] args) {
        GameFrame game = new GameFrame();
    }    
}
public class Pause implements MouseListener{

    private Rectangle2D resumeRect;
    private Rectangle2D restartRect;

    public Pause(GameFrame GameFrame) {
        GameFrame.addMouseListener(this);
    }


    public void draw(Graphics2D g) {        
        g.setFont(new Font("Arial", Font.BOLD, 14));
        int intValue = Integer.parseInt( "ff5030",16);      
        g.setColor(new Color(intValue));

        g.drawString("Resume", 200, 156);
        resumeRect= g.getFontMetrics().getStringBounds("Resume", g);

        g.drawString("Restart", 200, 172);
        restartRect = g.getFontMetrics().getStringBounds("Restart", g);

        g.drawString("Quit", 200, 188);
    }


    public void mouseClicked(MouseEvent e) {
        if (resumeRect.contains(e.getPoint())) {
            System.out.println("clicked");
        }

        System.out.println(resumeRect);
        System.out.println(restartRect);
        System.out.println(e.getPoint());
    }


    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

}

你必须记住你画绳子的位置。每个字符串可以有一个
矩形2D

字符串的矩形可以按如下方式计算:

Rectangle2D r = g.getFontMetrics().getStringBounds(str, g);
(需要根据绘制字符串的位置调整rect位置。)

然后,您将注册一个鼠标侦听器,根据这些矩形检查单击坐标:

if (resumeRect.contains(mouseEvent.getPoint())) {
    ...
}
话虽如此,我还是建议您重新考虑GUI代码,看看是否不能为此使用
JLabel
JButton


关于您的编辑:

您的NullPointerException是因为您可以在渲染图像之前(即,在初始化矩形之前)单击帧

除此之外,您还需要进行两次编辑:

  • 您需要考虑
    比例

    if (resumeRect.contains(e.getPoint().getX() / GameFrame.SCALE,
                            e.getPoint().getY() / GameFrame.SCALE)) {
    

  • 您需要补偿drawString在基线上绘制字符串的事实,因此矩形应从基线向上提升到文本的左上角:

    g.drawString("Resume", 200, 156);
    resumeRect= g.getFontMetrics().getStringBounds("Resume", g);
    
    // Add this:
    resumeRect.setRect(200,
                       156 - g.getFontMetrics().getAscent(),
                       resumeRect.getWidth(),
                       resumeRect.getHeight());
    
  • 不要使用drawString(),而是将文本放在JLabel中。然后,您可以将侦听器附加到标签上,这要容易得多


    JLabel还有一个优点,即您可以使用html进行格式化,并且它允许layoutmanager定位文本。

    您的意思是捕获文本恢复、重新启动、退出的单击事件吗?@Deepika Rajani索引如果NullPointerException引用rect.contains行,则rect或mouseEvent为null。请仔细检查。它说contains是null contains是一个方法。方法不能为null。请澄清。我在问题中添加了新代码。可能是我把矩形弄错了吗?顺便说一句,真的很漂亮。我从来没有见过有人在被要求回来后带着这么好的SSCCE回来。通常人们都太懒了。我希望您认为在这种情况下是值得的:-)我知道使用JLabel要容易得多。但问题是,我需要在游戏中画它,这是与图形2D。