我要实现边拖动边绘画一系列连续的点,下面是我的源码,可是不能实现,请高手帮忙看看!谢谢!import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Mousedrag
{
public static void main(String args[])
{
frame f=new frame();
f.setSize(600,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
class frame extends JFrame implements ActionListener,MouseMotionListener
{
static int ch=1,x=0,y=0;
JPanel panel=new JPanel();
JButton red=new JButton("red");
JButton green=new JButton("green");
JButton blue=new JButton("blue");
colorCanvas can=new colorCanvas();
frame()
{
panel.add(red);
panel.add(green);
panel.add(blue);
green.setBackground(Color.green);
red.setBackground(Color.red);
blue.setBackground(Color.blue);
green.addActionListener(this);
red.addActionListener(this);
blue.addActionListener(this);
add(panel,BorderLayout.SOUTH);
add(can,BorderLayout.CENTER);
can.addMouseMotionListener(this);
pack();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==red)
{
ch=1;
can.repaint();
}
if(e.getSource()==green)
{
ch=2;
can.repaint();
}
if(e.getSource()==blue)
{
ch=3;
can.repaint();
}
}
public void mouseDragged(MouseEvent e)
{
x=e.getX();
y=e.getY();
can.repaint();
}
public void mouseMoved(MouseEvent e){}
class colorCanvas extends Canvas
{
colorCanvas()
{
setBackground(Color.white);
setSize(300,200);
}
public void paint(Graphics g)
{
if(ch==1)
g.setColor(Color.red);
else
if(ch==2)
g.setColor(Color.green);
else
g.setColor(Color.blue);
g.drawLine(x,y,x,y);//实现边拖动边绘画一个点
}
}
}
import javax.swing.*;
import java.awt.event.*;
public class Mousedrag
{
public static void main(String args[])
{
frame f=new frame();
f.setSize(600,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
class frame extends JFrame implements ActionListener,MouseMotionListener
{
static int ch=1,x=0,y=0;
JPanel panel=new JPanel();
JButton red=new JButton("red");
JButton green=new JButton("green");
JButton blue=new JButton("blue");
colorCanvas can=new colorCanvas();
frame()
{
panel.add(red);
panel.add(green);
panel.add(blue);
green.setBackground(Color.green);
red.setBackground(Color.red);
blue.setBackground(Color.blue);
green.addActionListener(this);
red.addActionListener(this);
blue.addActionListener(this);
add(panel,BorderLayout.SOUTH);
add(can,BorderLayout.CENTER);
can.addMouseMotionListener(this);
pack();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==red)
{
ch=1;
can.repaint();
}
if(e.getSource()==green)
{
ch=2;
can.repaint();
}
if(e.getSource()==blue)
{
ch=3;
can.repaint();
}
}
public void mouseDragged(MouseEvent e)
{
x=e.getX();
y=e.getY();
can.repaint();
}
public void mouseMoved(MouseEvent e){}
class colorCanvas extends Canvas
{
colorCanvas()
{
setBackground(Color.white);
setSize(300,200);
}
public void paint(Graphics g)
{
if(ch==1)
g.setColor(Color.red);
else
if(ch==2)
g.setColor(Color.green);
else
g.setColor(Color.blue);
g.drawLine(x,y,x,y);//实现边拖动边绘画一个点
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货