gpt4 book ai didi

java - 如何让我的 MouseListener 方法在 Java 中工作?

转载 作者:行者123 更新时间:2023-12-02 09:12:05 25 4
gpt4 key购买 nike

我对java很陌生,我正在制作一个简单的像素艺术制作器。我复制了一个 for 循环来画圆圈。我用的是鼠标点击的方法。我这样做是为了当我单击时,它会打印“左”或“右”。

这是网格系统:http://www.java2s.com/Tutorials/Java/Graphics/Shape/Draw_a_grid_by_drawing_lines_in_Java.htm

这是我使用的 MouseEvent 系统:

https://github.com/DevonCrawford/A-Pathfinding-Visualization/blob/master/src/Frame.java

唯一的问题是它不打印“左”和“右”。这是我的代码:

import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

class Main extends JComponent implements MouseListener {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 600, 584);
window.getContentPane().add(new Main());
// window.setResizable(false);
window.setVisible(true);

}

public void paint(Graphics g) {
int rows = 20;

int cols = 20;
int width = getSize().width;
int height = getSize().height;

// draw the rows
int rowHt = height / (rows);
for (int i = 0; i < rows; i++)
g.drawLine(0, i * rowHt, width, i * rowHt);

// draw the columns
int rowWid = width / (cols);
for (int i = 0; i < cols; i++)
g.drawLine(i * rowWid, 0, i * rowWid, height);

}

public void MapCalculations(MouseEvent e) {
// If left mouse button is clicked
if (SwingUtilities.isLeftMouseButton(e)) {
System.out.println("Left");

}
// If right mouse button is clicked
else if (SwingUtilities.isRightMouseButton(e)) {
System.out.println("Right");
}
}

@Override
public void mouseClicked(MouseEvent e) {
MapCalculations(e);
}

@Override
public void mousePressed(MouseEvent e) {}

@Override
public void mouseReleased(MouseEvent e) {}

@Override
public void mouseEntered(MouseEvent e) {}

@Override
public void mouseExited(MouseEvent e) {}

public void mouseDragged(MouseEvent e) {
MapCalculations(e);
}
}

最佳答案

鼠标监听器方法永远不会被调用,因为框架不知道何时调用它们。

尝试将鼠标监听器添加到 main 方法中的 window 对象,如下所示:

public static void main(String[] args) {
JFrame window = new JFrame();
Main myMain = new Main();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 600, 584);
window.getContentPane().add(myMain);
// window.setResizable(false);
window.setVisible(true);
window.addMouseListener(myMain);
}

关于java - 如何让我的 MouseListener 方法在 Java 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59324618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com