每当我在单击的相同位置单击框架上的鼠标时,我都会尝试在框架上绘制一个点。我编写/复制的代码调用绘图函数,但没有绘制该点,我无法找出问题所在。这是代码:
import static com.sun.java.accessibility.util.AWTEventMonitor.addMouseListener;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class MyCanvas
{
JLabel view;
BufferedImage surface;
public MyCanvas()
{
surface = new BufferedImage(600,400,BufferedImage.TYPE_INT_RGB);
view = new JLabel(new ImageIcon(surface));
Graphics g = surface.getGraphics();
g.setColor(Color.ORANGE);
g.fillRect(0,0,600,400);
//g.setColor(Color.BLACK);
//g.drawLine(10, 20, 350, 380);
g.dispose();
/*
// RANDOM POINTS WORKING
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int x = random.nextInt(600);
int y = random.nextInt(400);
addNewElement(x,y);
}
};
Timer timer = new Timer(200, listener);
timer.start();
*/
}
public void addNewElement(int x,int y) {
Graphics g = surface.getGraphics();
drawNode(x,y,g);
g.dispose();
view.repaint();
}
public static void main(String[] args)
{
MyCanvas canvas = new MyCanvas();
JFrame frame = new JFrame();
int vertexes = 0;
// Change this next part later to be dynamic.
vertexes = 10;
int canvasSize = vertexes * vertexes;
frame.setSize(canvasSize, canvasSize);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(canvas.view);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//Restituisco le coordinate del click(x,y)
System.out.println(e.getPoint());
//NOT WORKING
MyCanvas a = new MyCanvas();
a.addNewElement(e.getPoint().x,e.getPoint().y);
}
});
}
public void drawNode(int x, int y, Graphics g)
{
g.setColor(Color.white);
g.fillOval(x, y, 8, 8);
g.drawOval(x, y, 8, 8);
}
}
删除:
g.dispose();
view.repaint();
切勿释放不是创建的 GUI 对象。此外,repaint()
将在绘制点后删除您的点,因为它调用刷新图像的paint()
。您的观点不会刷新,因为它不包含在paint
中。另请注意,您在帧上定义鼠标事件,并在view
上应用坐标。
好的,我只是想出了问题:我每次点击都会实例化一个新类。为了解决它,我只是改变了
MyCanvas a = new MyCanvas();
a.addNewElement(e.getPoint().x,e.getPoint().y);
自
canvas.addNewElement(e.getPoint().x,e.getPoint().y);