见//处注释importjava.awt.*;importjava.awt.event.*;importjava.awt.geom.*;importjava.io.*;importjava.util.*;importjavax.swing.*;classfextendsJFrame{JButtonbtn=newJButton("清...
见//处注释
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
class f extends JFrame{
JButton btn=new JButton("清除");
JButton btn1=new JButton("画直线");
JButton btn2=new JButton("画圆");
JButton btn3=new JButton("画矩形");
DrawPane p;
f()//构造函数
{
p=new DrawPane();
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
p.repaint();
}
});
getContentPane().setLayout(new BorderLayout());//为什么此处BorderLayout换成flowlayout就不能运行了,还有该如何添加其他诸如画圆之类的按钮
getContentPane().add(p,"Center");
getContentPane().add(btn,"North");
getContentPane().add(btn1,"North");
getContentPane().add(btn2,"North");
getContentPane().add(btn3,"North");
setSize(500,400);
setVisible(true);}
public static void main(String[] args)
{
new f();
}
int flag=0;
class DrawPane extends JPanel{ int x0, y0;
int x1, y1;
boolean first=true;
public DrawPane() {x0=0;y0=0;
x1=0;y1=0;
MouseAdapter adapter=new MouseAdapter(){
public void mouseDragged(MouseEvent e){ Graphics g=getGraphics(); if(flag==0) {
if(first==true){ System.out.println("try");
x1 = (int)e.getX();
y1 = (int)e.getY();
draw(g);
first=false;}
else{x0=x1;
y0=y1;
x1=e.getX();
y1=e.getY();
draw(g);}}}
public void mousePressed(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1){x0=x1=(int)e.getX();
y0=y1=(int)e.getY();}}
public void mouseReleased(MouseEvent e){if(e.getButton()==MouseEvent.BUTTON1){x0=x1=y1=y0=0;}
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);}
public void draw(Graphics g)
{g.drawLine(x0, y0, x1, y1);}
}}
展开