当前位置: 代码迷 >> J2SE >> 在jpanel中绘图如何不行啊
  详细解决方案

在jpanel中绘图如何不行啊

热度:283   发布时间:2016-04-24 15:26:33.0
在jpanel中绘图怎么不行啊?
lass   JPanels   extends   JPanel   implements   MouseListener
{
  public   Graphics   g1=this.getGraphics();;
 
  public JPanels   ()
  {    
  this.addMouseListener(this);
  }
  protected   void   paintComponent(Graphics   g)
  {
  super.paintComponent(g);
  for(int   i=0;i <15;i++)
  {
  g.drawLine(20,(i+1)*20,300,(i+1)*20);
                g.drawLine((i+1)*20,20,(i+1)*20,300);
  }
  }
public   void     draw(int   x,int   y)
  {
  g1.setColor(Color.BLUE);      
  g1.drawOval(x-5,y-5,10,10);
  g1.fillOval(x-5,y-5,10,10);
  g1.dispose();
  }
public   void   mouseClicked(MouseEvent   e)
  {
      int   x=e.getX()/20;
      int   y=e.getY()/20;
      draw(x*20,y*20);
  }
public   void   mousePressed(MouseEvent   e)
{
}
public   void   mouseReleased(MouseEvent   e)
{
}
public   void   mouseEntered(MouseEvent   e)
{
}
public   void   mouseExited(MouseEvent   e)
{
}
}

------解决方案--------------------
替楼主测试了一下代码通过。结贴吧


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test
{
public static void main(String[]args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
JPanels t = new JPanels();
f.getContentPane().add(t);
f.show();

}
}
class JPanels extends JPanel implements MouseListener
{
public Graphics g1=this.getGraphics();;

public JPanels ()
{
this.addMouseListener(this);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i=0;i <15;i++)
{
g.drawLine(20,(i+1)*20,300,(i+1)*20);
g.drawLine((i+1)*20,20,(i+1)*20,300);
}
}
public void draw(int x,int y)
{
g1.setColor(Color.BLUE);
g1.drawOval(x-5,y-5,10,10);
g1.fillOval(x-5,y-5,10,10);
g1.dispose();
}
public void mouseClicked(MouseEvent e)
{
int x=e.getX()/20;
int y=e.getY()/20;
draw(x*20,y*20);
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
}