实现效果
点击“自己取点”按钮后,即可在myframe上自己绘制点,点坐标将会记录在ArrayList P1中 。
代码
MouseAdapter类
package Java_GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseAdapater {
JButton btn01=new JButton("自己取点");
MyFrame myframe;
public static void main(String[] args) {
MouseAdapater mouseAdapater = new MouseAdapater();
mouseAdapater.init();
}
public void init(){
myframe=new MyFrame();
myframe.setVisible(true);
myframe.setBounds(200, 200, 760, 480);
myframe.setLayout(new FlowLayout());
btn01.setBounds(200, 5, 150, 30);
myframe.add(btn01);
myframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
btn01.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getSource().equals(btn01)){
myframe.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getSource().equals(myframe)){
addPoint(new Point(e.getX(),e.getY()));
myframe.repaint();
}
}
});
}
}
});
}
public void addPoint(Point point){
myframe.P1.add(point);
}
}
MyFrame类
package Java_GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseAdapater {
JButton btn01=new JButton("自己取点");
MyFrame myframe;
public static void main(String[] args) {
MouseAdapater mouseAdapater = new MouseAdapater();
mouseAdapater.init();
}
public void init(){
myframe=new MyFrame();
myframe.setVisible(true);
myframe.setBounds(200, 200, 760, 480);
myframe.setLayout(new FlowLayout());
btn01.setBounds(200, 5, 150, 30);
myframe.add(btn01);
myframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
btn01.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getSource().equals(btn01)){
myframe.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getSource().equals(myframe)){
addPoint(new Point(e.getX(),e.getY()));
myframe.repaint();
}
}
});
}
}
});
}
public void addPoint(Point point){
myframe.P1.add(point);
}
}
|