每当我在点击的同一位置点击鼠标时,我试图在框架上画一个点。 我编写/复制的代码调用绘图函数,但没有绘制点,我无法弄清楚问题。这是代码:
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);
}
}
答案 0 :(得分:0)
卸下:
g.dispose();
view.repaint();
永远不要丢弃您不创建的GUI对象。此外,repaint()
会在绘制后移除您的点,因为它会调用刷新图像的paint()
。您的观点不会刷新,因为它不包含在paint
中。另请注意,您在框架上定义了鼠标事件,并在view
上应用了坐标。
答案 1 :(得分:0)
好的,我只是搞清楚了问题:我每次点击都会实例化一个新课程。为了解决这个问题,我刚刚改变了
MyCanvas a = new MyCanvas();
a.addNewElement(e.getPoint().x,e.getPoint().y);
到
canvas.addNewElement(e.getPoint().x,e.getPoint().y);