package cao;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class cao4 extends JFrame
{
JPanel jp;
public Color color;
public JLabel jl;
public int x1=0,y1=0;
public cao4()
{
super("鼠标电击事件");
jl=new JLabel();
getContentPane().add(jl,BorderLayout.SOUTH);
jp=new JPanel(new FlowLayout());
getContentPane().add(jp,BorderLayout.CENTER);
addMouseMotionListener(new mc());
setSize(500,500);
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(color);
g.fillOval(x1-50,y1-50,100,100);
}
public static void main(String[] args)
{
cao4 mycao4=new cao4();
mycao4.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class mc extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent event)
{
x1=event.getX();
y1=event.getY();
color=Color.red;
repaint();
}
public void mouseMoved(MouseEvent event)
{
x1=event.getX();
y1=event.getY();
color=Color.black;
repaint();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
就是写成这样就错
package cao;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class cao4 extends JFrame
{
JPanel jp;
public Color color;
public JLabel jl;
public int x1=0,y1=0;
public cao4()
{
super("鼠标电击事件");
jl=new JLabel();
getContentPane().add(jl,BorderLayout.SOUTH);
jp=new JPanel(new FlowLayout());
getContentPane().add(jp,BorderLayout.CENTER);
addMouseMotionListener(new mc());
setSize(500,500);
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(color);
g.fillOval(x1-50,y1-50,100,100);
}
public static void main(String[] args)
{
cao4 mycao4=new cao4();
mycao4.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class mc extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent event)
{
x1=event.getX();
y1=event.getY();
color=Color.red;
repaint();
}
public void mouseMoved(MouseEvent event)
{
x1=event.getX();
y1=event.getY();
color=Color.black;
repaint();
}
}
为什么?
----------------解决方案--------------------------------------------------------
那个类是个内部类,不能拿出来.
在你后面的程序里x1 y1 color都没定义 没法传递
而如果写成内部类,就能访问在主类里的x1 y1 color
内部类对象能够访问创建它的对象的实现--包括那些私有数据.
----------------解决方案--------------------------------------------------------