画板の開発_リスニング_再描画_キュー
import java.awt.Graphics;
import java.awt.event.MouseEvent;
public class DrawFrame extends javax.swing.JFrame{
public int x1,y1,x2,y2;
public int count;
public Graphics g;
class Shape{
public int x1,y1,x2,y2;
}
// ,
public java.util.ArrayList<Shape> shapes = new java.util.ArrayList();
//
public void drawUI(){
this.setTitle(" ");
this.setBounds(150,25,700,700);
//
this.setResizable(false);
this.addMouseListener(new java.awt.event.MouseAdapter(){
public void mouseReleased(MouseEvent e){
onReleased(e);
}
});
// ,
this.setDefaultCloseOperation(3);
//
this.setVisible(true);
//
g = this.getGraphics();
}
private void onReleased(MouseEvent e) {
if(count == 0){
x1 = e.getX();
y1 = e.getY();
count++;
}else if(count == 1){
x2 = e.getX();
y2 = e.getY();
count--;
g.drawLine(x1, y1, x2, y2);
//
Shape shape = new Shape();
shape.x1 = x1;
shape.y1 = y1;
shape.x2 = x2;
shape.y2 = y2;
shapes.add(shape);
}
}
//
public void paint(Graphics g){
super.paint(g);
for(int i=0;i<shapes.size();i++){
Shape s = shapes.get(i);
g.drawLine(s.x1, s.y1, s.x2, s.y2);
}
}
//
public static void main(String[] args) {
DrawFrame df = new DrawFrame();
df.drawUI();
}
}
まとめ:1、座標のデータを配列やキューに格納する必要があります.そうしないと、再描画するときは最後の直線の座標しか覚えられません.
2,内部クラス,匿名クラスはコードの簡明化に有利である.