我想在框架上畫一點,每當我點擊鼠標點擊它的相同位置。 我寫/複製的代碼調用繪圖函數,但不繪製點,我無法找出問題。這是代碼:爲什麼這個函數沒有吸引人的地方?
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);
}
}
所以,要創建一個完全新的** **帆布'了'上點擊鼠標;然後你不用那個畫布做任何事情。你期望從那發生什麼?提示:考慮操縱那個'canvas'實例... – GhostCat