import java.awt.*;
import java.awt.event.*;
public class myTest extends Frame{
public myTest(){
myCanvas mC = new myCanvas();
add(mC);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[]){
myTest mT = new myTest();
mT.setSize(300, 300);
mT.setVisible(true);
}
}
class myCanvas extends Canvas{
private int x1=0, y1=0, x2=100, y2=100;
private Graphics mg = null; public void paint(Graphics g){
mg = g; addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e){
x2 = e.getX();
y2 = e.getY(); //repaint();
mg.drawLine(x1, y1, x2, y2);
}
});
//mg.drawLine(x1, y1, x2, y2);
//g.drawLine(x1, y1, x2, y2);
}
}
我在上面程序中,内置类里面调用mg.drawLine()方法为什么不能划线,而在内置类中调用repaint()方法就能实现划线???
import java.awt.event.*;
public class myTest extends Frame{
public myTest(){
myCanvas mC = new myCanvas();
add(mC);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[]){
myTest mT = new myTest();
mT.setSize(300, 300);
mT.setVisible(true);
}
}
class myCanvas extends Canvas{
private int x1=0, y1=0, x2=100, y2=100;
private Graphics mg = null; public void paint(Graphics g){
mg = g; addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e){
x2 = e.getX();
y2 = e.getY(); //repaint();
mg.drawLine(x1, y1, x2, y2);
}
});
//mg.drawLine(x1, y1, x2, y2);
//g.drawLine(x1, y1, x2, y2);
}
}
我在上面程序中,内置类里面调用mg.drawLine()方法为什么不能划线,而在内置类中调用repaint()方法就能实现划线???
import java.awt.event.*;import javax.swing.JFrame;public class myTest extends JFrame
{
public myTest()
{
myCanvas mC = new myCanvas();
add(mC);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
myTest mT = new myTest();
mT.setSize(300, 300);
mT.setVisible(true);
}
}class myCanvas extends Canvas implements MouseListener
{
private int x1 = 0, y1 = 0, x2 = 100, y2 = 100;
public myCanvas()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
g.drawLine(x1, y1, x2, y2);
} public void mouseClicked(MouseEvent e)
{
} public void mouseEntered(MouseEvent e)
{
} public void mouseExited(MouseEvent e)
{
} public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();
} public void mouseReleased(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}
}